diff --git a/.github/workflows/qemu.yaml b/.github/workflows/qemu.yaml index 534c46f3c206a1..6d61a2bdaee1f8 100644 --- a/.github/workflows/qemu.yaml +++ b/.github/workflows/qemu.yaml @@ -60,8 +60,6 @@ jobs: build \ " - name: Run all tests - # Disabled being tracked here: https://github.com/project-chip/connectedhomeip/issues/32587 - if: false run: | src/test_driver/esp32/run_qemu_image.py \ --verbose \ diff --git a/.github/workflows/third-party-check.yaml b/.github/workflows/third-party-check.yaml new file mode 100644 index 00000000000000..575e7e3c9c7137 --- /dev/null +++ b/.github/workflows/third-party-check.yaml @@ -0,0 +1,34 @@ +# Copyright (c) 2024 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: Check for Unintentional Submodule Updates + +on: + pull_request: + branches-ignore: + - 'dependabot/**' + paths: + - "third_party/**" + - ".gitmodules" + +jobs: + check-submodule-update-label: + name: Check For Submodule Update Label + runs-on: ubuntu-latest + if: "!contains(github.event.pull_request.labels.*.name, 'changing-submodules-on-purpose')" + steps: + - name: Error Message + run: echo This pull request attempts to update submodules without the changing-submodules-on-purpose label. Please apply that label if the changes are intentional, or remove those changes. + - name: Fail Job + run: exit 1 diff --git a/docs/guides/esp32/README.md b/docs/guides/esp32/README.md index e487a58f318591..443058a17b07aa 100644 --- a/docs/guides/esp32/README.md +++ b/docs/guides/esp32/README.md @@ -18,3 +18,4 @@ example on ESP32 series of SoCs - [Matter OTA](ota.md) - [Generating and Using ESP Secure Cert Partition](secure_cert_partition.md) - [BLE Settings](ble_settings.md) +- [Providers](providers.md) diff --git a/docs/guides/esp32/factory_data.md b/docs/guides/esp32/factory_data.md index 9ea2e12d1a87d3..638d3aa134b11f 100644 --- a/docs/guides/esp32/factory_data.md +++ b/docs/guides/esp32/factory_data.md @@ -44,13 +44,9 @@ Following data can be added to the manufacturing partition using - Serial Number - Unique identifier -- Device information - - Fixed Labels - - Supported locales - - Supported calendar types - - Supported modes - - Note: As per spec at max size of label should be 64 and `\0` will be - added at the end. +- Supported modes + - Note: As per spec at max size of label should be 64 and `\0` will be + added at the end. ### Configuration Options diff --git a/docs/guides/esp32/providers.md b/docs/guides/esp32/providers.md new file mode 100644 index 00000000000000..59b91b624a49fc --- /dev/null +++ b/docs/guides/esp32/providers.md @@ -0,0 +1,76 @@ +## Providers Implemented for ESP32 Platform + +The ESP32 platform has implemented several providers that can be used with data +stored in the factory or by setting fixed data. + +Below are the providers that have been implemented: + +- [Commissionable Data Provider](https://github.com/project-chip/connectedhomeip/blob/master/src/platform/ESP32/ESP32FactoryDataProvider.h#L47) + This provider reads the discriminator and setup pincode related parameters + from the factory partition. +- [Device Attestation Credentials Provider](https://github.com/project-chip/connectedhomeip/blob/master/src/platform/ESP32/ESP32FactoryDataProvider.h#L56) + This provider manages the attestation data. +- [Device Instance Info Provider](https://github.com/project-chip/connectedhomeip/blob/master/src/platform/ESP32/ESP32FactoryDataProvider.h#L86) + This provider reads basic device information from the factory partition. +- [Device Info Provider](https://github.com/project-chip/connectedhomeip/blob/master/src/platform/ESP32/ESP32DeviceInfoProvider.h#L31) + This provider provides fixed labels, supported calendar types, and supported + locales from the factory partition. +- [Supported Modes](https://github.com/project-chip/connectedhomeip/blob/master/examples/platform/esp32/mode-support/static-supported-modes-manager.h#L28) + This provider offers the supported modes for the mode-select cluster. + +More information can be found in the [factory data guide](factory_data.md). + +### Device Info Provider + +Currently, there are two implementations for this provider: + +1. [Reads data stored in the factory partition](https://github.com/project-chip/connectedhomeip/blob/master/src/platform/ESP32/ESP32FactoryDataProvider.h#L56) + _(This will be deprecated in the future)_ +2. [Provides APIs to set fixed data that gets read later](https://github.com/project-chip/connectedhomeip/blob/master/src/platform/ESP32/StaticESP32DeviceInfoProvider.h) + +- New products should use the `StaticESP32DeviceInfoProvider`. Utilize the + `Set...()` APIs to set the fixed data. +- Existing products using the first implementation can continue to use it if + they do not wish to change the data. +- For products using the first implementation and wanting to change the fixed + data via OTA, they should switch to the second implementation in the OTA + image and use the `Set...()` APIs to set the fixed data. + +#### Example: + +```cpp +#include + +DeviceLayer::StaticESP32DeviceInfoProvider deviceInfoProvider; + +// Define array for Supported Calendar Types +using namespace chip::app::Clusters::TimeFormatLocalization::CalendarTypeEnum; +CalendarTypeEnum supportedCalendarTypes[] = { + CalendarTypeEnum::kGregorian, CalendarTypeEnum::kCoptic, + CalendarTypeEnum::kEthiopian, CalendarTypeEnum::kChinese, +}; + +// Define array for Supported Locales +const char* supportedLocales[] = { + "en-US", + "en-EU", +}; + +// Define array for Fixed labels { EndpointId, Label, Value } +struct StaticESP32DeviceInfoProvider::FixedLabelEntry fixedLabels[] = { + { 0, "Room", "Bedroom 2" }, + { 0, "Orientation", "North" }, + { 0, "Direction", "Up" }, +}; + +Span sSupportedCalendarTypes(supportedCalendarTypes); +Span sSupportedLocales(supportedLocales); +Span sFixedLabels(fixedLabels); + +{ + deviceInfoProvider.SetSupportedLocales(sSupportedLocales); + deviceInfoProvider.SetSupportedCalendarTypes(sSupportedCalendarTypes); + deviceInfoProvider.SetFixedLabels(sFixedLabels); + DeviceLayer::SetDeviceInfoProvider(&deviceInfoProvider); +} +``` diff --git a/docs/tools/index.md b/docs/tools/index.md index 14ab8640c61bae..003573ed5ebb14 100644 --- a/docs/tools/index.md +++ b/docs/tools/index.md @@ -28,7 +28,6 @@ Source files for these tools are located at `scripts/tools`. ../scripts/tools/memory/README ../scripts/tools/spake2p/README -../src/tools/interop/idt/README ``` diff --git a/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp b/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp index 95f50acce7c4ef..39e6a91bcb1b04 100644 --- a/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp +++ b/examples/all-clusters-app/all-clusters-common/src/binding-handler.cpp @@ -80,7 +80,7 @@ static void BoundDeviceChangedHandler(const EmberBindingTableEntry & binding, ch } if (binding.type == MATTER_UNICAST_BINDING && binding.local == 1 && - (!binding.clusterId.HasValue() || binding.clusterId.Value() == Clusters::OnOff::Id)) + binding.clusterId.value_or(Clusters::OnOff::Id) == Clusters::OnOff::Id) { auto onSuccess = [](const ConcreteCommandPath & commandPath, const StatusIB & status, const auto & dataResponse) { ChipLogProgress(NotSpecified, "OnOff command succeeds"); diff --git a/examples/all-clusters-app/ameba/main/BindingHandler.cpp b/examples/all-clusters-app/ameba/main/BindingHandler.cpp index b00322b44e4f0b..1c0fef656c7913 100644 --- a/examples/all-clusters-app/ameba/main/BindingHandler.cpp +++ b/examples/all-clusters-app/ameba/main/BindingHandler.cpp @@ -194,7 +194,7 @@ CHIP_ERROR BindingGroupBindCommandHandler(int argc, char ** argv) entry->fabricIndex = atoi(argv[0]); entry->groupId = atoi(argv[1]); entry->local = 1; // Hardcoded to endpoint 1 for now - entry->clusterId.SetValue(6); // Hardcoded to OnOff cluster for now + entry->clusterId.emplace(6); // Hardcoded to OnOff cluster for now DeviceLayer::PlatformMgr().ScheduleWork(BindingWorkerFunction, reinterpret_cast(entry)); return CHIP_NO_ERROR; @@ -210,7 +210,7 @@ CHIP_ERROR BindingUnicastBindCommandHandler(int argc, char ** argv) entry->nodeId = atoi(argv[1]); entry->local = 1; // Hardcoded to endpoint 1 for now entry->remote = atoi(argv[2]); - entry->clusterId.SetValue(6); // Hardcode to OnOff cluster for now + entry->clusterId.emplace(6); // Hardcode to OnOff cluster for now DeviceLayer::PlatformMgr().ScheduleWork(BindingWorkerFunction, reinterpret_cast(entry)); return CHIP_NO_ERROR; diff --git a/examples/all-clusters-app/asr/include/AppTask.h b/examples/all-clusters-app/asr/include/AppTask.h index 210fd5a6fc7032..42cd6ae1541045 100755 --- a/examples/all-clusters-app/asr/include/AppTask.h +++ b/examples/all-clusters-app/asr/include/AppTask.h @@ -19,7 +19,7 @@ #pragma once #include "AppEvent.h" -#include +#include #include #include #include diff --git a/examples/all-clusters-app/cc13x4_26x4/main/AppTask.cpp b/examples/all-clusters-app/cc13x4_26x4/main/AppTask.cpp index 3e338474833eab..6fc9642b8c063a 100644 --- a/examples/all-clusters-app/cc13x4_26x4/main/AppTask.cpp +++ b/examples/all-clusters-app/cc13x4_26x4/main/AppTask.cpp @@ -54,12 +54,6 @@ #define APP_TASK_STACK_SIZE (5000) #define APP_TASK_PRIORITY 4 #define APP_EVENT_QUEUE_SIZE 10 - -#if (CHIP_CONFIG_ENABLE_ICD_SERVER == 1) -#define LED_ENABLE 0 -#else -#define LED_ENABLE 1 -#endif #define BUTTON_ENABLE 1 using namespace ::chip; @@ -68,7 +62,6 @@ using namespace ::chip::DeviceLayer; static TaskHandle_t sAppTaskHandle; static QueueHandle_t sAppEventQueue; - static Button_Handle sAppLeftHandle; static Button_Handle sAppRightHandle; static DeviceInfoProviderImpl sExampleDeviceInfoProvider; diff --git a/examples/all-clusters-app/cc13x4_26x4/main/Globals.cpp b/examples/all-clusters-app/cc13x4_26x4/main/Globals.cpp index 01a945e1a33d12..00fd64e3125218 100644 --- a/examples/all-clusters-app/cc13x4_26x4/main/Globals.cpp +++ b/examples/all-clusters-app/cc13x4_26x4/main/Globals.cpp @@ -18,5 +18,7 @@ #include "Globals.h" +#if (LED_ENABLE == 1) LED_Handle sAppRedHandle; LED_Handle sAppGreenHandle; +#endif diff --git a/examples/all-clusters-app/cc13x4_26x4/main/include/Globals.h b/examples/all-clusters-app/cc13x4_26x4/main/include/Globals.h index 4cdc0b69174d60..8320b01ac79bb7 100644 --- a/examples/all-clusters-app/cc13x4_26x4/main/include/Globals.h +++ b/examples/all-clusters-app/cc13x4_26x4/main/include/Globals.h @@ -31,5 +31,12 @@ void cc13xx_26xxLog(const char * aFormat, ...); #ifdef __cplusplus } #endif + +#if (CHIP_CONFIG_ENABLE_ICD_SERVER == 1) +#define LED_ENABLE 0 +#else +#define LED_ENABLE 1 +#endif + extern LED_Handle sAppRedHandle; extern LED_Handle sAppGreenHandle; diff --git a/examples/all-clusters-app/infineon/psoc6/include/AppTask.h b/examples/all-clusters-app/infineon/psoc6/include/AppTask.h index 9fade8c82356bf..aa031fe3ba4b52 100644 --- a/examples/all-clusters-app/infineon/psoc6/include/AppTask.h +++ b/examples/all-clusters-app/infineon/psoc6/include/AppTask.h @@ -26,7 +26,7 @@ #include "AppEvent.h" #include "FreeRTOS.h" #include "timers.h" // provides FreeRTOS timer support -#include +#include #include // Application-defined error codes in the CHIP_ERROR space. diff --git a/examples/all-clusters-app/nxp/mw320/binding-handler.cpp b/examples/all-clusters-app/nxp/mw320/binding-handler.cpp index ace7da026b253a..e4a2df4d387249 100644 --- a/examples/all-clusters-app/nxp/mw320/binding-handler.cpp +++ b/examples/all-clusters-app/nxp/mw320/binding-handler.cpp @@ -81,7 +81,7 @@ static void BoundDeviceChangedHandler(const EmberBindingTableEntry & binding, ch } if (binding.type == MATTER_UNICAST_BINDING && binding.local == 1 && - (!binding.clusterId.HasValue() || binding.clusterId.Value() == Clusters::OnOff::Id)) + binding.clusterId.value_or(Clusters::OnOff::Id) == Clusters::OnOff::Id) { auto onSuccess = [](const ConcreteCommandPath & commandPath, const StatusIB & status, const auto & dataResponse) { ChipLogProgress(NotSpecified, "OnOff command succeeds"); diff --git a/examples/all-clusters-minimal-app/asr/include/AppTask.h b/examples/all-clusters-minimal-app/asr/include/AppTask.h index 97d1bfe538fb64..7e168e14d5a854 100755 --- a/examples/all-clusters-minimal-app/asr/include/AppTask.h +++ b/examples/all-clusters-minimal-app/asr/include/AppTask.h @@ -24,7 +24,7 @@ #include "AppEvent.h" #include "FreeRTOS.h" #include "timers.h" // provides FreeRTOS timer support -#include +#include #include // Application-defined error codes in the CHIP_ERROR space. diff --git a/examples/all-clusters-minimal-app/infineon/psoc6/include/AppTask.h b/examples/all-clusters-minimal-app/infineon/psoc6/include/AppTask.h index 6dbd906b8104d6..b5102a153e25e1 100644 --- a/examples/all-clusters-minimal-app/infineon/psoc6/include/AppTask.h +++ b/examples/all-clusters-minimal-app/infineon/psoc6/include/AppTask.h @@ -26,7 +26,7 @@ #include "AppEvent.h" #include "FreeRTOS.h" #include "timers.h" // provides FreeRTOS timer support -#include +#include #include // Application-defined error codes in the CHIP_ERROR space. diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/bluetooth/BluetoothManager.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/bluetooth/BluetoothManager.kt index 16d0f745b5f70f..61e95838b1cc61 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/bluetooth/BluetoothManager.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/bluetooth/BluetoothManager.kt @@ -138,6 +138,12 @@ class BluetoothManager : BleCallback { private val coroutineContinuation = continuation + private val STATE_INIT = 1 + private val STATE_DISCOVER_SERVICE = 2 + private val STATE_REQUEST_MTU = 3 + + private var mState = STATE_INIT + override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) { super.onConnectionStateChange(gatt, status, newState) Log.i( @@ -148,21 +154,31 @@ class BluetoothManager : BleCallback { if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) { Log.i("$TAG|onConnectionStateChange", "Discovering Services...") + mState = STATE_DISCOVER_SERVICE gatt?.discoverServices() } } override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) { Log.d(TAG, "${gatt?.device?.name}.onServicesDiscovered status = $status") + if (mState != STATE_DISCOVER_SERVICE) { + Log.d(TAG, "Invalid state : $mState") + return + } wrappedCallback.onServicesDiscovered(gatt, status) Log.i("$TAG|onServicesDiscovered", "Services Discovered") + mState = STATE_REQUEST_MTU gatt?.requestMtu(247) } override fun onMtuChanged(gatt: BluetoothGatt?, mtu: Int, status: Int) { Log.d(TAG, "${gatt?.device?.name}.onMtuChanged: connecting to CHIP device") super.onMtuChanged(gatt, mtu, status) + if (mState != STATE_REQUEST_MTU) { + Log.d(TAG, "Invalid state : $mState") + return + } wrappedCallback.onMtuChanged(gatt, mtu, status) if (coroutineContinuation.isActive) { coroutineContinuation.resume(gatt) diff --git a/examples/chef/silabs/include/AppTask.h b/examples/chef/silabs/include/AppTask.h index 578d0a17834d29..b6c6d8a271df22 100644 --- a/examples/chef/silabs/include/AppTask.h +++ b/examples/chef/silabs/include/AppTask.h @@ -28,7 +28,7 @@ #include "AppEvent.h" #include "BaseApplication.h" -#include +#include #include #include #include diff --git a/examples/light-switch-app/ameba/main/BindingHandler.cpp b/examples/light-switch-app/ameba/main/BindingHandler.cpp index 0ffcddc67839eb..580b2bec197a44 100644 --- a/examples/light-switch-app/ameba/main/BindingHandler.cpp +++ b/examples/light-switch-app/ameba/main/BindingHandler.cpp @@ -250,7 +250,7 @@ CHIP_ERROR BindingGroupBindCommandHandler(int argc, char ** argv) entry->fabricIndex = atoi(argv[0]); entry->groupId = atoi(argv[1]); entry->local = 1; // Hardcoded to endpoint 1 for now - entry->clusterId.SetValue(6); // Hardcoded to OnOff cluster for now + entry->clusterId.emplace(6); // Hardcoded to OnOff cluster for now DeviceLayer::PlatformMgr().ScheduleWork(BindingWorkerFunction, reinterpret_cast(entry)); return CHIP_NO_ERROR; @@ -266,7 +266,7 @@ CHIP_ERROR BindingUnicastBindCommandHandler(int argc, char ** argv) entry->nodeId = atoi(argv[1]); entry->local = 1; // Hardcoded to endpoint 1 for now entry->remote = atoi(argv[2]); - entry->clusterId.SetValue(6); // Hardcode to OnOff cluster for now + entry->clusterId.emplace(6); // Hardcode to OnOff cluster for now DeviceLayer::PlatformMgr().ScheduleWork(BindingWorkerFunction, reinterpret_cast(entry)); return CHIP_NO_ERROR; diff --git a/examples/light-switch-app/asr/include/AppTask.h b/examples/light-switch-app/asr/include/AppTask.h index c103fd6f60944e..60525c1975ff43 100755 --- a/examples/light-switch-app/asr/include/AppTask.h +++ b/examples/light-switch-app/asr/include/AppTask.h @@ -25,7 +25,7 @@ #include "FreeRTOS.h" #include "timers.h" // provides FreeRTOS timer support -#include +#include #include // Application-defined error codes in the CHIP_ERROR space. diff --git a/examples/light-switch-app/asr/src/BindingHandler.cpp b/examples/light-switch-app/asr/src/BindingHandler.cpp index 10ee9e2332af30..b924292b42eef6 100644 --- a/examples/light-switch-app/asr/src/BindingHandler.cpp +++ b/examples/light-switch-app/asr/src/BindingHandler.cpp @@ -280,8 +280,8 @@ void BindingHandler::PrintBindingTable() \t+ ClusterId %d \n \ \t+ RemoteEndpointId %d \n \ \t+ NodeId %d", - (int) entry.fabricIndex, (int) entry.local, (int) entry.clusterId.Value(), (int) entry.remote, - (int) entry.nodeId); + (int) entry.fabricIndex, (int) entry.local, (int) entry.clusterId.value_or(kInvalidClusterId), + (int) entry.remote, (int) entry.nodeId); break; case MATTER_MULTICAST_BINDING: ASR_LOG("[%d] GROUP:", i++); diff --git a/examples/light-switch-app/esp32/main/BindingHandler.cpp b/examples/light-switch-app/esp32/main/BindingHandler.cpp index 9602cd1a534414..cc1a66a1e28878 100644 --- a/examples/light-switch-app/esp32/main/BindingHandler.cpp +++ b/examples/light-switch-app/esp32/main/BindingHandler.cpp @@ -248,7 +248,7 @@ CHIP_ERROR BindingGroupBindCommandHandler(int argc, char ** argv) entry->fabricIndex = atoi(argv[0]); entry->groupId = atoi(argv[1]); entry->local = 1; // Hardcoded to endpoint 1 for now - entry->clusterId.SetValue(6); // Hardcoded to OnOff cluster for now + entry->clusterId.emplace(6); // Hardcoded to OnOff cluster for now DeviceLayer::PlatformMgr().ScheduleWork(BindingWorkerFunction, reinterpret_cast(entry)); return CHIP_NO_ERROR; @@ -264,7 +264,7 @@ CHIP_ERROR BindingUnicastBindCommandHandler(int argc, char ** argv) entry->nodeId = atoi(argv[1]); entry->local = 1; // Hardcoded to endpoint 1 for now entry->remote = atoi(argv[2]); - entry->clusterId.SetValue(6); // Hardcode to OnOff cluster for now + entry->clusterId.emplace(6); // Hardcode to OnOff cluster for now DeviceLayer::PlatformMgr().ScheduleWork(BindingWorkerFunction, reinterpret_cast(entry)); return CHIP_NO_ERROR; diff --git a/examples/light-switch-app/genio/src/BindingHandler.cpp b/examples/light-switch-app/genio/src/BindingHandler.cpp index e988464b331afe..218a44671486d7 100644 --- a/examples/light-switch-app/genio/src/BindingHandler.cpp +++ b/examples/light-switch-app/genio/src/BindingHandler.cpp @@ -247,7 +247,7 @@ CHIP_ERROR BindingGroupBindCommandHandler(int argc, char ** argv) entry->fabricIndex = atoi(argv[0]); entry->groupId = atoi(argv[1]); entry->local = 1; // Hardcoded to endpoint 1 for now - entry->clusterId.SetValue(6); // Hardcoded to OnOff cluster for now + entry->clusterId.emplace(6); // Hardcoded to OnOff cluster for now DeviceLayer::PlatformMgr().ScheduleWork(BindingWorkerFunction, reinterpret_cast(entry)); return CHIP_NO_ERROR; @@ -263,7 +263,7 @@ CHIP_ERROR BindingUnicastBindCommandHandler(int argc, char ** argv) entry->nodeId = atoi(argv[1]); entry->local = 1; // Hardcoded to endpoint 1 for now entry->remote = atoi(argv[2]); - entry->clusterId.SetValue(6); // Hardcode to OnOff cluster for now + entry->clusterId.emplace(6); // Hardcode to OnOff cluster for now DeviceLayer::PlatformMgr().ScheduleWork(BindingWorkerFunction, reinterpret_cast(entry)); return CHIP_NO_ERROR; diff --git a/examples/light-switch-app/infineon/cyw30739/src/AppShellCommands.cpp b/examples/light-switch-app/infineon/cyw30739/src/AppShellCommands.cpp index 91cc0c74176a53..5a63cea5d543d6 100644 --- a/examples/light-switch-app/infineon/cyw30739/src/AppShellCommands.cpp +++ b/examples/light-switch-app/infineon/cyw30739/src/AppShellCommands.cpp @@ -365,7 +365,7 @@ CHIP_ERROR GroupBindCommandHandler(int argc, char ** argv) entry->local = 1; // Hardcoded to endpoint 1 for now entry->fabricIndex = atoi(argv[0]); entry->groupId = atoi(argv[1]); - entry->clusterId.SetValue(atoi(argv[3])); + entry->clusterId.emplace(atoi(argv[3])); DeviceLayer::PlatformMgr().ScheduleWork(BindingHandler::BindingWorkerHandler, reinterpret_cast(entry)); return CHIP_NO_ERROR; @@ -384,7 +384,7 @@ CHIP_ERROR UnicastBindCommandHandler(int argc, char ** argv) entry->fabricIndex = atoi(argv[0]); entry->nodeId = atoi(argv[1]); entry->remote = atoi(argv[2]); - entry->clusterId.SetValue(atoi(argv[3])); + entry->clusterId.emplace(atoi(argv[3])); DeviceLayer::PlatformMgr().ScheduleWork(BindingHandler::BindingWorkerHandler, reinterpret_cast(entry)); return CHIP_NO_ERROR; diff --git a/examples/light-switch-app/infineon/cyw30739/src/BindingHandler.cpp b/examples/light-switch-app/infineon/cyw30739/src/BindingHandler.cpp index 4df68993fddae4..9b03d14745cdf4 100644 --- a/examples/light-switch-app/infineon/cyw30739/src/BindingHandler.cpp +++ b/examples/light-switch-app/infineon/cyw30739/src/BindingHandler.cpp @@ -306,8 +306,8 @@ void BindingHandler::PrintBindingTable() \t+ ClusterId %d \n \ \t+ RemoteEndpointId %d \n \ \t+ NodeId %d \n", - (int) entry.fabricIndex, (int) entry.local, (int) entry.clusterId.Value(), (int) entry.remote, - (int) entry.nodeId); + (int) entry.fabricIndex, (int) entry.local, (int) entry.clusterId.value_or(kInvalidClusterId), + (int) entry.remote, (int) entry.nodeId); break; case MATTER_MULTICAST_BINDING: printf("[%d] GROUP:", i++); diff --git a/examples/light-switch-app/nrfconnect/main/BindingHandler.cpp b/examples/light-switch-app/nrfconnect/main/BindingHandler.cpp index 0d93428f8dca5e..a63488a34e5c2e 100644 --- a/examples/light-switch-app/nrfconnect/main/BindingHandler.cpp +++ b/examples/light-switch-app/nrfconnect/main/BindingHandler.cpp @@ -284,8 +284,8 @@ void BindingHandler::PrintBindingTable() \t+ ClusterId %d \n \ \t+ RemoteEndpointId %d \n \ \t+ NodeId %d", - (int) entry.fabricIndex, (int) entry.local, (int) entry.clusterId.Value(), (int) entry.remote, - (int) entry.nodeId); + (int) entry.fabricIndex, (int) entry.local, (int) entry.clusterId.value_or(kInvalidClusterId), + (int) entry.remote, (int) entry.nodeId); break; case MATTER_MULTICAST_BINDING: LOG_INF("[%d] GROUP:", i++); diff --git a/examples/light-switch-app/silabs/include/AppTask.h b/examples/light-switch-app/silabs/include/AppTask.h index a6a74b4605f52c..71ca4b427bad44 100644 --- a/examples/light-switch-app/silabs/include/AppTask.h +++ b/examples/light-switch-app/silabs/include/AppTask.h @@ -28,7 +28,7 @@ #include "AppEvent.h" #include "BaseApplication.h" -#include +#include #include #include #include diff --git a/examples/light-switch-app/silabs/src/ShellCommands.cpp b/examples/light-switch-app/silabs/src/ShellCommands.cpp index 565f425f8af344..167453906ee32c 100644 --- a/examples/light-switch-app/silabs/src/ShellCommands.cpp +++ b/examples/light-switch-app/silabs/src/ShellCommands.cpp @@ -143,7 +143,7 @@ CHIP_ERROR BindingGroupBindCommandHandler(int argc, char ** argv) entry->fabricIndex = atoi(argv[0]); entry->groupId = atoi(argv[1]); entry->local = 1; // Hardcoded to endpoint 1 for now - entry->clusterId.SetValue(6); // Hardcoded to OnOff cluster for now + entry->clusterId.emplace(6); // Hardcoded to OnOff cluster for now DeviceLayer::PlatformMgr().ScheduleWork(BindingWorkerFunction, reinterpret_cast(entry)); return CHIP_NO_ERROR; @@ -159,7 +159,7 @@ CHIP_ERROR BindingUnicastBindCommandHandler(int argc, char ** argv) entry->nodeId = atoi(argv[1]); entry->local = 1; // Hardcoded to endpoint 1 for now entry->remote = atoi(argv[2]); - entry->clusterId.SetValue(6); // Hardcode to OnOff cluster for now + entry->clusterId.emplace(6); // Hardcode to OnOff cluster for now DeviceLayer::PlatformMgr().ScheduleWork(BindingWorkerFunction, reinterpret_cast(entry)); return CHIP_NO_ERROR; diff --git a/examples/light-switch-app/telink/src/binding-handler.cpp b/examples/light-switch-app/telink/src/binding-handler.cpp old mode 100755 new mode 100644 index 39a8cddc2c60f8..23ab22ff454b98 --- a/examples/light-switch-app/telink/src/binding-handler.cpp +++ b/examples/light-switch-app/telink/src/binding-handler.cpp @@ -243,7 +243,7 @@ CHIP_ERROR BindingGroupBindCommandHandler(int argc, char ** argv) entry->fabricIndex = atoi(argv[0]); entry->groupId = atoi(argv[1]); entry->local = 1; // Hardcoded to endpoint 1 for now - entry->clusterId.SetValue(6); // Hardcoded to OnOff cluster for now + entry->clusterId.emplace(6); // Hardcoded to OnOff cluster for now DeviceLayer::PlatformMgr().ScheduleWork(BindingWorkerFunction, reinterpret_cast(entry)); return CHIP_NO_ERROR; @@ -259,7 +259,7 @@ CHIP_ERROR BindingUnicastBindCommandHandler(int argc, char ** argv) entry->nodeId = atoi(argv[1]); entry->local = 1; // Hardcoded to endpoint 1 for now entry->remote = atoi(argv[2]); - entry->clusterId.SetValue(6); // Hardcode to OnOff cluster for now + entry->clusterId.emplace(6); // Hardcode to OnOff cluster for now DeviceLayer::PlatformMgr().ScheduleWork(BindingWorkerFunction, reinterpret_cast(entry)); return CHIP_NO_ERROR; diff --git a/examples/lighting-app/cc13x4_26x4/src/AppTask.cpp b/examples/lighting-app/cc13x4_26x4/src/AppTask.cpp index bad302bb6b04ff..5b5bb7d7df222f 100644 --- a/examples/lighting-app/cc13x4_26x4/src/AppTask.cpp +++ b/examples/lighting-app/cc13x4_26x4/src/AppTask.cpp @@ -81,9 +81,10 @@ using namespace ::chip::DeviceLayer; static TaskHandle_t sAppTaskHandle; static QueueHandle_t sAppEventQueue; - +#if (LED_ENABLE == 1) static LED_Handle sAppRedHandle; static LED_Handle sAppGreenHandle; +#endif static Button_Handle sAppLeftHandle; static Button_Handle sAppRightHandle; static DeviceInfoProviderImpl sExampleDeviceInfoProvider; diff --git a/examples/lighting-app/infineon/psoc6/include/AppTask.h b/examples/lighting-app/infineon/psoc6/include/AppTask.h index 580744cb2fe2d2..4f6f77663d18a4 100644 --- a/examples/lighting-app/infineon/psoc6/include/AppTask.h +++ b/examples/lighting-app/infineon/psoc6/include/AppTask.h @@ -27,7 +27,7 @@ #include "FreeRTOS.h" #include "timers.h" // provides FreeRTOS timer support -#include +#include #include // Application-defined error codes in the CHIP_ERROR space. diff --git a/examples/lighting-app/silabs/include/AppTask.h b/examples/lighting-app/silabs/include/AppTask.h index 450d9c61b719b4..c42415d8868586 100644 --- a/examples/lighting-app/silabs/include/AppTask.h +++ b/examples/lighting-app/silabs/include/AppTask.h @@ -29,7 +29,7 @@ #include "AppEvent.h" #include "BaseApplication.h" #include "LightingManager.h" -#include +#include #include #include #include diff --git a/examples/lit-icd-app/esp32/main/IcdUatButton.cpp b/examples/lit-icd-app/esp32/main/IcdUatButton.cpp new file mode 100644 index 00000000000000..b45b17c634b877 --- /dev/null +++ b/examples/lit-icd-app/esp32/main/IcdUatButton.cpp @@ -0,0 +1,148 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "IcdUatButton.h" + +#include "driver/gpio.h" +#include "esp_attr.h" +#include "esp_log.h" +#include "freertos/FreeRTOS.h" +#include "freertos/queue.h" +#include "freertos/task.h" +#include "hal/gpio_types.h" +#include + +#define ESP_INTR_FLAG_DEFAULT 0 + +static const char TAG[] = "Button"; +QueueHandle_t UatButton::sEventQueue = nullptr; +TaskHandle_t UatButton::sTaskHandle = nullptr; + +static void IRAM_ATTR gpio_isr_handler(void * arg) +{ + if (UatButton::sEventQueue) + { + UatButton * button = (UatButton *) arg; + button->GpioIntrEnable(false); + xQueueSendFromISR(UatButton::sEventQueue, &button, NULL); + } +} + +void UatButton::RunEventLoop(void * arg) +{ + bool eventDone = true; + UatButton * button = nullptr; + + for (;;) + { + if (xQueueReceive(sEventQueue, &button, portMAX_DELAY) == pdTRUE && button) + { + button->GpioIntrEnable(false); + eventDone = false; + } + while (!eventDone) + { + // GPIO Pull up is enabled so the button is pressed when this value is false. + bool value = gpio_get_level(button->mGpioNum); + switch (button->mState) + { + case ButtonState::kIdle: + button->mState = value == false ? ButtonState::kPressed : ButtonState::kIdle; + break; + case ButtonState::kPressed: + button->mState = value == false ? ButtonState::kPressed : ButtonState::kReleased; + break; + case ButtonState::kReleased: + button->mState = ButtonState::kIdle; + if (button->mUatButtonPressCallback) + { + button->mUatButtonPressCallback(button); + } + break; + default: + break; + } + if (button->mState == ButtonState::kIdle) + { + button->GpioIntrEnable(true); + eventDone = true; + break; + } + vTaskDelay(10 / portTICK_PERIOD_MS); + } + } +} + +void UatButton::GpioIntrEnable(bool enable) +{ + if (enable) + { + gpio_intr_enable(mGpioNum); + } + else + { + gpio_intr_disable(mGpioNum); + } +} + +void UatButton::Init(gpio_num_t gpioNum, esp_sleep_ext1_wakeup_mode_t wakeupMode) +{ + mGpioNum = gpioNum; + mState = ButtonState::kIdle; + gpio_config_t io_conf = {}; + io_conf.intr_type = GPIO_INTR_LOW_LEVEL; + io_conf.pin_bit_mask = (1ULL << static_cast(mGpioNum)); + io_conf.mode = GPIO_MODE_INPUT; + io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE; + io_conf.pull_up_en = GPIO_PULLUP_ENABLE; + // configure GPIO with the given settings + gpio_config(&io_conf); + if (!sEventQueue) + { + // create a queue to handle gpio event from isr + sEventQueue = xQueueCreate(10, sizeof(UatButton *)); + if (!sEventQueue) + { + ESP_LOGE(TAG, "Failed to create GPIO EventQueue"); + return; + } + } + if (!sTaskHandle) + { + // start gpio task + xTaskCreate(RunEventLoop, "UatButton", 4096, nullptr, 10, &sTaskHandle); + if (!sTaskHandle) + { + ESP_LOGE(TAG, "Failed to create GPIO Task"); + return; + } + } + // install gpio isr service + gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT); + // hook isr handler for specific gpio pin + gpio_isr_handler_add(mGpioNum, gpio_isr_handler, (void *) this); + ESP_LOGI(TAG, "UAT Button initialized.."); + // Configure RTC IO wake up + esp_sleep_enable_ext1_wakeup(1ULL << static_cast(mGpioNum), wakeupMode); +#if SOC_RTCIO_INPUT_OUTPUT_SUPPORTED + rtc_gpio_pulldown_dis(mGpioNum); + rtc_gpio_pullup_en(mGpioNum); +#else + gpio_pulldown_dis(mGpioNum); + gpio_pullup_en(mGpioNum); +#endif +} diff --git a/examples/lit-icd-app/esp32/main/include/IcdUatButton.h b/examples/lit-icd-app/esp32/main/include/IcdUatButton.h new file mode 100644 index 00000000000000..2104d1a7c4079d --- /dev/null +++ b/examples/lit-icd-app/esp32/main/include/IcdUatButton.h @@ -0,0 +1,50 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include +#include +#include + +class UatButton +{ +public: + using UatButtonPressCallback = void (*)(UatButton *); + + enum class ButtonState : uint8_t + { + kIdle = 0, + kPressed, + kReleased, + }; + + void Init(gpio_num_t gpioNum, esp_sleep_ext1_wakeup_mode_t wakeMode); + void SetUatButtonPressCallback(UatButtonPressCallback buttonCallback) { mUatButtonPressCallback = buttonCallback; } + void GpioIntrEnable(bool enable); + + static void RunEventLoop(void * arg); + static TaskHandle_t sTaskHandle; + static QueueHandle_t sEventQueue; + +private: + gpio_num_t mGpioNum; + ButtonState mState; + UatButtonPressCallback mUatButtonPressCallback; +}; diff --git a/examples/lit-icd-app/esp32/main/main.cpp b/examples/lit-icd-app/esp32/main/main.cpp index 340ae124d816c3..4bb736b219eabd 100644 --- a/examples/lit-icd-app/esp32/main/main.cpp +++ b/examples/lit-icd-app/esp32/main/main.cpp @@ -15,6 +15,7 @@ * limitations under the License. */ +#include "app/icd/server/ICDNotifier.h" #include "esp_log.h" #include "esp_netif.h" #include "esp_system.h" @@ -24,6 +25,8 @@ #include "nvs_flash.h" #include +#include +#include #include #include #include @@ -31,6 +34,7 @@ #include #include #include +#include #if CONFIG_ENABLE_ESP32_FACTORY_DATA_PROVIDER #include @@ -58,6 +62,18 @@ chip::DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider; #error "Currently this example only support Thread chips" #endif +#ifdef CONFIG_IDF_TARGET_ESP32H2 +// GPIO9-GPIO14 could be used to wake up ESP32-H2. +// For ESP32-H2 DevKitM, the boot button is GPIO9. +#define UAT_GPIO GPIO_NUM_9 +#elif defined(CONFIG_IDF_TARGET_ESP32C6) +// GPIO0-GPIO7 could be used to wake up ESP32-C6. +// For ESP32-C6 DevKitC, the boot button is GPIO9, we cannot use it to wake up the chip. +#define UAT_GPIO GPIO_NUM_7 +#else +#error "Unsupport IDF target" +#endif + using namespace ::chip; using namespace ::chip::DeviceManager; using namespace ::chip::Credentials; @@ -66,6 +82,11 @@ extern const char TAG[] = "lit-icd-app"; static AppDeviceCallbacks EchoCallbacks; +static void UatButtonHandler(UatButton * button) +{ + DeviceLayer::PlatformMgr().ScheduleWork([](intptr_t) { app::ICDNotifier::GetInstance().NotifyNetworkActivityNotification(); }); +} + static void InitServer(intptr_t context) { Esp32AppServer::Init(); // Init ZCL Data Model and CHIP App Server AND Initialize device attestation config @@ -110,6 +131,9 @@ extern "C" void app_main() SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); #endif // CONFIG_ENABLE_ESP32_FACTORY_DATA_PROVIDER ESPOpenThreadInit(); + static UatButton sButton; + sButton.Init(UAT_GPIO, ESP_EXT1_WAKEUP_ANY_LOW); + sButton.SetUatButtonPressCallback(UatButtonHandler); chip::DeviceLayer::PlatformMgr().ScheduleWork(InitServer, reinterpret_cast(nullptr)); } diff --git a/examples/lit-icd-app/nrfconnect/main/AppTask.cpp b/examples/lit-icd-app/nrfconnect/main/AppTask.cpp index d7d35bb53fcc04..336024fe289ea3 100644 --- a/examples/lit-icd-app/nrfconnect/main/AppTask.cpp +++ b/examples/lit-icd-app/nrfconnect/main/AppTask.cpp @@ -296,7 +296,8 @@ void AppTask::ButtonEventHandler(uint32_t buttonState, uint32_t hasChanged) void AppTask::IcdUatEventHandler(const AppEvent &) { - Server::GetInstance().GetICDManager().UpdateOperationState(ICDManager::OperationalState::ActiveMode); + // Temporarily claim network activity, until we implement a "user trigger" reason for ICD wakeups. + PlatformMgr().ScheduleWork([](intptr_t) { ICDNotifier::GetInstance().NotifyNetworkActivityNotification(); }); } void AppTask::FunctionTimerTimeoutCallback(k_timer * timer) diff --git a/examples/lit-icd-app/silabs/include/AppTask.h b/examples/lit-icd-app/silabs/include/AppTask.h index 1fc5f2fae5f18c..7866fc48079962 100644 --- a/examples/lit-icd-app/silabs/include/AppTask.h +++ b/examples/lit-icd-app/silabs/include/AppTask.h @@ -28,7 +28,7 @@ #include "AppEvent.h" #include "BaseApplication.h" -#include +#include #include #include #include diff --git a/examples/lock-app/asr/include/AppTask.h b/examples/lock-app/asr/include/AppTask.h index 854d70efdb9744..5c96ea0bec07ae 100755 --- a/examples/lock-app/asr/include/AppTask.h +++ b/examples/lock-app/asr/include/AppTask.h @@ -27,7 +27,7 @@ #include "FreeRTOS.h" #include "timers.h" // provides FreeRTOS timer support -#include +#include #include // Application-defined error codes in the CHIP_ERROR space. diff --git a/examples/lock-app/cc13x4_26x4/src/AppTask.cpp b/examples/lock-app/cc13x4_26x4/src/AppTask.cpp index ec6a1d048c0276..2a202ce432ed7a 100644 --- a/examples/lock-app/cc13x4_26x4/src/AppTask.cpp +++ b/examples/lock-app/cc13x4_26x4/src/AppTask.cpp @@ -72,9 +72,10 @@ using namespace ::chip::app::Clusters::DoorLock; static TaskHandle_t sAppTaskHandle; static QueueHandle_t sAppEventQueue; - +#if (LED_ENABLE == 1) static LED_Handle sAppRedHandle; static LED_Handle sAppGreenHandle; +#endif static Button_Handle sAppLeftHandle; static Button_Handle sAppRightHandle; diff --git a/examples/lock-app/esp32/main/include/AppTask.h b/examples/lock-app/esp32/main/include/AppTask.h index 3c32cb8704aa0e..32d5dfd199e335 100644 --- a/examples/lock-app/esp32/main/include/AppTask.h +++ b/examples/lock-app/esp32/main/include/AppTask.h @@ -24,7 +24,7 @@ #include #include "freertos/FreeRTOS.h" -#include +#include #include #include diff --git a/examples/lock-app/infineon/psoc6/include/AppTask.h b/examples/lock-app/infineon/psoc6/include/AppTask.h index 8d6ca18b1f8e8a..b120a9c9aec325 100644 --- a/examples/lock-app/infineon/psoc6/include/AppTask.h +++ b/examples/lock-app/infineon/psoc6/include/AppTask.h @@ -27,7 +27,7 @@ #include "FreeRTOS.h" #include "timers.h" // provides FreeRTOS timer support -#include +#include #include // Application-defined error codes in the CHIP_ERROR space. diff --git a/examples/lock-app/qpg/include/AppTask.h b/examples/lock-app/qpg/include/AppTask.h index 3734eeadeef816..b4ede0e6abde0d 100644 --- a/examples/lock-app/qpg/include/AppTask.h +++ b/examples/lock-app/qpg/include/AppTask.h @@ -27,7 +27,7 @@ #include "FreeRTOS.h" #include "timers.h" // provides FreeRTOS timer support -#include +#include #include #include diff --git a/examples/lock-app/silabs/include/AppTask.h b/examples/lock-app/silabs/include/AppTask.h index e1560ac19439b5..b0040ac5bf6586 100644 --- a/examples/lock-app/silabs/include/AppTask.h +++ b/examples/lock-app/silabs/include/AppTask.h @@ -29,7 +29,7 @@ #include "AppEvent.h" #include "BaseApplication.h" #include "LockManager.h" -#include +#include #include #include #include diff --git a/examples/platform/cc13x4_26x4/project_include/OpenThreadConfig.h b/examples/platform/cc13x4_26x4/project_include/OpenThreadConfig.h index 795d77b646769c..c4087578b982c8 100644 --- a/examples/platform/cc13x4_26x4/project_include/OpenThreadConfig.h +++ b/examples/platform/cc13x4_26x4/project_include/OpenThreadConfig.h @@ -23,6 +23,7 @@ #pragma once +#define OPENTHREAD_CONFIG_NUM_MESSAGE_BUFFERS 22 #define OPENTHREAD_CONFIG_DHCP6_SERVER_ENABLE 0 #define OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE 0 #define OPENTHREAD_CONFIG_DIAG_ENABLE 0 diff --git a/examples/platform/esp32/common/Esp32AppServer.cpp b/examples/platform/esp32/common/Esp32AppServer.cpp index 53957784b8c5f5..873115c25ab1af 100644 --- a/examples/platform/esp32/common/Esp32AppServer.cpp +++ b/examples/platform/esp32/common/Esp32AppServer.cpp @@ -61,14 +61,14 @@ static app::Clusters::NetworkCommissioning::Instance sEthernetNetworkCommissioningInstance(0 /* Endpoint Id */, &(NetworkCommissioning::ESPEthernetDriver::GetInstance())); #endif -#if CONFIG_TEST_EVENT_TRIGGER_ENABLED && CONFIG_ENABLE_OTA_REQUESTOR +#if CONFIG_TEST_EVENT_TRIGGER_ENABLED static uint8_t sTestEventTriggerEnableKey[TestEventTriggerDelegate::kEnableKeyLength] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; #endif } // namespace -#if CONFIG_TEST_EVENT_TRIGGER_ENABLED && CONFIG_ENABLE_OTA_REQUESTOR +#if CONFIG_TEST_EVENT_TRIGGER_ENABLED static int hex_digit_to_int(char hex) { if ('A' <= hex && hex <= 'F') @@ -107,7 +107,7 @@ static size_t hex_string_to_binary(const char * hex_string, uint8_t * buf, size_ return buf_size; } -#endif // CONFIG_TEST_EVENT_TRIGGER_ENABLED && CONFIG_ENABLE_OTA_REQUESTOR +#endif // CONFIG_TEST_EVENT_TRIGGER_ENABLED void Esp32AppServer::DeInitBLEIfCommissioned(void) { @@ -158,7 +158,7 @@ void Esp32AppServer::Init(AppDelegate * sAppDelegate) { // Init ZCL Data Model and CHIP App Server static chip::CommonCaseDeviceServerInitParams initParams; -#if CONFIG_TEST_EVENT_TRIGGER_ENABLED && CONFIG_ENABLE_OTA_REQUESTOR +#if CONFIG_TEST_EVENT_TRIGGER_ENABLED if (hex_string_to_binary(CONFIG_TEST_EVENT_TRIGGER_ENABLE_KEY, sTestEventTriggerEnableKey, sizeof(sTestEventTriggerEnableKey)) == 0) { @@ -166,9 +166,11 @@ void Esp32AppServer::Init(AppDelegate * sAppDelegate) memset(sTestEventTriggerEnableKey, 0, sizeof(sTestEventTriggerEnableKey)); } static SimpleTestEventTriggerDelegate sTestEventTriggerDelegate{}; - static OTATestEventTriggerHandler sOtaTestEventTriggerHandler{}; VerifyOrDie(sTestEventTriggerDelegate.Init(ByteSpan(sTestEventTriggerEnableKey)) == CHIP_NO_ERROR); +#if CONFIG_ENABLE_OTA_REQUESTOR + static OTATestEventTriggerHandler sOtaTestEventTriggerHandler{}; VerifyOrDie(sTestEventTriggerDelegate.AddHandler(&sOtaTestEventTriggerHandler) == CHIP_NO_ERROR); +#endif initParams.testEventTriggerDelegate = &sTestEventTriggerDelegate; #endif // CONFIG_TEST_EVENT_TRIGGER_ENABLED && CONFIG_ENABLE_OTA_REQUESTOR (void) initParams.InitializeStaticResourcesBeforeServerInit(); diff --git a/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp b/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp index e03634e9807aa5..2f0bbcbf85b653 100644 --- a/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp +++ b/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp @@ -62,6 +62,10 @@ #include #endif +#ifdef ENABLE_CHIP_SHELL +#include +#endif + using namespace chip; using namespace chip::TLV; using namespace ::chip::Credentials; @@ -202,6 +206,9 @@ CHIP_ERROR chip::NXP::App::AppTaskBase::Init() #if CONFIG_CHIP_WIFI || CHIP_DEVICE_CONFIG_ENABLE_WPA sNetworkCommissioningInstance.Init(); +#ifdef ENABLE_CHIP_SHELL + Shell::SetWiFiDriver(chip::NXP::App::GetAppTask().GetWifiDriverInstance()); +#endif #endif #if CONFIG_CHIP_OTA_REQUESTOR if (err == CHIP_NO_ERROR) diff --git a/examples/platform/silabs/BaseApplication.cpp b/examples/platform/silabs/BaseApplication.cpp index a6986db57d2b3e..f02826f1308c32 100644 --- a/examples/platform/silabs/BaseApplication.cpp +++ b/examples/platform/silabs/BaseApplication.cpp @@ -515,9 +515,7 @@ void BaseApplication::ButtonHandler(AppEvent * aEvent) SILABS_LOG("Network is already provisioned, Ble advertisement not enabled"); #if CHIP_CONFIG_ENABLE_ICD_SERVER // Temporarily claim network activity, until we implement a "user trigger" reason for ICD wakeups. - PlatformMgr().LockChipStack(); - ICDNotifier::GetInstance().NotifyNetworkActivityNotification(); - PlatformMgr().UnlockChipStack(); + PlatformMgr().ScheduleWork([](intptr_t) { ICDNotifier::GetInstance().NotifyNetworkActivityNotification(); }); #endif // CHIP_CONFIG_ENABLE_ICD_SERVER } } diff --git a/examples/platform/silabs/BaseApplication.h b/examples/platform/silabs/BaseApplication.h index e9ca6bfc950834..8a231aa6c51513 100644 --- a/examples/platform/silabs/BaseApplication.h +++ b/examples/platform/silabs/BaseApplication.h @@ -30,7 +30,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/examples/pump-app/cc13x4_26x4/main/AppTask.cpp b/examples/pump-app/cc13x4_26x4/main/AppTask.cpp index 4450b09bd95e8d..0aaa1c6b4029a7 100644 --- a/examples/pump-app/cc13x4_26x4/main/AppTask.cpp +++ b/examples/pump-app/cc13x4_26x4/main/AppTask.cpp @@ -79,9 +79,10 @@ using namespace chip::app::Clusters; static TaskHandle_t sAppTaskHandle; static QueueHandle_t sAppEventQueue; - +#if (LED_ENABLE == 1) static LED_Handle sAppRedHandle; static LED_Handle sAppGreenHandle; +#endif static Button_Handle sAppLeftHandle; static Button_Handle sAppRightHandle; diff --git a/examples/pump-app/silabs/include/AppTask.h b/examples/pump-app/silabs/include/AppTask.h index 69bf7021bf47dd..921ae9a2694475 100644 --- a/examples/pump-app/silabs/include/AppTask.h +++ b/examples/pump-app/silabs/include/AppTask.h @@ -29,7 +29,7 @@ #include "AppEvent.h" #include "BaseApplication.h" #include "PumpManager.h" -#include +#include #include #include #include diff --git a/examples/pump-controller-app/cc13x4_26x4/main/AppTask.cpp b/examples/pump-controller-app/cc13x4_26x4/main/AppTask.cpp index 6c849549343c1d..fd44a3df454b57 100644 --- a/examples/pump-controller-app/cc13x4_26x4/main/AppTask.cpp +++ b/examples/pump-controller-app/cc13x4_26x4/main/AppTask.cpp @@ -68,9 +68,10 @@ using namespace ::chip::DeviceLayer; static TaskHandle_t sAppTaskHandle; static QueueHandle_t sAppEventQueue; - +#if (LED_ENABLE == 1) static LED_Handle sAppRedHandle; static LED_Handle sAppGreenHandle; +#endif static Button_Handle sAppLeftHandle; static Button_Handle sAppRightHandle; diff --git a/examples/smoke-co-alarm-app/silabs/include/AppTask.h b/examples/smoke-co-alarm-app/silabs/include/AppTask.h index 9e68505d341a36..0cfd86fa01021a 100644 --- a/examples/smoke-co-alarm-app/silabs/include/AppTask.h +++ b/examples/smoke-co-alarm-app/silabs/include/AppTask.h @@ -27,7 +27,7 @@ #include "AppEvent.h" #include "BaseApplication.h" #include "SmokeCoAlarmManager.h" -#include +#include #include #include #include diff --git a/examples/temperature-measurement-app/asr/include/AppTask.h b/examples/temperature-measurement-app/asr/include/AppTask.h index 97d1bfe538fb64..7e168e14d5a854 100755 --- a/examples/temperature-measurement-app/asr/include/AppTask.h +++ b/examples/temperature-measurement-app/asr/include/AppTask.h @@ -24,7 +24,7 @@ #include "AppEvent.h" #include "FreeRTOS.h" #include "timers.h" // provides FreeRTOS timer support -#include +#include #include // Application-defined error codes in the CHIP_ERROR space. diff --git a/examples/thermostat/asr/include/AppTask.h b/examples/thermostat/asr/include/AppTask.h index 90a8ac65adff46..1bfe23bc1d3692 100644 --- a/examples/thermostat/asr/include/AppTask.h +++ b/examples/thermostat/asr/include/AppTask.h @@ -26,7 +26,7 @@ #include "SensorManager.h" #include "TemperatureManager.h" #include "timers.h" // provides FreeRTOS timer support -#include +#include #include #include diff --git a/examples/thermostat/silabs/include/AppTask.h b/examples/thermostat/silabs/include/AppTask.h index 25177b9ab43808..e41122994237ad 100644 --- a/examples/thermostat/silabs/include/AppTask.h +++ b/examples/thermostat/silabs/include/AppTask.h @@ -34,7 +34,7 @@ #include "BaseApplication.h" #include "SensorManager.h" #include "TemperatureManager.h" -#include +#include #include #include #include diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/DiscoveryExampleFragment.java b/examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/DiscoveryExampleFragment.java index 49076867a9cc75..a706780c5be3b4 100644 --- a/examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/DiscoveryExampleFragment.java +++ b/examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/DiscoveryExampleFragment.java @@ -350,6 +350,10 @@ private String getCastingPlayerButtonText(CastingPlayer player) { ? (aux.isEmpty() ? "" : ", ") + "Device Type: " + player.getDeviceType() : ""; aux += (aux.isEmpty() ? "" : ", ") + "Resolved IP?: " + (player.getIpAddresses().size() > 0); + aux += + (aux.isEmpty() ? "" : ", ") + + "Supports Commissioner Generated Passcode: " + + (player.getSupportsCommissionerGeneratedPasscode()); aux = aux.isEmpty() ? aux : "\n" + aux; return main + aux; diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/matter/casting/core/CastingPlayer.java b/examples/tv-casting-app/android/App/app/src/main/jni/com/matter/casting/core/CastingPlayer.java index 39db6488fa8ed8..3c3a74032bd313 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/matter/casting/core/CastingPlayer.java +++ b/examples/tv-casting-app/android/App/app/src/main/jni/com/matter/casting/core/CastingPlayer.java @@ -49,6 +49,8 @@ public interface CastingPlayer { long getDeviceType(); + boolean getSupportsCommissionerGeneratedPasscode(); + List getEndpoints(); @Override diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/com/matter/casting/core/MatterCastingPlayer.java b/examples/tv-casting-app/android/App/app/src/main/jni/com/matter/casting/core/MatterCastingPlayer.java index dd4bd0ba6531c6..a4f03a00e4f5a2 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/com/matter/casting/core/MatterCastingPlayer.java +++ b/examples/tv-casting-app/android/App/app/src/main/jni/com/matter/casting/core/MatterCastingPlayer.java @@ -47,6 +47,8 @@ public class MatterCastingPlayer implements CastingPlayer { private int productId; private int vendorId; private long deviceType; + private boolean supportsCommissionerGeneratedPasscode; + protected long _cppCastingPlayer; public MatterCastingPlayer( @@ -59,7 +61,8 @@ public MatterCastingPlayer( int port, int productId, int vendorId, - long deviceType) { + long deviceType, + boolean supportsCommissionerGeneratedPasscode) { this.connected = connected; this.deviceId = deviceId; this.hostName = hostName; @@ -70,6 +73,7 @@ public MatterCastingPlayer( this.productId = productId; this.vendorId = vendorId; this.deviceType = deviceType; + this.supportsCommissionerGeneratedPasscode = supportsCommissionerGeneratedPasscode; } /** @@ -131,6 +135,11 @@ public long getDeviceType() { return this.deviceType; } + @Override + public boolean getSupportsCommissionerGeneratedPasscode() { + return this.supportsCommissionerGeneratedPasscode; + } + @Override public native List getEndpoints(); diff --git a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/Converters-JNI.cpp b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/Converters-JNI.cpp index aa5ef2b25f0096..00ca47216ae804 100644 --- a/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/Converters-JNI.cpp +++ b/examples/tv-casting-app/android/App/app/src/main/jni/cpp/support/Converters-JNI.cpp @@ -151,7 +151,7 @@ jobject convertCastingPlayerFromCppToJava(matter::casting::memory::StrongGetMethodID(matterCastingPlayerJavaClass, "", - "(ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;IIIJ)V"); + "(ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;IIIJZ)V"); if (constructor == nullptr) { ChipLogError(AppServer, "convertCastingPlayerFromCppToJava() could not locate MatterCastingPlayer Java class constructor"); @@ -186,7 +186,8 @@ jobject convertCastingPlayerFromCppToJava(matter::casting::memory::StrongNewStringUTF(player->GetId()), env->NewStringUTF(player->GetHostName()), env->NewStringUTF(player->GetDeviceName()), env->NewStringUTF(player->GetInstanceName()), jIpAddressList, (jint) (player->GetPort()), (jint) (player->GetProductId()), - (jint) (player->GetVendorId()), (jlong) (player->GetDeviceType())); + (jint) (player->GetVendorId()), (jlong) (player->GetDeviceType()), + static_cast(player->GetSupportsCommissionerGeneratedPasscode())); if (jMatterCastingPlayer == nullptr) { ChipLogError(AppServer, "convertCastingPlayerFromCppToJava(): Could not create MatterCastingPlayer Java object"); diff --git a/examples/tv-casting-app/linux/CastingShellCommands.cpp b/examples/tv-casting-app/linux/CastingShellCommands.cpp index e82c0491a00c51..18078344512606 100644 --- a/examples/tv-casting-app/linux/CastingShellCommands.cpp +++ b/examples/tv-casting-app/linux/CastingShellCommands.cpp @@ -91,7 +91,7 @@ void PrintBindings() "Binding type=%d fab=%d nodeId=0x" ChipLogFormatX64 " groupId=%d local endpoint=%d remote endpoint=%d cluster=" ChipLogFormatMEI, binding.type, binding.fabricIndex, ChipLogValueX64(binding.nodeId), binding.groupId, binding.local, - binding.remote, ChipLogValueMEI(binding.clusterId.ValueOr(0))); + binding.remote, ChipLogValueMEI(binding.clusterId.value_or(0))); } } diff --git a/examples/tv-casting-app/linux/simple-app-helper.cpp b/examples/tv-casting-app/linux/simple-app-helper.cpp index f0e7c2068883ea..de8c255366cd37 100644 --- a/examples/tv-casting-app/linux/simple-app-helper.cpp +++ b/examples/tv-casting-app/linux/simple-app-helper.cpp @@ -45,6 +45,7 @@ DiscoveryDelegateImpl * DiscoveryDelegateImpl::GetInstance() void DiscoveryDelegateImpl::HandleOnAdded(matter::casting::memory::Strong player) { + ChipLogProgress(AppServer, "DiscoveryDelegateImpl::HandleOnAdded() called"); if (commissionersCount == 0) { ChipLogProgress(AppServer, "Select discovered Casting Player (start index = 0) to request commissioning"); @@ -58,7 +59,7 @@ void DiscoveryDelegateImpl::HandleOnAdded(matter::casting::memory::Strong player) { - ChipLogProgress(AppServer, "Updated CastingPlayer with ID: %s", player->GetId()); + ChipLogProgress(AppServer, "DiscoveryDelegateImpl::HandleOnUpdated() Updated CastingPlayer with ID: %s", player->GetId()); } void InvokeContentLauncherLaunchURL(matter::casting::memory::Strong endpoint) @@ -294,7 +295,7 @@ void PrintBindings() "Binding type=%d fab=%d nodeId=0x" ChipLogFormatX64 " groupId=%d local endpoint=%d remote endpoint=%d cluster=" ChipLogFormatMEI, binding.type, binding.fabricIndex, ChipLogValueX64(binding.nodeId), binding.groupId, binding.local, - binding.remote, ChipLogValueMEI(binding.clusterId.ValueOr(0))); + binding.remote, ChipLogValueMEI(binding.clusterId.value_or(0))); } } diff --git a/examples/tv-casting-app/tv-casting-common/core/CastingPlayer.cpp b/examples/tv-casting-app/tv-casting-common/core/CastingPlayer.cpp index fe966722ccf902..c9f938dbc695c7 100644 --- a/examples/tv-casting-app/tv-casting-common/core/CastingPlayer.cpp +++ b/examples/tv-casting-app/tv-casting-common/core/CastingPlayer.cpp @@ -236,6 +236,7 @@ bool CastingPlayer::ContainsDesiredEndpoint(core::CastingPlayer * cachedCastingP void CastingPlayer::LogDetail() const { + ChipLogProgress(AppServer, "CastingPlayer::LogDetail() called"); if (strlen(mAttributes.id) != 0) { ChipLogDetail(AppServer, "\tID: %s", mAttributes.id); @@ -281,6 +282,8 @@ void CastingPlayer::LogDetail() const { ChipLogDetail(AppServer, "\tDevice Type: %" PRIu32, mAttributes.deviceType); } + ChipLogDetail(AppServer, "\tSupports Commissioner Generated Passcode: %s", + mAttributes.supportsCommissionerGeneratedPasscode ? "true" : "false"); if (mAttributes.nodeId > 0) { ChipLogDetail(AppServer, "\tNode ID: 0x" ChipLogFormatX64, ChipLogValueX64(mAttributes.nodeId)); diff --git a/examples/tv-casting-app/tv-casting-common/core/CastingPlayer.h b/examples/tv-casting-app/tv-casting-common/core/CastingPlayer.h index 7d383bb6669225..783d50f60af390 100644 --- a/examples/tv-casting-app/tv-casting-common/core/CastingPlayer.h +++ b/examples/tv-casting-app/tv-casting-common/core/CastingPlayer.h @@ -56,13 +56,14 @@ class CastingPlayerAttributes char deviceName[chip::Dnssd::kMaxDeviceNameLen + 1] = {}; char hostName[chip::Dnssd::kHostNameMaxLength + 1] = {}; char instanceName[chip::Dnssd::Commission::kInstanceNameMaxLength + 1] = {}; - unsigned int numIPs; // number of valid IP addresses + unsigned int numIPs; // Number of valid IP addresses chip::Inet::IPAddress ipAddresses[chip::Dnssd::CommonResolutionData::kMaxIPAddresses]; chip::Inet::InterfaceId interfaceId; uint16_t port; uint16_t productId; uint16_t vendorId; uint32_t deviceType; + bool supportsCommissionerGeneratedPasscode; chip::NodeId nodeId = 0; chip::FabricIndex fabricIndex = 0; @@ -182,6 +183,8 @@ class CastingPlayer : public std::enable_shared_from_this uint32_t GetDeviceType() const { return mAttributes.deviceType; } + bool GetSupportsCommissionerGeneratedPasscode() const { return mAttributes.supportsCommissionerGeneratedPasscode; } + chip::NodeId GetNodeId() const { return mAttributes.nodeId; } chip::FabricIndex GetFabricIndex() const { return mAttributes.fabricIndex; } diff --git a/examples/tv-casting-app/tv-casting-common/core/CastingPlayerDiscovery.cpp b/examples/tv-casting-app/tv-casting-common/core/CastingPlayerDiscovery.cpp index 9b26a868efd8c1..9dd365d8db559f 100644 --- a/examples/tv-casting-app/tv-casting-common/core/CastingPlayerDiscovery.cpp +++ b/examples/tv-casting-app/tv-casting-common/core/CastingPlayerDiscovery.cpp @@ -93,11 +93,12 @@ void DeviceDiscoveryDelegateImpl::OnDiscoveredDevice(const chip::Dnssd::Discover { attributes.ipAddresses[j] = nodeData.resolutionData.ipAddress[j]; } - attributes.interfaceId = nodeData.resolutionData.interfaceId; - attributes.port = nodeData.resolutionData.port; - attributes.productId = nodeData.nodeData.productId; - attributes.vendorId = nodeData.nodeData.vendorId; - attributes.deviceType = nodeData.nodeData.deviceType; + attributes.interfaceId = nodeData.resolutionData.interfaceId; + attributes.port = nodeData.resolutionData.port; + attributes.productId = nodeData.nodeData.productId; + attributes.vendorId = nodeData.nodeData.vendorId; + attributes.deviceType = nodeData.nodeData.deviceType; + attributes.supportsCommissionerGeneratedPasscode = nodeData.nodeData.supportsCommissionerGeneratedPasscode; memory::Strong player = std::make_shared(attributes); diff --git a/examples/tv-casting-app/tv-casting-common/include/TargetVideoPlayerInfo.h b/examples/tv-casting-app/tv-casting-common/include/TargetVideoPlayerInfo.h index 8c00cf61da4031..dd799bdf8c776d 100644 --- a/examples/tv-casting-app/tv-casting-common/include/TargetVideoPlayerInfo.h +++ b/examples/tv-casting-app/tv-casting-common/include/TargetVideoPlayerInfo.h @@ -72,7 +72,7 @@ class TargetVideoPlayerInfo public: TargetVideoPlayerInfo() {} - bool operator==(const TargetVideoPlayerInfo & other) { return this->mNodeId == other.mNodeId; } + bool operator==(const TargetVideoPlayerInfo & other) const { return this->mNodeId == other.mNodeId; } bool IsInitialized() { return mInitialized; } void Reset(); diff --git a/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp b/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp index 3c77048e67d551..ef56d3f1144644 100644 --- a/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp +++ b/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp @@ -312,7 +312,7 @@ void CastingServer::ReadServerClustersForNode(NodeId nodeId) "Binding type=%d fab=%d nodeId=0x" ChipLogFormatX64 " groupId=%d local endpoint=%d remote endpoint=%d cluster=" ChipLogFormatMEI, binding.type, binding.fabricIndex, ChipLogValueX64(binding.nodeId), binding.groupId, binding.local, - binding.remote, ChipLogValueMEI(binding.clusterId.ValueOr(0))); + binding.remote, ChipLogValueMEI(binding.clusterId.value_or(0))); if (binding.type == MATTER_UNICAST_BINDING && nodeId == binding.nodeId) { if (!mActiveTargetVideoPlayerInfo.HasEndpoint(binding.remote)) @@ -584,7 +584,7 @@ void CastingServer::DeviceEventCallback(const DeviceLayer::ChipDeviceEvent * eve "CastingServer::DeviceEventCallback Read cached binding type=%d fabrixIndex=%d nodeId=0x" ChipLogFormatX64 " groupId=%d local endpoint=%d remote endpoint=%d cluster=" ChipLogFormatMEI, binding.type, binding.fabricIndex, ChipLogValueX64(binding.nodeId), binding.groupId, binding.local, - binding.remote, ChipLogValueMEI(binding.clusterId.ValueOr(0))); + binding.remote, ChipLogValueMEI(binding.clusterId.value_or(0))); if (binding.type == MATTER_UNICAST_BINDING && event->BindingsChanged.fabricIndex == binding.fabricIndex) { ChipLogProgress( @@ -675,7 +675,7 @@ NodeId CastingServer::GetVideoPlayerNodeForFabricIndex(FabricIndex fabricIndex) "Binding type=%d fab=%d nodeId=0x" ChipLogFormatX64 " groupId=%d local endpoint=%d remote endpoint=%d cluster=" ChipLogFormatMEI, binding.type, binding.fabricIndex, ChipLogValueX64(binding.nodeId), binding.groupId, binding.local, - binding.remote, ChipLogValueMEI(binding.clusterId.ValueOr(0))); + binding.remote, ChipLogValueMEI(binding.clusterId.value_or(0))); if (binding.type == MATTER_UNICAST_BINDING && fabricIndex == binding.fabricIndex) { ChipLogProgress(NotSpecified, "GetVideoPlayerNodeForFabricIndex nodeId=0x" ChipLogFormatX64, @@ -701,7 +701,7 @@ FabricIndex CastingServer::GetVideoPlayerFabricIndexForNode(NodeId nodeId) "Binding type=%d fab=%d nodeId=0x" ChipLogFormatX64 " groupId=%d local endpoint=%d remote endpoint=%d cluster=" ChipLogFormatMEI, binding.type, binding.fabricIndex, ChipLogValueX64(binding.nodeId), binding.groupId, binding.local, - binding.remote, ChipLogValueMEI(binding.clusterId.ValueOr(0))); + binding.remote, ChipLogValueMEI(binding.clusterId.value_or(0))); if (binding.type == MATTER_UNICAST_BINDING && nodeId == binding.nodeId) { ChipLogProgress(NotSpecified, "GetVideoPlayerFabricIndexForNode fabricIndex=%d nodeId=0x" ChipLogFormatX64, diff --git a/examples/tv-casting-app/tv-casting-common/support/CastingStore.cpp b/examples/tv-casting-app/tv-casting-common/support/CastingStore.cpp index c9b9c5450b3641..819c0299945ed4 100644 --- a/examples/tv-casting-app/tv-casting-common/support/CastingStore.cpp +++ b/examples/tv-casting-app/tv-casting-common/support/CastingStore.cpp @@ -182,6 +182,14 @@ std::vector CastingStore::ReadAll() continue; } + if (castingPlayerContainerTagNum == kCastingPlayerSupportsCommissionerGeneratedPasscodeTag) + { + err = reader.Get(attributes.supportsCommissionerGeneratedPasscode); + VerifyOrReturnValue(err == CHIP_NO_ERROR, std::vector(), + ChipLogError(AppServer, "TLVReader.Get failed %" CHIP_ERROR_FORMAT, err.Format())); + continue; + } + if (castingPlayerContainerTagNum == kCastingPlayerPortTag) { err = reader.Get(attributes.port); @@ -472,6 +480,8 @@ CHIP_ERROR CastingStore::WriteAll(std::vector castingPlayer ReturnErrorOnFailure(tlvWriter.Put(chip::TLV::ContextTag(kCastingPlayerVendorIdTag), castingPlayer.GetVendorId())); ReturnErrorOnFailure(tlvWriter.Put(chip::TLV::ContextTag(kCastingPlayerProductIdTag), castingPlayer.GetProductId())); ReturnErrorOnFailure(tlvWriter.Put(chip::TLV::ContextTag(kCastingPlayerDeviceTypeIdTag), castingPlayer.GetDeviceType())); + ReturnErrorOnFailure(tlvWriter.Put(chip::TLV::ContextTag(kCastingPlayerSupportsCommissionerGeneratedPasscodeTag), + castingPlayer.GetSupportsCommissionerGeneratedPasscode())); ReturnErrorOnFailure(tlvWriter.Put(chip::TLV::ContextTag(kCastingPlayerPortTag), castingPlayer.GetPort())); ReturnErrorOnFailure(tlvWriter.PutBytes(chip::TLV::ContextTag(kCastingPlayerInstanceNameTag), (const uint8_t *) castingPlayer.GetInstanceName(), diff --git a/examples/tv-casting-app/tv-casting-common/support/CastingStore.h b/examples/tv-casting-app/tv-casting-common/support/CastingStore.h index 9602af892c9909..c60fa128079122 100644 --- a/examples/tv-casting-app/tv-casting-common/support/CastingStore.h +++ b/examples/tv-casting-app/tv-casting-common/support/CastingStore.h @@ -97,6 +97,8 @@ class CastingStore : public chip::FabricTable::Delegate kCastingPlayerEndpointServerListContainerTag, kCastingPlayerEndpointServerClusterIdTag, + kCastingPlayerSupportsCommissionerGeneratedPasscodeTag, + kContextTagMaxNum = UINT8_MAX }; diff --git a/examples/tv-casting-app/tv-casting-common/support/ChipDeviceEventHandler.cpp b/examples/tv-casting-app/tv-casting-common/support/ChipDeviceEventHandler.cpp index 20558982ea78ca..b7136b3583884f 100644 --- a/examples/tv-casting-app/tv-casting-common/support/ChipDeviceEventHandler.cpp +++ b/examples/tv-casting-app/tv-casting-common/support/ChipDeviceEventHandler.cpp @@ -155,7 +155,7 @@ void ChipDeviceEventHandler::HandleBindingsChangedViaCluster(const chip::DeviceL "nodeId=0x" ChipLogFormatX64 " groupId=%d local endpoint=%d remote endpoint=%d cluster=" ChipLogFormatMEI, binding.type, binding.fabricIndex, ChipLogValueX64(binding.nodeId), binding.groupId, binding.local, - binding.remote, ChipLogValueMEI(binding.clusterId.ValueOr(0))); + binding.remote, ChipLogValueMEI(binding.clusterId.value_or(0))); if (binding.type == MATTER_UNICAST_BINDING && event->BindingsChanged.fabricIndex == binding.fabricIndex) { ChipLogProgress(AppServer, diff --git a/examples/tv-casting-app/tv-casting-common/support/EndpointListLoader.cpp b/examples/tv-casting-app/tv-casting-common/support/EndpointListLoader.cpp index 5a1bf7244879a2..a7bbfb78d6ad3a 100644 --- a/examples/tv-casting-app/tv-casting-common/support/EndpointListLoader.cpp +++ b/examples/tv-casting-app/tv-casting-common/support/EndpointListLoader.cpp @@ -86,7 +86,7 @@ CHIP_ERROR EndpointListLoader::Load() "Binding type=%d fab=%d nodeId=0x" ChipLogFormatX64 " groupId=%d local endpoint=%d remote endpoint=%d cluster=" ChipLogFormatMEI, binding.type, binding.fabricIndex, ChipLogValueX64(binding.nodeId), binding.groupId, binding.local, - binding.remote, ChipLogValueMEI(binding.clusterId.ValueOr(0))); + binding.remote, ChipLogValueMEI(binding.clusterId.value_or(0))); if (binding.type == MATTER_UNICAST_BINDING && CastingPlayer::GetTargetCastingPlayer()->GetNodeId() == binding.nodeId) { // if we discovered a new Endpoint from the bindings, read its EndpointAttributes diff --git a/examples/window-app/silabs/include/AppTask.h b/examples/window-app/silabs/include/AppTask.h index 268e5eea415a06..ea9f6e5e19868a 100644 --- a/examples/window-app/silabs/include/AppTask.h +++ b/examples/window-app/silabs/include/AppTask.h @@ -27,7 +27,7 @@ #include #include "BaseApplication.h" -#include +#include #include #include #include diff --git a/scripts/checkout_submodules.py b/scripts/checkout_submodules.py index aa220f7ff3b139..81dafa1fb91a29 100755 --- a/scripts/checkout_submodules.py +++ b/scripts/checkout_submodules.py @@ -52,7 +52,7 @@ 'silabs_docker', ]) -Module = namedtuple('Module', 'name path platforms') +Module = namedtuple('Module', 'name path platforms recursive') def load_module_info() -> None: @@ -63,9 +63,11 @@ def load_module_info() -> None: if name != 'DEFAULT': platforms = module.get('platforms', '').split(',') platforms = set(filter(None, platforms)) - assert not (platforms - ALL_PLATFORMS), "Submodule's platform not contained in ALL_PLATFORMS" + assert not ( + platforms - ALL_PLATFORMS), "Submodule's platform not contained in ALL_PLATFORMS" + recursive = module.getboolean('recursive', False) name = name.replace('submodule "', '').replace('"', '') - yield Module(name=name, path=module['path'], platforms=platforms) + yield Module(name=name, path=module['path'], platforms=platforms, recursive=recursive) def module_matches_platforms(module: Module, platforms: set) -> bool: @@ -88,8 +90,10 @@ def make_chip_root_safe_directory() -> None: config.check_returncode() existing = config.stdout.split('\0') if CHIP_ROOT not in existing: - logging.info("Adding CHIP_ROOT to global git safe.directory configuration") - subprocess.check_call(['git', 'config', '--global', '--add', 'safe.directory', CHIP_ROOT]) + logging.info( + "Adding CHIP_ROOT to global git safe.directory configuration") + subprocess.check_call( + ['git', 'config', '--global', '--add', 'safe.directory', CHIP_ROOT]) def checkout_modules(modules: list, shallow: bool, force: bool, recursive: bool, jobs: int) -> None: @@ -101,9 +105,21 @@ def checkout_modules(modules: list, shallow: bool, force: bool, recursive: bool, cmd += ['--force'] if force else [] cmd += ['--recursive'] if recursive else [] cmd += ['--jobs', f'{jobs}'] if jobs else [] - cmd += [module.path for module in modules] + module_paths = [module.path for module in modules] - subprocess.check_call(cmd) + subprocess.check_call(cmd + module_paths) + + if recursive: + # We've recursively checkouted all submodules. + pass + else: + # We've checkouted all top-level submodules. + # We're going to recursively checkout submodules whose recursive configuration is true. + cmd += ['--recursive'] + module_paths = [module.path for module in modules if module.recursive] + + if module_paths: + subprocess.check_call(cmd + module_paths) def deinit_modules(modules: list, force: bool) -> None: @@ -120,28 +136,35 @@ def deinit_modules(modules: list, force: bool) -> None: def main(): logging.basicConfig(format='%(message)s', level=logging.INFO) - parser = argparse.ArgumentParser(description='Checkout or update relevant git submodules') + parser = argparse.ArgumentParser( + description='Checkout or update relevant git submodules') parser.add_argument('--allow-changing-global-git-config', action='store_true', help='Allow global git options to be modified if necessary, e.g. safe.directory') - parser.add_argument('--shallow', action='store_true', help='Fetch submodules without history') + parser.add_argument('--shallow', action='store_true', + help='Fetch submodules without history') parser.add_argument('--platform', nargs='+', choices=ALL_PLATFORMS, default=[], help='Process submodules for specific platforms only') - parser.add_argument('--force', action='store_true', help='Perform action despite of warnings') + parser.add_argument('--force', action='store_true', + help='Perform action despite of warnings') parser.add_argument('--deinit-unmatched', action='store_true', help='Deinitialize submodules for non-matching platforms') - parser.add_argument('--recursive', action='store_true', help='Recursive init of the listed submodules') - parser.add_argument('--jobs', type=int, metavar='N', help='Clone new submodules in parallel with N jobs') + parser.add_argument('--recursive', action='store_true', + help='Recursive init of the listed submodules') + parser.add_argument('--jobs', type=int, metavar='N', + help='Clone new submodules in parallel with N jobs') args = parser.parse_args() modules = list(load_module_info()) selected_platforms = set(args.platform) - selected_modules = [m for m in modules if module_matches_platforms(m, selected_platforms)] + selected_modules = [ + m for m in modules if module_matches_platforms(m, selected_platforms)] unmatched_modules = [m for m in modules if not module_matches_platforms( m, selected_platforms) and module_initialized(m)] if args.allow_changing_global_git_config: make_chip_root_safe_directory() # ignore directory ownership issues for sub-modules - checkout_modules(selected_modules, args.shallow, args.force, args.recursive, args.jobs) + checkout_modules(selected_modules, args.shallow, + args.force, args.recursive, args.jobs) if args.deinit_unmatched and unmatched_modules: deinit_modules(unmatched_modules, args.force) diff --git a/scripts/examples/gn_silabs_example.sh b/scripts/examples/gn_silabs_example.sh index 3877b5c98ad40a..5dbea0452fb7c6 100755 --- a/scripts/examples/gn_silabs_example.sh +++ b/scripts/examples/gn_silabs_example.sh @@ -193,7 +193,7 @@ else shift ;; --icd) - optArgs+="chip_enable_icd_server=true chip_openthread_ftd=false sl_enable_test_event_trigger=true" + optArgs+="chip_enable_icd_server=true chip_openthread_ftd=false sl_enable_test_event_trigger=true " shift ;; --low-power) diff --git a/scripts/helpers/iwyu-check.py b/scripts/helpers/iwyu-check.py index 822b85c184766d..d60a35612679b3 100755 --- a/scripts/helpers/iwyu-check.py +++ b/scripts/helpers/iwyu-check.py @@ -51,42 +51,38 @@ def find_program(names): @click.command() @click.option( '--log-level', - default='INFO', + show_default=True, + default='info', type=click.Choice(__LOG_LEVELS__.keys(), case_sensitive=False), - help='Determines the verbosity of script output.') + help='Set the verbosity of script output.') @click.option( '--no-log-timestamps', default=False, is_flag=True, - help='Skip timestamps in log output') + help='Skip timestamps in log output.') @click.option( '--compile-commands-glob', show_default=True, - default=os.path.join(proj_root_dir, "out", "debug", "compile_commands*.json"), - help='Set global pattern for compile_commands.json files' -) -@click.option( - '--scanning-destination', - show_default=True, - default=os.path.join(proj_root_dir, "src", "platform"), - help='Set scanning destination file(s) or directory /ies in project' -) + default=os.path.join(proj_root_dir, "out", "debug", + "compile_commands*.json"), + help='Set global pattern for compile_commands.json files.') @click.option( '--mapping-file-dir', - help='Set mapping file directory /ies manually. File should have name iwyu.imp' -) + help='Set directory with iwyu.imp mapping file.') @click.option( '--iwyu-args', show_default=True, default="-Xiwyu --no_fwd_decls", - help='Set custom arg(s) for include what you use' -) + help='Set custom arg(s) for include what you use.') @click.option( '--clang-args', default="", - help='Set custom arg(s) for clang' -) -def main(compile_commands_glob, scanning_destination, mapping_file_dir, + help='Set custom arg(s) for clang.') +@click.argument( + 'source', + nargs=-1, + type=click.Path(exists=True)) +def main(compile_commands_glob, source, mapping_file_dir, iwyu_args, clang_args, log_level, no_log_timestamps): # Ensures somewhat pretty logging of what is going on log_fmt = '%(asctime)s %(levelname)-7s %(message)s' @@ -114,8 +110,10 @@ def main(compile_commands_glob, scanning_destination, mapping_file_dir, for compile_commands in compile_commands_glob: compile_commands_path = os.path.dirname(compile_commands) - compile_commands_file = os.path.join(compile_commands_path, "compile_commands.json") - logging.debug("Copy compile command file %s to %s", compile_commands, compile_commands_file) + compile_commands_file = os.path.join( + compile_commands_path, "compile_commands.json") + logging.debug("Copy compile command file %s to %s", + compile_commands, compile_commands_file) with contextlib.suppress(shutil.SameFileError): shutil.copyfile(compile_commands, compile_commands_file) @@ -153,14 +151,14 @@ def main(compile_commands_glob, scanning_destination, mapping_file_dir, command_arr = [ iwyu, - "-p", compile_commands_path, scanning_destination, + "-p", compile_commands_path, *source, "--", iwyu_args, "-Xiwyu", "--mapping_file=" + mapping_file_dir + "/iwyu.imp", ] + platform_clang_args + [clang_args] logging.info("Used compile commands: %s", compile_commands) logging.info("Scanning includes for platform: %s", platform) - logging.info("Scanning destination: %s", scanning_destination) + logging.info("Scanning sources(s): %s", ", ".join(source)) logging.debug("Command: %s", " ".join(command_arr)) status = subprocess.Popen(" ".join(command_arr), @@ -175,13 +173,13 @@ def main(compile_commands_glob, scanning_destination, mapping_file_dir, for line in status.stdout: line = line.rstrip() - if re.match(r"^warning:.*$", line): + if re.search(r"^warning:", line): logger = logging.warning - elif re.match(r"^.*([A-Za-z0-9]+(/[A-Za-z0-9]+)+)\.cpp should [a-zA-Z]+ these lines:$", line): + elif re.search(r"should (add|remove)? these lines:$", line): logger = logging.warning - elif re.match(r"^.*([A-Za-z0-9]+(/[A-Za-z0-9]+)+)\.[a-zA-Z]+ has correct #includes/fwd-decls\)$", line): + elif re.search(r"has correct #includes/fwd-decls\)$", line): logger = logging.info - elif re.match(r"^The full include-list for .*$", line): + elif re.search(r"^The full include-list for", line): logger = logging.warning warning_in_files += 1 @@ -190,7 +188,8 @@ def main(compile_commands_glob, scanning_destination, mapping_file_dir, logging.info("============== IWYU output end ================") if warning_in_files: - logging.error("Number of files with include issues: %d", warning_in_files) + logging.error("Number of files with include issues: %d", + warning_in_files) sys.exit(2) else: logging.info("Every include looks good!") diff --git a/scripts/py_matter_idl/matter_idl/README.md b/scripts/py_matter_idl/matter_idl/README.md index bd4d3ef468188d..602e8565fac829 100644 --- a/scripts/py_matter_idl/matter_idl/README.md +++ b/scripts/py_matter_idl/matter_idl/README.md @@ -182,7 +182,7 @@ directory of this README). Most of the heavy lifting is done by the lark using content - [matter_idl_parser.py](./matter_idl_parser.py) has a transformer that converts the text given by lark into a more type-safe (and type-rich) AST as - defined ing [matter_idl_types.py](./matter_idl_types.py) + defined in [matter_idl_types.py](./matter_idl_types.py) ## Code generation diff --git a/scripts/setup/requirements.nxp.txt b/scripts/setup/requirements.nxp.txt new file mode 100644 index 00000000000000..6db976c85da690 --- /dev/null +++ b/scripts/setup/requirements.nxp.txt @@ -0,0 +1,3 @@ +jsonschema>=4.17.0 +pycrypto>=2.6.1 +pycryptodome>=3.20.0 diff --git a/scripts/setup/zap.json b/scripts/setup/zap.json index 173a68633f6d0e..4e7da8f6d30a7c 100644 --- a/scripts/setup/zap.json +++ b/scripts/setup/zap.json @@ -8,13 +8,13 @@ "mac-amd64", "windows-amd64" ], - "tags": ["version:2@v2024.03.14-nightly.1"] + "tags": ["version:2@v2024.04.15-nightly.1"] }, { "_comment": "Always get the amd64 version on mac until usable arm64 zap build is available", "path": "fuchsia/third_party/zap/mac-amd64", "platforms": ["mac-arm64"], - "tags": ["version:2@v2024.03.14-nightly.1"] + "tags": ["version:2@v2024.04.15-nightly.1"] } ] } diff --git a/scripts/setup/zap.version b/scripts/setup/zap.version index 6f551d6ac92803..cdc8952361f654 100644 --- a/scripts/setup/zap.version +++ b/scripts/setup/zap.version @@ -1 +1 @@ -v2024.03.14-nightly +v2024.04.15-nightly diff --git a/scripts/tools/generate_esp32_chip_factory_bin.py b/scripts/tools/generate_esp32_chip_factory_bin.py index a4ccce52c0ab77..ff00daedb53682 100755 --- a/scripts/tools/generate_esp32_chip_factory_bin.py +++ b/scripts/tools/generate_esp32_chip_factory_bin.py @@ -18,15 +18,12 @@ import argparse import base64 -import enum import logging import os import sys from types import SimpleNamespace import cryptography.x509 -from bitarray import bitarray -from bitarray.util import ba2int from esp_secure_cert.tlv_format import generate_partition_ds, generate_partition_no_ds, tlv_priv_key_t, tlv_priv_key_type_t CHIP_TOPDIR = os.path.dirname(os.path.realpath(__file__))[:-len(os.path.join('scripts', 'tools'))] @@ -152,52 +149,9 @@ 'encoding': 'hex2bin', 'value': None, }, - # DeviceInfoProvider - 'cal-types': { - 'type': 'data', - 'encoding': 'u32', - 'value': None, - }, - 'locale-sz': { - 'type': 'data', - 'encoding': 'u32', - 'value': None, - }, - - # Other device info provider keys are dynamically generated - # in the respective functions. } -class CalendarTypes(enum.Enum): - Buddhist = 0 - Chinese = 1 - Coptic = 2 - Ethiopian = 3 - Gregorian = 4 - Hebrew = 5 - Indian = 6 - Islamic = 7 - Japanese = 8 - Korean = 9 - Persian = 10 - Taiwanese = 11 - - -# Supported Calendar types is stored as a bit array in one uint32_t. -def calendar_types_to_uint32(calendar_types): - result = bitarray(32, endian='little') - result.setall(0) - for calendar_type in calendar_types: - try: - result[CalendarTypes[calendar_type].value] = 1 - except KeyError: - logging.error('Unknown calendar type: %s', calendar_type) - logging.error('Supported calendar types: %s', ', '.join(CalendarTypes.__members__)) - sys.exit(1) - return ba2int(result) - - def ishex(s): try: _ = int(s, 16) @@ -205,31 +159,6 @@ def ishex(s): except ValueError: return False -# get_fixed_label_dict() converts the list of strings to per endpoint dictionaries. -# example input : ['0/orientation/up', '1/orientation/down', '2/orientation/down'] -# example output : {'0': [{'orientation': 'up'}], '1': [{'orientation': 'down'}], '2': [{'orientation': 'down'}]} - - -def get_fixed_label_dict(fixed_labels): - fl_dict = {} - for fl in fixed_labels: - _l = fl.split('/') - - if len(_l) != 3: - logging.error('Invalid fixed label: %s', fl) - sys.exit(1) - - if not (ishex(_l[0]) and (len(_l[1]) > 0 and len(_l[1]) < 16) and (len(_l[2]) > 0 and len(_l[2]) < 16)): - logging.error('Invalid fixed label: %s', fl) - sys.exit(1) - - if _l[0] not in fl_dict.keys(): - fl_dict[_l[0]] = list() - - fl_dict[_l[0]].append({_l[1]: _l[2]}) - - return fl_dict - # get_supported_modes_dict() converts the list of strings to per endpoint dictionaries. # example with semantic tags # input : ['0/label1/1/"1\0x8000, 2\0x8000" 1/label2/1/"1\0x8000, 2\0x8000"'] @@ -373,52 +302,6 @@ def populate_factory_data(args, spake2p_params): if args.hw_ver_str: FACTORY_DATA['hw-ver-str']['value'] = args.hw_ver_str - if args.calendar_types: - FACTORY_DATA['cal-types']['value'] = calendar_types_to_uint32(args.calendar_types) - - # Supported locale is stored as multiple entries, key format: "locale/, example key: "locale/0" - if args.locales: - FACTORY_DATA['locale-sz']['value'] = len(args.locales) - - for i in range(len(args.locales)): - _locale = { - 'type': 'data', - 'encoding': 'string', - 'value': args.locales[i] - } - FACTORY_DATA.update({'locale/{:x}'.format(i): _locale}) - - # Each endpoint can contains the fixed lables - # - fl-sz/ : number of fixed labels for the endpoint - # - fl-k// : fixed label key for the endpoint and index - # - fl-v// : fixed label value for the endpoint and index - if args.fixed_labels: - dict = get_fixed_label_dict(args.fixed_labels) - for key in dict.keys(): - _sz = { - 'type': 'data', - 'encoding': 'u32', - 'value': len(dict[key]) - } - FACTORY_DATA.update({'fl-sz/{:x}'.format(int(key)): _sz}) - - for i in range(len(dict[key])): - entry = dict[key][i] - - _label_key = { - 'type': 'data', - 'encoding': 'string', - 'value': list(entry.keys())[0] - } - _label_value = { - 'type': 'data', - 'encoding': 'string', - 'value': list(entry.values())[0] - } - - FACTORY_DATA.update({'fl-k/{:x}/{:x}'.format(int(key), i): _label_key}) - FACTORY_DATA.update({'fl-v/{:x}/{:x}'.format(int(key), i): _label_value}) - # SupportedModes are stored as multiple entries # - sm-sz/ : number of supported modes for the endpoint # - sm-label// : supported modes label key for the endpoint and index @@ -584,13 +467,6 @@ def any_base_int(s): return int(s, 0) help=('128-bit unique identifier for generating rotating device identifier, ' 'provide 32-byte hex string, e.g. "1234567890abcdef1234567890abcdef"')) - # These will be used by DeviceInfoProvider - parser.add_argument('--calendar-types', nargs='+', - help=('List of supported calendar types.\nSupported Calendar Types: Buddhist, Chinese, Coptic, Ethiopian, ' - 'Gregorian, Hebrew, Indian, Islamic, Japanese, Korean, Persian, Taiwanese')) - parser.add_argument('--locales', nargs='+', help='List of supported locales, Language Tag as defined by BCP47, eg. en-US en-GB') - parser.add_argument('--fixed-labels', nargs='+', - help='List of fixed labels, eg: "0/orientation/up" "1/orientation/down" "2/orientation/down"') parser.add_argument('--supported-modes', type=str, nargs='+', required=False, help='List of supported modes, eg: mode1/label1/ep/"tagValue1\\mfgCode, tagValue2\\mfgCode" mode2/label2/ep/"tagValue1\\mfgCode, tagValue2\\mfgCode" mode3/label3/ep/"tagValue1\\mfgCode, tagValue2\\mfgCode"') diff --git a/scripts/tools/zap/zap_execution.py b/scripts/tools/zap/zap_execution.py index b5880f761dd41d..3256ba069c2790 100644 --- a/scripts/tools/zap/zap_execution.py +++ b/scripts/tools/zap/zap_execution.py @@ -23,7 +23,7 @@ # Use scripts/tools/zap/version_update.py to manage ZAP versioning as many # files may need updating for versions # -MIN_ZAP_VERSION = '2024.3.14' +MIN_ZAP_VERSION = '2024.4.15' class ZapTool: diff --git a/src/BUILD.gn b/src/BUILD.gn index 25f0a57211766b..d283c7ec4defad 100644 --- a/src/BUILD.gn +++ b/src/BUILD.gn @@ -86,6 +86,7 @@ if (chip_build_tests) { chip_device_platform != "efr32") { tests += [ "${chip_root}/src/setup_payload/tests", + "${chip_root}/src/setup_payload/tests:tests_nltest", "${chip_root}/src/transport/raw/tests", ] } diff --git a/src/app/ClusterStateCache.cpp b/src/app/ClusterStateCache.cpp index 7a6eed3de8576c..e3dd3dd8d84ca4 100644 --- a/src/app/ClusterStateCache.cpp +++ b/src/app/ClusterStateCache.cpp @@ -27,14 +27,14 @@ namespace app { namespace { // Determine how much space a StatusIB takes up on the wire. -size_t SizeOfStatusIB(const StatusIB & aStatus) +uint32_t SizeOfStatusIB(const StatusIB & aStatus) { // 1 byte: anonymous tag control byte for struct. // 1 byte: control byte for uint8 value. // 1 byte: context-specific tag for uint8 value. // 1 byte: the uint8 value. // 1 byte: end of container. - size_t size = 5; + uint32_t size = 5; if (aStatus.mClusterStatus.HasValue()) { @@ -49,7 +49,8 @@ size_t SizeOfStatusIB(const StatusIB & aStatus) } // anonymous namespace -CHIP_ERROR ClusterStateCache::GetElementTLVSize(TLV::TLVReader * apData, size_t & aSize) +template +CHIP_ERROR ClusterStateCacheT::GetElementTLVSize(TLV::TLVReader * apData, uint32_t & aSize) { Platform::ScopedMemoryBufferWithSize backingBuffer; TLV::TLVReader reader; @@ -64,8 +65,9 @@ CHIP_ERROR ClusterStateCache::GetElementTLVSize(TLV::TLVReader * apData, size_t return CHIP_NO_ERROR; } -CHIP_ERROR ClusterStateCache::UpdateCache(const ConcreteDataAttributePath & aPath, TLV::TLVReader * apData, - const StatusIB & aStatus) +template +CHIP_ERROR ClusterStateCacheT::UpdateCache(const ConcreteDataAttributePath & aPath, TLV::TLVReader * apData, + const StatusIB & aStatus) { AttributeState state; bool endpointIsNew = false; @@ -82,24 +84,32 @@ CHIP_ERROR ClusterStateCache::UpdateCache(const ConcreteDataAttributePath & aPat if (apData) { - size_t elementSize = 0; + uint32_t elementSize = 0; ReturnErrorOnFailure(GetElementTLVSize(apData, elementSize)); - if (mCacheData) + if constexpr (CanEnableDataCaching) { - Platform::ScopedMemoryBufferWithSize backingBuffer; - backingBuffer.Calloc(elementSize); - VerifyOrReturnError(backingBuffer.Get() != nullptr, CHIP_ERROR_NO_MEMORY); - TLV::ScopedBufferTLVWriter writer(std::move(backingBuffer), elementSize); - ReturnErrorOnFailure(writer.CopyElement(TLV::AnonymousTag(), *apData)); - ReturnErrorOnFailure(writer.Finalize(backingBuffer)); - - state.Set(std::move(backingBuffer)); + if (mCacheData) + { + Platform::ScopedMemoryBufferWithSize backingBuffer; + backingBuffer.Calloc(elementSize); + VerifyOrReturnError(backingBuffer.Get() != nullptr, CHIP_ERROR_NO_MEMORY); + TLV::ScopedBufferTLVWriter writer(std::move(backingBuffer), elementSize); + ReturnErrorOnFailure(writer.CopyElement(TLV::AnonymousTag(), *apData)); + ReturnErrorOnFailure(writer.Finalize(backingBuffer)); + + state.template Set(std::move(backingBuffer)); + } + else + { + state.template Set(elementSize); + } } else { - state.Set(elementSize); + state = elementSize; } + // // Clear out the committed data version and only set it again once we have received all data for this cluster. // Otherwise, we may have incomplete data that looks like it's complete since it has a valid data version. @@ -132,13 +142,20 @@ CHIP_ERROR ClusterStateCache::UpdateCache(const ConcreteDataAttributePath & aPat } else { - if (mCacheData) + if constexpr (CanEnableDataCaching) { - state.Set(aStatus); + if (mCacheData) + { + state.template Set(aStatus); + } + else + { + state.template Set(SizeOfStatusIB(aStatus)); + } } else { - state.Set(SizeOfStatusIB(aStatus)); + state = SizeOfStatusIB(aStatus); } } @@ -161,7 +178,9 @@ CHIP_ERROR ClusterStateCache::UpdateCache(const ConcreteDataAttributePath & aPat return CHIP_NO_ERROR; } -CHIP_ERROR ClusterStateCache::UpdateEventCache(const EventHeader & aEventHeader, TLV::TLVReader * apData, const StatusIB * apStatus) +template +CHIP_ERROR ClusterStateCacheT::UpdateEventCache(const EventHeader & aEventHeader, TLV::TLVReader * apData, + const StatusIB * apStatus) { if (apData) { @@ -208,7 +227,8 @@ CHIP_ERROR ClusterStateCache::UpdateEventCache(const EventHeader & aEventHeader, return CHIP_NO_ERROR; } -void ClusterStateCache::OnReportBegin() +template +void ClusterStateCacheT::OnReportBegin() { mLastReportDataPath = ConcreteClusterPath(kInvalidEndpointId, kInvalidClusterId); mChangedAttributeSet.clear(); @@ -216,7 +236,8 @@ void ClusterStateCache::OnReportBegin() mCallback.OnReportBegin(); } -void ClusterStateCache::CommitPendingDataVersion() +template +void ClusterStateCacheT::CommitPendingDataVersion() { if (!mLastReportDataPath.IsValidConcreteClusterPath()) { @@ -231,7 +252,8 @@ void ClusterStateCache::CommitPendingDataVersion() } } -void ClusterStateCache::OnReportEnd() +template +void ClusterStateCacheT::OnReportEnd() { CommitPendingDataVersion(); mLastReportDataPath = ConcreteClusterPath(kInvalidEndpointId, kInvalidClusterId); @@ -260,26 +282,35 @@ void ClusterStateCache::OnReportEnd() mCallback.OnReportEnd(); } -CHIP_ERROR ClusterStateCache::Get(const ConcreteAttributePath & path, TLV::TLVReader & reader) const +template <> +CHIP_ERROR ClusterStateCacheT::Get(const ConcreteAttributePath & path, TLV::TLVReader & reader) const { CHIP_ERROR err; auto attributeState = GetAttributeState(path.mEndpointId, path.mClusterId, path.mAttributeId, err); ReturnErrorOnFailure(err); - if (attributeState->Is()) + + if (attributeState->template Is()) { return CHIP_ERROR_IM_STATUS_CODE_RECEIVED; } - if (!attributeState->Is()) + if (!attributeState->template Is()) { return CHIP_ERROR_KEY_NOT_FOUND; } - reader.Init(attributeState->Get().Get(), attributeState->Get().AllocatedSize()); + reader.Init(attributeState->template Get().Get(), attributeState->template Get().AllocatedSize()); return reader.Next(); } -CHIP_ERROR ClusterStateCache::Get(EventNumber eventNumber, TLV::TLVReader & reader) const +template <> +CHIP_ERROR ClusterStateCacheT::Get(const ConcreteAttributePath & path, TLV::TLVReader & reader) const +{ + return CHIP_ERROR_KEY_NOT_FOUND; +} + +template +CHIP_ERROR ClusterStateCacheT::Get(EventNumber eventNumber, TLV::TLVReader & reader) const { CHIP_ERROR err; @@ -295,7 +326,9 @@ CHIP_ERROR ClusterStateCache::Get(EventNumber eventNumber, TLV::TLVReader & read return CHIP_NO_ERROR; } -const ClusterStateCache::EndpointState * ClusterStateCache::GetEndpointState(EndpointId endpointId, CHIP_ERROR & err) const +template +const typename ClusterStateCacheT::EndpointState * +ClusterStateCacheT::GetEndpointState(EndpointId endpointId, CHIP_ERROR & err) const { auto endpointIter = mCache.find(endpointId); if (endpointIter == mCache.end()) @@ -308,8 +341,9 @@ const ClusterStateCache::EndpointState * ClusterStateCache::GetEndpointState(End return &endpointIter->second; } -const ClusterStateCache::ClusterState * ClusterStateCache::GetClusterState(EndpointId endpointId, ClusterId clusterId, - CHIP_ERROR & err) const +template +const typename ClusterStateCacheT::ClusterState * +ClusterStateCacheT::GetClusterState(EndpointId endpointId, ClusterId clusterId, CHIP_ERROR & err) const { auto endpointState = GetEndpointState(endpointId, err); if (err != CHIP_NO_ERROR) @@ -328,8 +362,10 @@ const ClusterStateCache::ClusterState * ClusterStateCache::GetClusterState(Endpo return &clusterState->second; } -const ClusterStateCache::AttributeState * ClusterStateCache::GetAttributeState(EndpointId endpointId, ClusterId clusterId, - AttributeId attributeId, CHIP_ERROR & err) const +template +const typename ClusterStateCacheT::AttributeState * +ClusterStateCacheT::GetAttributeState(EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, + CHIP_ERROR & err) const { auto clusterState = GetClusterState(endpointId, clusterId, err); if (err != CHIP_NO_ERROR) @@ -348,7 +384,9 @@ const ClusterStateCache::AttributeState * ClusterStateCache::GetAttributeState(E return &attributeState->second; } -const ClusterStateCache::EventData * ClusterStateCache::GetEventData(EventNumber eventNumber, CHIP_ERROR & err) const +template +const typename ClusterStateCacheT::EventData * +ClusterStateCacheT::GetEventData(EventNumber eventNumber, CHIP_ERROR & err) const { EventData compareKey; @@ -364,7 +402,9 @@ const ClusterStateCache::EventData * ClusterStateCache::GetEventData(EventNumber return &(*eventData); } -void ClusterStateCache::OnAttributeData(const ConcreteDataAttributePath & aPath, TLV::TLVReader * apData, const StatusIB & aStatus) +template +void ClusterStateCacheT::OnAttributeData(const ConcreteDataAttributePath & aPath, TLV::TLVReader * apData, + const StatusIB & aStatus) { // // Since the cache itself is a ReadClient::Callback, it may be incorrectly passed in directly when registering with the @@ -394,7 +434,9 @@ void ClusterStateCache::OnAttributeData(const ConcreteDataAttributePath & aPath, mCallback.OnAttributeData(aPath, apData ? &dataSnapshot : nullptr, aStatus); } -CHIP_ERROR ClusterStateCache::GetVersion(const ConcreteClusterPath & aPath, Optional & aVersion) const +template +CHIP_ERROR ClusterStateCacheT::GetVersion(const ConcreteClusterPath & aPath, + Optional & aVersion) const { VerifyOrReturnError(aPath.IsValidConcreteClusterPath(), CHIP_ERROR_INVALID_ARGUMENT); CHIP_ERROR err; @@ -404,7 +446,9 @@ CHIP_ERROR ClusterStateCache::GetVersion(const ConcreteClusterPath & aPath, Opti return CHIP_NO_ERROR; } -void ClusterStateCache::OnEventData(const EventHeader & aEventHeader, TLV::TLVReader * apData, const StatusIB * apStatus) +template +void ClusterStateCacheT::OnEventData(const EventHeader & aEventHeader, TLV::TLVReader * apData, + const StatusIB * apStatus) { VerifyOrDie(apData != nullptr || apStatus != nullptr); @@ -418,23 +462,31 @@ void ClusterStateCache::OnEventData(const EventHeader & aEventHeader, TLV::TLVRe mCallback.OnEventData(aEventHeader, apData ? &dataSnapshot : nullptr, apStatus); } -CHIP_ERROR ClusterStateCache::GetStatus(const ConcreteAttributePath & path, StatusIB & status) const +template <> +CHIP_ERROR ClusterStateCacheT::GetStatus(const ConcreteAttributePath & path, StatusIB & status) const { CHIP_ERROR err; auto attributeState = GetAttributeState(path.mEndpointId, path.mClusterId, path.mAttributeId, err); ReturnErrorOnFailure(err); - if (!attributeState->Is()) + if (!attributeState->template Is()) { return CHIP_ERROR_INVALID_ARGUMENT; } - status = attributeState->Get(); + status = attributeState->template Get(); return CHIP_NO_ERROR; } -CHIP_ERROR ClusterStateCache::GetStatus(const ConcreteEventPath & path, StatusIB & status) const +template <> +CHIP_ERROR ClusterStateCacheT::GetStatus(const ConcreteAttributePath & path, StatusIB & status) const +{ + return CHIP_ERROR_INVALID_ARGUMENT; +} + +template +CHIP_ERROR ClusterStateCacheT::GetStatus(const ConcreteEventPath & path, StatusIB & status) const { auto statusIter = mEventStatusCache.find(path); if (statusIter == mEventStatusCache.end()) @@ -446,7 +498,8 @@ CHIP_ERROR ClusterStateCache::GetStatus(const ConcreteEventPath & path, StatusIB return CHIP_NO_ERROR; } -void ClusterStateCache::GetSortedFilters(std::vector> & aVector) const +template +void ClusterStateCacheT::GetSortedFilters(std::vector> & aVector) const { for (auto const & endpointIter : mCache) { @@ -463,26 +516,33 @@ void ClusterStateCache::GetSortedFilters(std::vector()) - { - clusterSize += SizeOfStatusIB(attributeIter.second.Get()); - } - else if (attributeIter.second.Is()) + if constexpr (CanEnableDataCaching) { - clusterSize += attributeIter.second.Get(); + if (attributeIter.second.template Is()) + { + clusterSize += SizeOfStatusIB(attributeIter.second.template Get()); + } + else if (attributeIter.second.template Is()) + { + clusterSize += attributeIter.second.template Get(); + } + else + { + VerifyOrDie(attributeIter.second.template Is()); + TLV::TLVReader bufReader; + bufReader.Init(attributeIter.second.template Get().Get(), + attributeIter.second.template Get().AllocatedSize()); + ReturnOnFailure(bufReader.Next()); + // Skip to the end of the element. + ReturnOnFailure(bufReader.Skip()); + + // Compute the amount of value data + clusterSize += bufReader.GetLengthRead(); + } } else { - VerifyOrDie(attributeIter.second.Is()); - TLV::TLVReader bufReader; - bufReader.Init(attributeIter.second.Get().Get(), - attributeIter.second.Get().AllocatedSize()); - ReturnOnFailure(bufReader.Next()); - // Skip to the end of the element. - ReturnOnFailure(bufReader.Skip()); - - // Compute the amount of value data - clusterSize += bufReader.GetLengthRead(); + clusterSize += attributeIter.second; } } @@ -505,9 +565,10 @@ void ClusterStateCache::GetSortedFilters(std::vector & aAttributePaths, - bool & aEncodedDataVersionList) +template +CHIP_ERROR ClusterStateCacheT::OnUpdateDataVersionFilterList( + DataVersionFilterIBs::Builder & aDataVersionFilterIBsBuilder, const Span & aAttributePaths, + bool & aEncodedDataVersionList) { CHIP_ERROR err = CHIP_NO_ERROR; TLV::TLVWriter backup; @@ -587,7 +648,8 @@ CHIP_ERROR ClusterStateCache::OnUpdateDataVersionFilterList(DataVersionFilterIBs return err; } -CHIP_ERROR ClusterStateCache::GetLastReportDataPath(ConcreteClusterPath & aPath) +template +CHIP_ERROR ClusterStateCacheT::GetLastReportDataPath(ConcreteClusterPath & aPath) { if (mLastReportDataPath.IsValidConcreteClusterPath()) { @@ -596,5 +658,10 @@ CHIP_ERROR ClusterStateCache::GetLastReportDataPath(ConcreteClusterPath & aPath) } return CHIP_ERROR_INCORRECT_STATE; } + +// Ensure that our out-of-line template methods actually get compiled. +template class ClusterStateCacheT; +template class ClusterStateCacheT; + } // namespace app } // namespace chip diff --git a/src/app/ClusterStateCache.h b/src/app/ClusterStateCache.h index 4c663a2a5fc2f9..7f7e9e96e855a9 100644 --- a/src/app/ClusterStateCache.h +++ b/src/app/ClusterStateCache.h @@ -66,7 +66,8 @@ namespace app { * 2. The same cache cannot be used by multiple subscribe/read interactions at the same time. * */ -class ClusterStateCache : protected ReadClient::Callback +template +class ClusterStateCacheT : protected ReadClient::Callback { public: class Callback : public ReadClient::Callback @@ -83,17 +84,17 @@ class ClusterStateCache : protected ReadClient::Callback /* * Called anytime an attribute value has changed in the cache */ - virtual void OnAttributeChanged(ClusterStateCache * cache, const ConcreteAttributePath & path){}; + virtual void OnAttributeChanged(ClusterStateCacheT * cache, const ConcreteAttributePath & path){}; /* * Called anytime any attribute in a cluster has changed in the cache */ - virtual void OnClusterChanged(ClusterStateCache * cache, EndpointId endpointId, ClusterId clusterId){}; + virtual void OnClusterChanged(ClusterStateCacheT * cache, EndpointId endpointId, ClusterId clusterId){}; /* * Called anytime an endpoint was added to the cache */ - virtual void OnEndpointAdded(ClusterStateCache * cache, EndpointId endpointId){}; + virtual void OnEndpointAdded(ClusterStateCacheT * cache, EndpointId endpointId){}; }; /** @@ -104,18 +105,25 @@ class ClusterStateCache : protected ReadClient::Callback * @param [in] cacheData boolean to decide whether this cache would store attribute/event data/status, * the default is true. */ - ClusterStateCache(Callback & callback, Optional highestReceivedEventNumber = Optional::Missing(), - bool cacheData = true) : + ClusterStateCacheT(Callback & callback, Optional highestReceivedEventNumber = Optional::Missing()) : + mCallback(callback), mBufferedReader(*this) + { + mHighestReceivedEventNumber = highestReceivedEventNumber; + } + + template = true> + ClusterStateCacheT(Callback & callback, Optional highestReceivedEventNumber = Optional::Missing(), + bool cacheData = true) : mCallback(callback), mBufferedReader(*this), mCacheData(cacheData) { mHighestReceivedEventNumber = highestReceivedEventNumber; } - ClusterStateCache(const ClusterStateCache &) = delete; - ClusterStateCache(ClusterStateCache &&) = delete; - ClusterStateCache & operator=(const ClusterStateCache &) = delete; - ClusterStateCache & operator=(ClusterStateCache &&) = delete; + ClusterStateCacheT(const ClusterStateCacheT &) = delete; + ClusterStateCacheT(ClusterStateCacheT &&) = delete; + ClusterStateCacheT & operator=(const ClusterStateCacheT &) = delete; + ClusterStateCacheT & operator=(ClusterStateCacheT &&) = delete; void SetHighestReceivedEventNumber(EventNumber highestReceivedEventNumber) { @@ -534,8 +542,12 @@ class ClusterStateCache : protected ReadClient::Callback // * If we got data for the attribute and we are not storing data // oureselves, the size of the data, so we can still prioritize sending // DataVersions correctly. + // + // The data for a single attribute is not going to be gigabytes in size, so + // using uint32_t for the size is fine; on 64-bit systems this can save + // quite a bit of space. using AttributeData = Platform::ScopedMemoryBufferWithSize; - using AttributeState = Variant; + using AttributeState = std::conditional_t, uint32_t>; // mPendingDataVersion represents a tentative data version for a cluster that we have gotten some reports for. // // mCurrentDataVersion represents a known data version for a cluster. In order for this to have a @@ -659,7 +671,7 @@ class ClusterStateCache : protected ReadClient::Callback // on the wire if not all filters can be applied. void GetSortedFilters(std::vector> & aVector) const; - CHIP_ERROR GetElementTLVSize(TLV::TLVReader * apData, size_t & aSize); + CHIP_ERROR GetElementTLVSize(TLV::TLVReader * apData, uint32_t & aSize); Callback & mCallback; NodeState mCache; @@ -672,9 +684,12 @@ class ClusterStateCache : protected ReadClient::Callback std::map mEventStatusCache; BufferedReadCallback mBufferedReader; ConcreteClusterPath mLastReportDataPath = ConcreteClusterPath(kInvalidEndpointId, kInvalidClusterId); - const bool mCacheData = true; + const bool mCacheData = CanEnableDataCaching; }; +using ClusterStateCache = ClusterStateCacheT; +using ClusterStateCacheNoData = ClusterStateCacheT; + }; // namespace app }; // namespace chip #endif // CHIP_CONFIG_ENABLE_READ_CLIENT diff --git a/src/app/CommandHandler.cpp b/src/app/CommandHandler.cpp index 901cc658580749..005067c96bd7c4 100644 --- a/src/app/CommandHandler.cpp +++ b/src/app/CommandHandler.cpp @@ -158,7 +158,7 @@ CHIP_ERROR CommandHandler::ValidateInvokeRequestMessageAndBuildRegistry(InvokeRe // Grab the CommandRef if there is one, and validate that it's there when it // has to be. - Optional commandRef; + std::optional commandRef; uint16_t ref; err = commandData.GetRef(&ref); VerifyOrReturnError(err == CHIP_NO_ERROR || err == CHIP_END_OF_TLV, err); @@ -168,7 +168,7 @@ CHIP_ERROR CommandHandler::ValidateInvokeRequestMessageAndBuildRegistry(InvokeRe } if (err == CHIP_NO_ERROR) { - commandRef.SetValue(ref); + commandRef.emplace(ref); } // Adding can fail if concretePath is not unique, or if commandRef is a value @@ -590,10 +590,9 @@ CHIP_ERROR CommandHandler::PrepareInvokeResponseCommand(const ConcreteCommandPat const CommandHandler::InvokeResponseParameters & aPrepareParameters) { auto commandPathRegistryEntry = GetCommandPathRegistry().Find(aPrepareParameters.mRequestCommandPath); - VerifyOrReturnValue(commandPathRegistryEntry.HasValue(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnValue(commandPathRegistryEntry.has_value(), CHIP_ERROR_INCORRECT_STATE); - return PrepareInvokeResponseCommand(commandPathRegistryEntry.Value(), aResponseCommandPath, - aPrepareParameters.mStartOrEndDataStruct); + return PrepareInvokeResponseCommand(*commandPathRegistryEntry, aResponseCommandPath, aPrepareParameters.mStartOrEndDataStruct); } CHIP_ERROR CommandHandler::PrepareCommand(const ConcreteCommandPath & aResponseCommandPath, bool aStartDataStruct) @@ -610,9 +609,9 @@ CHIP_ERROR CommandHandler::PrepareCommand(const ConcreteCommandPath & aResponseC "Seemingly device supports batch commands, but is calling the deprecated PrepareCommand API"); auto commandPathRegistryEntry = GetCommandPathRegistry().GetFirstEntry(); - VerifyOrReturnValue(commandPathRegistryEntry.HasValue(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnValue(commandPathRegistryEntry.has_value(), CHIP_ERROR_INCORRECT_STATE); - return PrepareInvokeResponseCommand(commandPathRegistryEntry.Value(), aResponseCommandPath, aStartDataStruct); + return PrepareInvokeResponseCommand(*commandPathRegistryEntry, aResponseCommandPath, aStartDataStruct); } CHIP_ERROR CommandHandler::PrepareInvokeResponseCommand(const CommandPathRegistryEntry & apCommandPathRegistryEntry, @@ -675,9 +674,9 @@ CHIP_ERROR CommandHandler::FinishCommand(bool aStartDataStruct) ReturnErrorOnFailure(commandData.GetWriter()->EndContainer(mDataElementContainerType)); } - if (mRefForResponse.HasValue()) + if (mRefForResponse.has_value()) { - ReturnErrorOnFailure(commandData.Ref(mRefForResponse.Value())); + ReturnErrorOnFailure(commandData.Ref(*mRefForResponse)); } ReturnErrorOnFailure(commandData.EndOfCommandDataIB()); @@ -699,8 +698,8 @@ CHIP_ERROR CommandHandler::PrepareStatus(const ConcreteCommandPath & aCommandPat } auto commandPathRegistryEntry = GetCommandPathRegistry().Find(aCommandPath); - VerifyOrReturnError(commandPathRegistryEntry.HasValue(), CHIP_ERROR_INCORRECT_STATE); - mRefForResponse = commandPathRegistryEntry.Value().ref; + VerifyOrReturnError(commandPathRegistryEntry.has_value(), CHIP_ERROR_INCORRECT_STATE); + mRefForResponse = commandPathRegistryEntry->ref; MoveToState(State::Preparing); InvokeResponseIBs::Builder & invokeResponses = mInvokeResponseBuilder.GetInvokeResponses(); @@ -720,9 +719,9 @@ CHIP_ERROR CommandHandler::FinishStatus() VerifyOrReturnError(mState == State::AddingCommand, CHIP_ERROR_INCORRECT_STATE); CommandStatusIB::Builder & commandStatus = mInvokeResponseBuilder.GetInvokeResponses().GetInvokeResponse().GetStatus(); - if (mRefForResponse.HasValue()) + if (mRefForResponse.has_value()) { - ReturnErrorOnFailure(commandStatus.Ref(mRefForResponse.Value())); + ReturnErrorOnFailure(commandStatus.Ref(*mRefForResponse)); } ReturnErrorOnFailure(mInvokeResponseBuilder.GetInvokeResponses().GetInvokeResponse().GetStatus().EndOfCommandStatusIB()); diff --git a/src/app/CommandHandler.h b/src/app/CommandHandler.h index e31edfd444c629..2eed73daccdda9 100644 --- a/src/app/CommandHandler.h +++ b/src/app/CommandHandler.h @@ -686,7 +686,7 @@ class CommandHandler // TODO Allow flexibility in registration. BasicCommandPathRegistry mBasicCommandPathRegistry; CommandPathRegistry * mCommandPathRegistry = &mBasicCommandPathRegistry; - Optional mRefForResponse; + std::optional mRefForResponse; CommandHandlerExchangeInterface * mpResponder = nullptr; diff --git a/src/app/CommandPathRegistry.h b/src/app/CommandPathRegistry.h index 0d914ef1de3348..da0d16e1f69109 100644 --- a/src/app/CommandPathRegistry.h +++ b/src/app/CommandPathRegistry.h @@ -24,13 +24,15 @@ #include #include +#include + namespace chip { namespace app { struct CommandPathRegistryEntry { ConcreteCommandPath requestPath = ConcreteCommandPath(0, 0, 0); - Optional ref; + std::optional ref; }; class CommandPathRegistry @@ -38,11 +40,11 @@ class CommandPathRegistry public: virtual ~CommandPathRegistry() = default; - virtual Optional Find(const ConcreteCommandPath & requestPath) const = 0; - virtual Optional GetFirstEntry() const = 0; - virtual CHIP_ERROR Add(const ConcreteCommandPath & requestPath, const Optional & ref) = 0; - virtual size_t Count() const = 0; - virtual size_t MaxSize() const = 0; + virtual std::optional Find(const ConcreteCommandPath & requestPath) const = 0; + virtual std::optional GetFirstEntry() const = 0; + virtual CHIP_ERROR Add(const ConcreteCommandPath & requestPath, const std::optional & ref) = 0; + virtual size_t Count() const = 0; + virtual size_t MaxSize() const = 0; }; /** @@ -59,28 +61,28 @@ template class BasicCommandPathRegistry : public CommandPathRegistry { public: - Optional Find(const ConcreteCommandPath & requestPath) const override + std::optional Find(const ConcreteCommandPath & requestPath) const override { for (size_t i = 0; i < mCount; i++) { if (mTable[i].requestPath == requestPath) { - return MakeOptional(mTable[i]); + return std::make_optional(mTable[i]); } } - return NullOptional; + return std::nullopt; } - Optional GetFirstEntry() const override + std::optional GetFirstEntry() const override { if (mCount > 0) { - return MakeOptional(mTable[0]); + return std::make_optional(mTable[0]); } - return NullOptional; + return std::nullopt; } - CHIP_ERROR Add(const ConcreteCommandPath & requestPath, const Optional & ref) override + CHIP_ERROR Add(const ConcreteCommandPath & requestPath, const std::optional & ref) override { if (mCount >= N) { diff --git a/src/app/ConcreteAttributePath.h b/src/app/ConcreteAttributePath.h index cfde88ab9bd374..03e801bd9b3395 100644 --- a/src/app/ConcreteAttributePath.h +++ b/src/app/ConcreteAttributePath.h @@ -142,7 +142,10 @@ struct ConcreteDataAttributePath : public ConcreteAttributePath ChipLogValueMEI(mClusterId), ChipLogValueMEI(mAttributeId)); } - bool MatchesConcreteAttributePath(const ConcreteAttributePath & aOther) { return ConcreteAttributePath::operator==(aOther); } + bool MatchesConcreteAttributePath(const ConcreteAttributePath & aOther) const + { + return ConcreteAttributePath::operator==(aOther); + } bool operator==(const ConcreteDataAttributePath & aOther) const { diff --git a/src/app/clusters/bindings/BindingManager.cpp b/src/app/clusters/bindings/BindingManager.cpp index b765146ed55153..936324c19e045c 100644 --- a/src/app/clusters/bindings/BindingManager.cpp +++ b/src/app/clusters/bindings/BindingManager.cpp @@ -185,7 +185,7 @@ CHIP_ERROR BindingManager::NotifyBoundClusterChanged(EndpointId endpoint, Cluste for (auto iter = BindingTable::GetInstance().begin(); iter != BindingTable::GetInstance().end(); ++iter) { - if (iter->local == endpoint && (!iter->clusterId.HasValue() || iter->clusterId.Value() == cluster)) + if (iter->local == endpoint && (iter->clusterId.value_or(cluster) == cluster)) { if (iter->type == MATTER_UNICAST_BINDING) { diff --git a/src/app/clusters/bindings/PendingNotificationMap.h b/src/app/clusters/bindings/PendingNotificationMap.h index c06a0a426d434c..1b187df74c7e1c 100644 --- a/src/app/clusters/bindings/PendingNotificationMap.h +++ b/src/app/clusters/bindings/PendingNotificationMap.h @@ -88,9 +88,9 @@ class PendingNotificationMap return *this; } - bool operator!=(const Iterator & rhs) { return mIndex != rhs.mIndex; } + bool operator!=(const Iterator & rhs) const { return mIndex != rhs.mIndex; } - bool operator==(const Iterator & rhs) { return mIndex == rhs.mIndex; } + bool operator==(const Iterator & rhs) const { return mIndex == rhs.mIndex; } private: PendingNotificationMap * mMap; diff --git a/src/app/clusters/bindings/bindings.cpp b/src/app/clusters/bindings/bindings.cpp index 8404dee7a7899f..d7c1712baf9672 100644 --- a/src/app/clusters/bindings/bindings.cpp +++ b/src/app/clusters/bindings/bindings.cpp @@ -125,12 +125,13 @@ CHIP_ERROR CreateBindingEntry(const TargetStructType & entry, EndpointId localEn if (entry.group.HasValue()) { - bindingEntry = EmberBindingTableEntry::ForGroup(entry.fabricIndex, entry.group.Value(), localEndpoint, entry.cluster); + bindingEntry = + EmberBindingTableEntry::ForGroup(entry.fabricIndex, entry.group.Value(), localEndpoint, entry.cluster.std_optional()); } else { bindingEntry = EmberBindingTableEntry::ForNode(entry.fabricIndex, entry.node.Value(), localEndpoint, entry.endpoint.Value(), - entry.cluster); + entry.cluster.std_optional()); } return AddBindingEntry(bindingEntry); @@ -159,7 +160,7 @@ CHIP_ERROR BindingTableAccess::ReadBindingTable(EndpointId endpoint, AttributeVa .node = MakeOptional(entry.nodeId), .group = NullOptional, .endpoint = MakeOptional(entry.remote), - .cluster = entry.clusterId, + .cluster = FromStdOptional(entry.clusterId), .fabricIndex = entry.fabricIndex, }; ReturnErrorOnFailure(subEncoder.Encode(value)); @@ -170,7 +171,7 @@ CHIP_ERROR BindingTableAccess::ReadBindingTable(EndpointId endpoint, AttributeVa .node = NullOptional, .group = MakeOptional(entry.groupId), .endpoint = NullOptional, - .cluster = entry.clusterId, + .cluster = FromStdOptional(entry.clusterId), .fabricIndex = entry.fabricIndex, }; ReturnErrorOnFailure(subEncoder.Encode(value)); diff --git a/src/app/clusters/group-key-mgmt-server/group-key-mgmt-server.cpp b/src/app/clusters/group-key-mgmt-server/group-key-mgmt-server.cpp index c3cf09eb283f63..518e28b94fbd2b 100644 --- a/src/app/clusters/group-key-mgmt-server/group-key-mgmt-server.cpp +++ b/src/app/clusters/group-key-mgmt-server/group-key-mgmt-server.cpp @@ -84,7 +84,7 @@ struct GroupTableCodec TLV::TLVType inner; ReturnErrorOnFailure(writer.StartContainer(TagEndpoints(), TLV::kTLVType_Array, inner)); GroupDataProvider::GroupEndpoint mapping; - auto iter = mProvider->IterateEndpoints(mFabric, MakeOptional(mInfo.group_id)); + auto iter = mProvider->IterateEndpoints(mFabric, std::make_optional(mInfo.group_id)); if (nullptr != iter) { while (iter->Next(mapping)) diff --git a/src/app/clusters/scenes-server/SceneTable.h b/src/app/clusters/scenes-server/SceneTable.h index 1b634211ead063..6e384609c11057 100644 --- a/src/app/clusters/scenes-server/SceneTable.h +++ b/src/app/clusters/scenes-server/SceneTable.h @@ -149,7 +149,7 @@ class SceneTable bool IsValid() { return (mSceneId != kUndefinedSceneId); } - bool operator==(const SceneStorageId & other) { return (mGroupId == other.mGroupId && mSceneId == other.mSceneId); } + bool operator==(const SceneStorageId & other) const { return (mGroupId == other.mGroupId && mSceneId == other.mSceneId); } }; /// @brief struct used to store data held in a scene @@ -235,7 +235,7 @@ class SceneTable SceneTableEntry(SceneStorageId id) : mStorageId(id) {} SceneTableEntry(const SceneStorageId id, const SceneData data) : mStorageId(id), mStorageData(data) {} - bool operator==(const SceneTableEntry & other) + bool operator==(const SceneTableEntry & other) const { return (mStorageId == other.mStorageId && mStorageData == other.mStorageData); } diff --git a/src/app/clusters/thread-network-diagnostics-server/thread-network-diagnostics-server.cpp b/src/app/clusters/thread-network-diagnostics-server/thread-network-diagnostics-server.cpp index 59115c0971cffb..c2e198736ff9e4 100644 --- a/src/app/clusters/thread-network-diagnostics-server/thread-network-diagnostics-server.cpp +++ b/src/app/clusters/thread-network-diagnostics-server/thread-network-diagnostics-server.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -30,6 +31,9 @@ #include #include #include +#include +#include +#include using namespace chip; using namespace chip::app; @@ -133,6 +137,60 @@ CHIP_ERROR ThreadDiagosticsAttrAccess::Read(const ConcreteReadAttributePath & aP return CHIP_NO_ERROR; } +class ThreadDiagnosticsDelegate : public DeviceLayer::ThreadDiagnosticsDelegate +{ + // Notified when the Node’s connection status to a Thread network has changed. + void OnConnectionStatusChanged(ConnectionStatusEnum newConnectionStatus) override + { + ChipLogProgress(Zcl, "ThreadDiagnosticsDelegate: OnConnectionStatusChanged"); + + Events::ConnectionStatus::Type event{ newConnectionStatus }; + + // ThreadNetworkDiagnostics cluster should exist only for endpoint 0. + if (emberAfContainsServer(kRootEndpointId, ThreadNetworkDiagnostics::Id)) + { + // If Thread Network Diagnostics cluster is implemented on this endpoint + EventNumber eventNumber; + + if (CHIP_NO_ERROR != LogEvent(event, kRootEndpointId, eventNumber)) + { + ChipLogError(Zcl, "ThreadDiagnosticsDelegate: Failed to record ConnectionStatus event"); + } + } + } + + // Notified when the Node’s faults related to a Thread network have changed. + void OnNetworkFaultChanged(const GeneralFaults & previous, + const GeneralFaults & current) override + { + ChipLogProgress(Zcl, "ThreadDiagnosticsDelegate: OnNetworkFaultChanged"); + + /* Verify that the data size matches the expected one. */ + static_assert(sizeof(*current.data()) == sizeof(NetworkFaultEnum)); + + DataModel::List currentList(reinterpret_cast(current.data()), + current.size()); + DataModel::List previousList(reinterpret_cast(previous.data()), + previous.size()); + + Events::NetworkFaultChange::Type event{ currentList, previousList }; + + // ThreadNetworkDiagnostics cluster should exist only for endpoint 0. + if (emberAfContainsServer(kRootEndpointId, ThreadNetworkDiagnostics::Id)) + { + // If Thread Network Diagnostics cluster is implemented on this endpoint + EventNumber eventNumber; + + if (CHIP_NO_ERROR != LogEvent(event, kRootEndpointId, eventNumber)) + { + ChipLogError(Zcl, "ThreadDiagnosticsDelegate: Failed to record NetworkFaultChange event"); + } + } + } +}; + +ThreadDiagnosticsDelegate gDiagnosticDelegate; + } // anonymous namespace bool emberAfThreadNetworkDiagnosticsClusterResetCountsCallback(app::CommandHandler * commandObj, @@ -147,4 +205,5 @@ bool emberAfThreadNetworkDiagnosticsClusterResetCountsCallback(app::CommandHandl void MatterThreadNetworkDiagnosticsPluginServerInitCallback() { registerAttributeAccessOverride(&gAttrAccess); + GetDiagnosticDataProvider().SetThreadDiagnosticsDelegate(&gDiagnosticDelegate); } diff --git a/src/app/icd/server/ICDManager.cpp b/src/app/icd/server/ICDManager.cpp index 5f93946fa8eebf..8691a4d1360c64 100644 --- a/src/app/icd/server/ICDManager.cpp +++ b/src/app/icd/server/ICDManager.cpp @@ -378,12 +378,13 @@ void ICDManager::UpdateICDMode() if (ICDConfigurationData::GetInstance().GetICDMode() != tempMode) { ICDConfigurationData::GetInstance().SetICDMode(tempMode); - postObserverEvent(ObserverEventType::ICDModeChange); // Can't use attribute accessors/Attributes::OperatingMode::Set in unit tests #if !CONFIG_BUILD_FOR_HOST_UNIT_TEST Attributes::OperatingMode::Set(kRootEndpointId, static_cast(tempMode)); #endif + + postObserverEvent(ObserverEventType::ICDModeChange); } // When in SIT mode, the slow poll interval SHOULDN'T be greater than the SIT mode polling threshold, per spec. @@ -433,6 +434,8 @@ void ICDManager::UpdateOperationState(OperationalState state) { ChipLogError(AppServer, "Failed to set Slow Polling Interval: err %" CHIP_ERROR_FORMAT, err.Format()); } + + postObserverEvent(ObserverEventType::EnterIdleMode); } else if (state == OperationalState::ActiveMode) { @@ -447,7 +450,7 @@ void ICDManager::UpdateOperationState(OperationalState state) if (activeModeDuration == kZero && !mKeepActiveFlags.HasAny()) { - // A Network Activity triggered the active mode and activeModeDuration is 0. + // Network Activity triggered the active mode and activeModeDuration is 0. // Stay active for at least Active Mode Threshold. activeModeDuration = ICDConfigurationData::GetInstance().GetActiveModeThreshold(); } @@ -455,9 +458,14 @@ void ICDManager::UpdateOperationState(OperationalState state) DeviceLayer::SystemLayer().StartTimer(activeModeDuration, OnActiveModeDone, this); Milliseconds32 activeModeJitterInterval = Milliseconds32(ICD_ACTIVE_TIME_JITTER_MS); + // TODO(#33074): Edge case when we transition to IdleMode with this condition being true + // (activeModeDuration == kZero && !mKeepActiveFlags.HasAny()) activeModeJitterInterval = (activeModeDuration >= activeModeJitterInterval) ? activeModeDuration - activeModeJitterInterval : kZero; + // Reset this flag when we enter ActiveMode to avoid having a feedback loop that keeps us indefinitly in + // ActiveMode. + mTransitionToIdleCalled = false; DeviceLayer::SystemLayer().StartTimer(activeModeJitterInterval, OnTransitionToIdle, this); CHIP_ERROR err = @@ -504,10 +512,6 @@ void ICDManager::OnIdleModeDone(System::Layer * aLayer, void * appState) { ICDManager * pICDManager = reinterpret_cast(appState); pICDManager->UpdateOperationState(OperationalState::ActiveMode); - - // We only reset this flag when idle mode is complete to avoid re-triggering the check when an event brings us back to active, - // which could cause a loop. - pICDManager->mTransitionToIdleCalled = false; } void ICDManager::OnActiveModeDone(System::Layer * aLayer, void * appState) @@ -532,10 +536,10 @@ void ICDManager::OnTransitionToIdle(System::Layer * aLayer, void * appState) } /* ICDListener functions. */ + void ICDManager::OnKeepActiveRequest(KeepActiveFlags request) { assertChipStackLockedByCurrentThread(); - VerifyOrReturn(request < KeepActiveFlagsValues::kInvalidFlag); if (request.Has(KeepActiveFlag::kExchangeContextOpen)) @@ -560,7 +564,6 @@ void ICDManager::OnKeepActiveRequest(KeepActiveFlags request) void ICDManager::OnActiveRequestWithdrawal(KeepActiveFlags request) { assertChipStackLockedByCurrentThread(); - VerifyOrReturn(request < KeepActiveFlagsValues::kInvalidFlag); if (request.Has(KeepActiveFlag::kExchangeContextOpen)) @@ -697,6 +700,10 @@ void ICDManager::postObserverEvent(ObserverEventType event) obs->mObserver->OnEnterActiveMode(); return Loop::Continue; } + case ObserverEventType::EnterIdleMode: { + obs->mObserver->OnEnterIdleMode(); + return Loop::Continue; + } case ObserverEventType::TransitionToIdle: { obs->mObserver->OnTransitionToIdle(); return Loop::Continue; diff --git a/src/app/icd/server/ICDManager.h b/src/app/icd/server/ICDManager.h index 69dfdbf6a88863..bf6e439c62ef52 100644 --- a/src/app/icd/server/ICDManager.h +++ b/src/app/icd/server/ICDManager.h @@ -57,7 +57,9 @@ class TestICDManager; class ICDManager : public ICDListener, public TestEventTriggerHandler { public: - // This structure is used for the creation an ObjectPool of ICDStateObserver pointers + /** + * @brief This structure is used for the creation an ObjectPool of ICDStateObserver pointers + */ struct ObserverPointer { ObserverPointer(ICDStateObserver * obs) : mObserver(obs) {} @@ -71,11 +73,31 @@ class ICDManager : public ICDListener, public TestEventTriggerHandler ActiveMode, }; - // This enum class represents to all ICDStateObserver callbacks available from the - // mStateObserverPool for the ICDManager. + /** + * @brief This enum class represents to all ICDStateObserver callbacks available from the + * mStateObserverPool for the ICDManager. + * + * EnterActiveMode, TransitionToIdle and EnterIdleMode will always be called as a trio in the same order. + * Each event will only be called once per cycle. + * EnterActiveMode will always be called first, when the ICD has transitioned to ActiveMode. + * TransitionToIdle will always be second. This event will only be called the first time there is + * `ICD_ACTIVE_TIME_JITTER_MS` remaining to the ActiveMode timer. + * When this event is called, the ICD is still in ActiveMode. + * If the ActiveMode timer is increased due to the TransitionToIdle event, the event will not be called a second time in + * a given cycle. + * OnEnterIdleMode will always the third when the ICD has transitioned to IdleMode. + * + * The ICDModeChange event can occur independently from the EnterActiveMode, TransitionToIdle and EnterIdleMode. + * It will typpically hapen at the ICDManager init when a client is already registered with the ICD before the + * OnEnterIdleMode event or when a client send a register command after the OnEnterActiveMode event. Nothing prevents the + * ICDModeChange event to happen multiple times per cycle or while the ICD is in IdleMode. + * + * See src/app/icd/server/ICDStateObserver.h for more information on the APIs each event triggers + */ enum class ObserverEventType : uint8_t { EnterActiveMode, + EnterIdleMode, TransitionToIdle, ICDModeChange, }; @@ -85,22 +107,31 @@ class ICDManager : public ICDListener, public TestEventTriggerHandler * This type can be used to implement specific verifiers that can be used in the CheckInMessagesWouldBeSent function. * The goal is to avoid having multiple functions that implement the iterator loop with only the check changing. * - * @return true if at least one Check-In message would be sent - * false No Check-In messages would be sent + * @return true: if at least one Check-In message would be sent + * false: No Check-In messages would be sent */ - using ShouldCheckInMsgsBeSentFunction = bool(FabricIndex aFabricIndex, NodeId subjectID); - ICDManager() {} + ICDManager() = default; + ~ICDManager() = default; + void Init(PersistentStorageDelegate * storage, FabricTable * fabricTable, Crypto::SymmetricKeystore * symmetricKeyStore, - Messaging::ExchangeManager * exchangeManager, SubscriptionsInfoProvider * manager); + Messaging::ExchangeManager * exchangeManager, SubscriptionsInfoProvider * subInfoProvider); void Shutdown(); - void UpdateICDMode(); - void UpdateOperationState(OperationalState state); - void SetKeepActiveModeRequirements(KeepActiveFlags flag, bool state); - bool IsKeepActive() { return mKeepActiveFlags.HasAny(); } + + /** + * @brief SupportsFeature verifies if a given FeatureMap bit is enabled + * + * @param[in] feature FeatureMap bit to verify + * + * @return true: if the FeatureMap bit is enabled in the ICDM cluster attribute. + * false: if the FeatureMap bit is not enabled in the ICDM cluster attribute. + * if we failed to read the FeatureMap attribute. + */ bool SupportsFeature(Clusters::IcdManagement::Feature feature); + ICDConfigurationData::ICDMode GetICDMode() { return ICDConfigurationData::GetInstance().GetICDMode(); }; + /** * @brief Adds the referenced observer in parameters to the mStateObserverPool * A maximum of CHIP_CONFIG_ICD_OBSERVERS_POOL_SIZE observers can be concurrently registered @@ -111,20 +142,14 @@ class ICDManager : public ICDListener, public TestEventTriggerHandler /** * @brief Remove the referenced observer in parameters from the mStateObserverPool + * If the observer is not present in the object pool, we do nothing */ void ReleaseObserver(ICDStateObserver * observer); - /** - * @brief Associates the ObserverEventType parameters to the correct - * ICDStateObservers function and calls it for all observers in the mStateObserverPool - */ - void postObserverEvent(ObserverEventType event); - OperationalState GetOperationalState() { return mOperationalState; } - /** * @brief Ensures that the remaining Active Mode duration is at least the smaller of 30000 milliseconds and stayActiveDuration. * - * @param stayActiveDuration The duration (in milliseconds) requested by the client to stay in Active Mode + * @param[in] stayActiveDuration The duration (in milliseconds) requested by the client to stay in Active Mode * @return The duration (in milliseconds) the device will stay in Active Mode */ uint32_t StayActiveRequest(uint32_t stayActiveDuration); @@ -132,15 +157,14 @@ class ICDManager : public ICDListener, public TestEventTriggerHandler /** * @brief TestEventTriggerHandler for the ICD feature set * - * @param eventTrigger Event trigger to handle. + * @param[in] eventTrigger Event trigger to handle. + * * @return CHIP_ERROR CHIP_NO_ERROR - No erros during the processing * CHIP_ERROR_INVALID_ARGUMENT - eventTrigger isn't a valid value */ CHIP_ERROR HandleEventTrigger(uint64_t eventTrigger) override; #if CHIP_CONFIG_ENABLE_ICD_CIP - void SendCheckInMsgs(); - /** * @brief Trigger the ICDManager to send Check-In message if necessary * @@ -160,47 +184,108 @@ class ICDManager : public ICDListener, public TestEventTriggerHandler #if CONFIG_BUILD_FOR_HOST_UNIT_TEST void SetTestFeatureMapValue(uint32_t featureMap) { mFeatureMap = featureMap; }; -#if !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION && CHIP_CONFIG_PERSIST_SUBSCRIPTIONS +#if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION bool GetIsBootUpResumeSubscriptionExecuted() { return mIsBootUpResumeSubscriptionExecuted; }; #endif // !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION && CHIP_CONFIG_PERSIST_SUBSCRIPTIONS #endif // Implementation of ICDListener functions. // Callers must origin from the chip task context or hold the ChipStack lock. + void OnNetworkActivity() override; void OnKeepActiveRequest(KeepActiveFlags request) override; void OnActiveRequestWithdrawal(KeepActiveFlags request) override; void OnICDManagementServerEvent(ICDManagementEvents event) override; void OnSubscriptionReport() override; -protected: +private: friend class TestICDManager; + /** + * @brief UpdateICDMode evaluates in which mode the ICD can be in; SIT or LIT mode. + * If the current operating mode does not match the evaluated operating mode, function updates the ICDMode and triggers + * all necessary operations. + * For a SIT ICD, this function does nothing. + * For a LIT ICD, the function checks if the ICD has a registration in the ICDMonitoringTable to determine which ICDMode + * the ICD must be in. + */ + void UpdateICDMode(); /** - * @brief Hepler function that extends the Active Mode duration as well as the Active Mode Jitter timer for the transition to - * iddle mode. + * @brief UpdateOperationState updates the OperationState of the ICD to the requested one. + * IdleMode -> IdleMode : No actions are necessary, do nothing. + * IdleMode -> ActiveMode : Transition the device to ActiveMode, start the ActiveMode timer and trigger all necessary + * operations. These operations could be : Send Check-In messages + * Send subscription reports + * Process user actions + * ActiveMode -> ActiveMode : Increase remaining ActiveMode timer to one ActiveModeThreshold. + * If ActiveModeThreshold is 0, do nothing. + * ActiveMode -> IdleMode : Transition ICD to IdleMode and start the IdleMode timer. + * + * @param state requested OperationalState for the ICD to transition to + */ + void UpdateOperationState(OperationalState state); + + /** + * @brief Set or Remove a keep ActiveMode requirement for the given flag + * If state is true and the ICD is in IdleMode, transition the ICD to ActiveMode + * If state is false and the ICD is in ActiveMode, check whether we can transition the ICD to IdleMode. + * If we can, transition the ICD to IdleMode. + * + * @param flag KeepActiveFlag to remove or add + * @param state true: adding a flag requirement + * false: removing a flag requirement + */ + void SetKeepActiveModeRequirements(KeepActiveFlags flag, bool state); + + /** + * @brief Associates the ObserverEventType parameters to the correct + * ICDStateObservers function and calls it for all observers in the mStateObserverPool + */ + void postObserverEvent(ObserverEventType event); + + /** + * @brief Hepler function that extends the ActiveMode timer as well as the Active Mode Jitter timer for the transition to + * idle mode event. */ void ExtendActiveMode(System::Clock::Milliseconds16 extendDuration); + /** + * @brief Timer callback function for when the IdleMode timer expires + * + * @param appState pointer to the ICDManager + */ static void OnIdleModeDone(System::Layer * aLayer, void * appState); + + /** + * @brief Timer callback function for when the ActiveMode timer expires + * + * @param appState pointer to the ICDManager + */ static void OnActiveModeDone(System::Layer * aLayer, void * appState); /** - * @brief Callback function called shortly before the device enters idle mode to allow checks to be made. This is currently only - * called once to prevent entering in a loop if some events re-trigger this check (for instance if a check for subscription - * before entering idle mode leads to emiting a report, we will re-enter UpdateOperationState and check again for subscription, - * etc.) + * @brief Timer Callback function called shortly before the device enters idle mode to allow checks to be made. + * This is currently only called once to prevent entering in a loop if some events re-trigger this check (for instance if + * a check for subscriptions before entering idle mode leads to emiting a report, we will re-enter UpdateOperationState + * and check again for subscription, etc.) + * + * @param appState pointer to the ICDManager */ static void OnTransitionToIdle(System::Layer * aLayer, void * appState); #if CHIP_CONFIG_ENABLE_ICD_CIP - uint8_t mCheckInRequestCount = 0; -#endif // CHIP_CONFIG_ENABLE_ICD_CIP - - uint8_t mOpenExchangeContextCount = 0; + /** + * @brief Function triggers all necessary Check-In messages to be sent. + * + * @note For each ICDMonitoring entry, we check if should send a Check-In message with + * ShouldCheckInMsgsBeSentAtActiveModeFunction. If we should, we allocate an ICDCheckInSender which tries to send a + * Check-In message to the registered client. + */ + void SendCheckInMsgs(); -private: -#if CHIP_CONFIG_ENABLE_ICD_CIP + /** + * @brief See function implementation in .cpp for details on this function. + */ bool ShouldCheckInMsgsBeSentAtActiveModeFunction(FabricIndex aFabricIndex, NodeId subjectID); /** @@ -221,11 +306,15 @@ class ICDManager : public ICDListener, public TestEventTriggerHandler OperationalState mOperationalState = OperationalState::ActiveMode; bool mTransitionToIdleCalled = false; ObjectPool mStateObserverPool; + uint8_t mOpenExchangeContextCount = 0; #if CHIP_CONFIG_ENABLE_ICD_CIP + uint8_t mCheckInRequestCount = 0; + #if !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION && CHIP_CONFIG_PERSIST_SUBSCRIPTIONS bool mIsBootUpResumeSubscriptionExecuted = false; #endif // !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION && CHIP_CONFIG_PERSIST_SUBSCRIPTIONS + PersistentStorageDelegate * mStorage = nullptr; FabricTable * mFabricTable = nullptr; Messaging::ExchangeManager * mExchangeManager = nullptr; diff --git a/src/app/icd/server/ICDStateObserver.h b/src/app/icd/server/ICDStateObserver.h index 996dad0ec6608b..34fc309b466449 100644 --- a/src/app/icd/server/ICDStateObserver.h +++ b/src/app/icd/server/ICDStateObserver.h @@ -27,13 +27,43 @@ namespace chip { namespace app { +/** + * @brief Public API used by the ICDManager to expose when different events occur. + * ICDManager::RegisterObserver can be used to register as an Observer to be notified when these events occur. + * These functions are called synchronously. + */ class ICDStateObserver { public: virtual ~ICDStateObserver() {} - virtual void OnEnterActiveMode() = 0; + + /** + * @brief API called when the ICD enters ActiveMode. API isn't called if we need to extend the remaining active mode timer + * duration. API is called after the ICDManager has finished executing its internal actions. + */ + virtual void OnEnterActiveMode() = 0; + + /** + * @brief API called when the ICD enters IdleMode. + * API is called after the ICDManager has finished executing its internal actions. + */ + virtual void OnEnterIdleMode() = 0; + + /** + * @brief API is called when the ICD is about to enter IdleMode. API is called when there is `ICD_ACTIVE_TIME_JITTER_MS` of time + * remaining to the active mode timer. + * This API is only called once per transition from ActiveMode to IdleMode. + * If OnTransitionToIdle triggers the active mode timer to increase, the next time we are about to enter IdleMode, + * this API will not be called. + */ virtual void OnTransitionToIdle() = 0; - virtual void OnICDModeChange() = 0; + + /** + * @brief API is called when the ICD changes operating mode. This API is only called if the ICD changes state, not when it + * remains in the same state. + * API is called after the ICDManager has finished executing its internal actions. + */ + virtual void OnICDModeChange() = 0; }; } // namespace app diff --git a/src/app/reporting/ReportSchedulerImpl.h b/src/app/reporting/ReportSchedulerImpl.h index 38fcc2ae1bf941..f7889a5ac3e6c7 100644 --- a/src/app/reporting/ReportSchedulerImpl.h +++ b/src/app/reporting/ReportSchedulerImpl.h @@ -89,6 +89,12 @@ class ReportSchedulerImpl : public ReportScheduler */ void OnICDModeChange() override{}; + /** + * @brief This implementation does not attempt any synchronization on this ICD event, therefore no action is needed on + * ICDEnterIdleMode() + */ + void OnEnterIdleMode() override{}; + // ReadHandlerObserver /** diff --git a/src/app/server/Dnssd.h b/src/app/server/Dnssd.h index e669f4d0860a50..105318ca5a08be 100644 --- a/src/app/server/Dnssd.h +++ b/src/app/server/Dnssd.h @@ -126,11 +126,25 @@ class DLL_EXPORT DnssdServer : public ICDStateObserver */ CHIP_ERROR SetEphemeralDiscriminator(Optional discriminator); - // ICDStateObserver - // No action is needed by the DnssdServer on active or idle state entries + /** + * @brief When the ICD changes operating mode, the dnssd server needs to restart its DNS-SD advertising to update the TXT keys. + */ + void OnICDModeChange() override; + + /** + * @brief dnssd server has no action to do on this ICD event. Do nothing. + */ void OnEnterActiveMode() override{}; + + /** + * @brief dnssd server has no action to do on this ICD event. Do nothing. + */ void OnTransitionToIdle() override{}; - void OnICDModeChange() override; + + /** + * @brief dnssd server has no action to do on this ICD event. Do nothing. + */ + void OnEnterIdleMode() override{}; private: /// Overloaded utility method for commissioner and commissionable advertisement diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index 57abf8087f59ca..cd9c56f9f021f7 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -27,7 +27,7 @@ #include #if CONFIG_NETWORK_LAYER_BLE -#include +#include #endif #include #include diff --git a/src/app/tests/TestBasicCommandPathRegistry.cpp b/src/app/tests/TestBasicCommandPathRegistry.cpp index 61e859b95498f0..28d7621ccbe7d1 100644 --- a/src/app/tests/TestBasicCommandPathRegistry.cpp +++ b/src/app/tests/TestBasicCommandPathRegistry.cpp @@ -36,13 +36,13 @@ void TestAddingSameConcretePath(nlTestSuite * apSuite, void * apContext) BasicCommandPathRegistry basicCommandPathRegistry; ConcreteCommandPath concretePath(0, 0, 0); - Optional commandRef; + std::optional commandRef; uint16_t commandRefValue = 0; size_t idx = 0; for (idx = 0; idx < kQuickTestSize && err == CHIP_NO_ERROR; idx++) { - commandRef.SetValue(commandRefValue); + commandRef.emplace(commandRefValue); commandRefValue++; err = basicCommandPathRegistry.Add(concretePath, commandRef); } @@ -56,8 +56,8 @@ void TestAddingSameCommandRef(nlTestSuite * apSuite, void * apContext) CHIP_ERROR err = CHIP_NO_ERROR; BasicCommandPathRegistry basicCommandPathRegistry; - Optional commandRef; - commandRef.SetValue(0); + std::optional commandRef; + commandRef.emplace(0); uint16_t endpointValue = 0; @@ -78,14 +78,14 @@ void TestAddingMaxNumberOfEntries(nlTestSuite * apSuite, void * apContext) CHIP_ERROR err = CHIP_NO_ERROR; BasicCommandPathRegistry basicCommandPathRegistry; - Optional commandRef; + std::optional commandRef; uint16_t commandRefAndEndpointValue = 0; size_t idx = 0; for (idx = 0; idx < kQuickTestSize && err == CHIP_NO_ERROR; idx++) { ConcreteCommandPath concretePath(commandRefAndEndpointValue, 0, 0); - commandRef.SetValue(commandRefAndEndpointValue); + commandRef.emplace(commandRefAndEndpointValue); commandRefAndEndpointValue++; err = basicCommandPathRegistry.Add(concretePath, commandRef); } @@ -100,14 +100,14 @@ void TestAddingTooManyEntries(nlTestSuite * apSuite, void * apContext) BasicCommandPathRegistry basicCommandPathRegistry; size_t maxPlusOne = kQuickTestSize + 1; - Optional commandRef; + std::optional commandRef; uint16_t commandRefAndEndpointValue = 0; size_t idx = 0; for (idx = 0; idx < maxPlusOne && err == CHIP_NO_ERROR; idx++) { ConcreteCommandPath concretePath(commandRefAndEndpointValue, 0, 0); - commandRef.SetValue(commandRefAndEndpointValue); + commandRef.emplace(commandRefAndEndpointValue); commandRefAndEndpointValue++; err = basicCommandPathRegistry.Add(concretePath, commandRef); } diff --git a/src/app/tests/TestBindingTable.cpp b/src/app/tests/TestBindingTable.cpp index fa314d1c1fd1dc..db95408813a0c1 100644 --- a/src/app/tests/TestBindingTable.cpp +++ b/src/app/tests/TestBindingTable.cpp @@ -23,7 +23,6 @@ #include using chip::BindingTable; -using chip::NullOptional; namespace { @@ -46,9 +45,9 @@ void TestAdd(nlTestSuite * aSuite, void * aContext) NL_TEST_ASSERT(aSuite, table.Add(unusedEntry) == CHIP_ERROR_INVALID_ARGUMENT); for (uint8_t i = 0; i < MATTER_BINDING_TABLE_SIZE; i++) { - NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, i, 0, 0, NullOptional)) == CHIP_NO_ERROR); + NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, i, 0, 0, std::nullopt)) == CHIP_NO_ERROR); } - NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, 0, 0, 0, NullOptional)) == CHIP_ERROR_NO_MEMORY); + NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, 0, 0, 0, std::nullopt)) == CHIP_ERROR_NO_MEMORY); NL_TEST_ASSERT(aSuite, table.Size() == MATTER_BINDING_TABLE_SIZE); auto iter = table.begin(); @@ -67,7 +66,7 @@ void TestRemoveThenAdd(nlTestSuite * aSuite, void * aContext) BindingTable table; chip::TestPersistentStorageDelegate testStorage; table.SetPersistentStorage(&testStorage); - NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, 0, 0, 0, NullOptional)) == CHIP_NO_ERROR); + NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, 0, 0, 0, std::nullopt)) == CHIP_NO_ERROR); auto iter = table.begin(); NL_TEST_ASSERT(aSuite, table.RemoveAt(iter) == CHIP_NO_ERROR); NL_TEST_ASSERT(aSuite, iter == table.end()); @@ -75,7 +74,7 @@ void TestRemoveThenAdd(nlTestSuite * aSuite, void * aContext) NL_TEST_ASSERT(aSuite, table.begin() == table.end()); for (uint8_t i = 0; i < MATTER_BINDING_TABLE_SIZE; i++) { - NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, i, 0, 0, NullOptional)) == CHIP_NO_ERROR); + NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, i, 0, 0, std::nullopt)) == CHIP_NO_ERROR); } iter = table.begin(); ++iter; @@ -87,7 +86,7 @@ void TestRemoveThenAdd(nlTestSuite * aSuite, void * aContext) ++iterCheck; NL_TEST_ASSERT(aSuite, iter == iterCheck); - NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, 1, 0, 0, NullOptional)) == CHIP_NO_ERROR); + NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, 1, 0, 0, std::nullopt)) == CHIP_NO_ERROR); NL_TEST_ASSERT(aSuite, table.Size() == MATTER_BINDING_TABLE_SIZE); iter = table.begin(); for (uint8_t i = 0; i < MATTER_BINDING_TABLE_SIZE - 1; i++) @@ -137,10 +136,10 @@ void TestPersistentStorage(nlTestSuite * aSuite, void * aContext) BindingTable table; chip::Optional cluster = chip::MakeOptional(static_cast(UINT16_MAX + 6)); std::vector expected = { - EmberBindingTableEntry::ForNode(0, 0, 0, 0, NullOptional), - EmberBindingTableEntry::ForNode(1, 1, 0, 0, cluster), - EmberBindingTableEntry::ForGroup(2, 2, 0, NullOptional), - EmberBindingTableEntry::ForGroup(3, 3, 0, cluster), + EmberBindingTableEntry::ForNode(0, 0, 0, 0, std::nullopt), + EmberBindingTableEntry::ForNode(1, 1, 0, 0, cluster.std_optional()), + EmberBindingTableEntry::ForGroup(2, 2, 0, std::nullopt), + EmberBindingTableEntry::ForGroup(3, 3, 0, cluster.std_optional()), }; table.SetPersistentStorage(&testStorage); NL_TEST_ASSERT(aSuite, table.Add(expected[0]) == CHIP_NO_ERROR); @@ -151,7 +150,7 @@ void TestPersistentStorage(nlTestSuite * aSuite, void * aContext) // Verify storage untouched if add fails testStorage.AddPoisonKey(chip::DefaultStorageKeyAllocator::BindingTableEntry(4).KeyName()); - NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(4, 4, 0, 0, NullOptional)) != CHIP_NO_ERROR); + NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(4, 4, 0, 0, std::nullopt)) != CHIP_NO_ERROR); VerifyRestored(aSuite, testStorage, expected); testStorage.ClearPoisonKeys(); diff --git a/src/app/tests/TestCommandInteraction.cpp b/src/app/tests/TestCommandInteraction.cpp index 9837818862c21b..87296580fa695f 100644 --- a/src/app/tests/TestCommandInteraction.cpp +++ b/src/app/tests/TestCommandInteraction.cpp @@ -40,6 +40,7 @@ #include #include #include +#include #include #include #include @@ -392,7 +393,7 @@ class TestCommandInteraction const Optional & aRef) : CommandHandler(apCallback) { - GetCommandPathRegistry().Add(aRequestCommandPath, aRef); + GetCommandPathRegistry().Add(aRequestCommandPath, aRef.std_optional()); SetExchangeInterface(&mMockCommandResponder); } MockCommandResponder mMockCommandResponder; @@ -407,7 +408,8 @@ class TestCommandInteraction // payload will be included. Otherwise no payload will be included. static void GenerateInvokeResponse(nlTestSuite * apSuite, void * apContext, System::PacketBufferHandle & aPayload, CommandId aCommandId, ClusterId aClusterId = kTestClusterId, - EndpointId aEndpointId = kTestEndpointId, Optional aCommandRef = NullOptional); + EndpointId aEndpointId = kTestEndpointId, + std::optional aCommandRef = std::nullopt); static void AddInvokeRequestData(nlTestSuite * apSuite, void * apContext, CommandSender * apCommandSender, CommandId aCommandId = kTestCommandIdWithData); static void AddInvalidInvokeRequestData(nlTestSuite * apSuite, void * apContext, CommandSender * apCommandSender, @@ -494,7 +496,7 @@ void TestCommandInteraction::GenerateInvokeRequest(nlTestSuite * apSuite, void * void TestCommandInteraction::GenerateInvokeResponse(nlTestSuite * apSuite, void * apContext, System::PacketBufferHandle & aPayload, CommandId aCommandId, ClusterId aClusterId, EndpointId aEndpointId, - Optional aCommandRef) + std::optional aCommandRef) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -536,9 +538,9 @@ void TestCommandInteraction::GenerateInvokeResponse(nlTestSuite * apSuite, void NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); } - if (aCommandRef.HasValue()) + if (aCommandRef.has_value()) { - NL_TEST_ASSERT(apSuite, commandDataIBBuilder.Ref(aCommandRef.Value()) == CHIP_NO_ERROR); + NL_TEST_ASSERT(apSuite, commandDataIBBuilder.Ref(*aCommandRef) == CHIP_NO_ERROR); } commandDataIBBuilder.EndOfCommandDataIB(); @@ -633,9 +635,9 @@ uint32_t TestCommandInteraction::GetAddResponseDataOverheadSizeForPath(nlTestSui ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; - CHIP_ERROR err = basicCommandPathRegistry.Add(requestCommandPath1, MakeOptional(static_cast(1))); + CHIP_ERROR err = basicCommandPathRegistry.Add(requestCommandPath1, std::make_optional(static_cast(1))); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = basicCommandPathRegistry.Add(requestCommandPath2, MakeOptional(static_cast(2))); + err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); err = commandHandler.AllocateBuffer(); @@ -823,7 +825,7 @@ void TestCommandInteraction::TestCommandSenderExtendableApiWithProcessReceivedMs uint16_t invalidResponseCommandRef = 2; GenerateInvokeResponse(apSuite, apContext, buf, kTestCommandIdWithData, kTestClusterId, kTestEndpointId, - MakeOptional(invalidResponseCommandRef)); + std::make_optional(invalidResponseCommandRef)); bool moreChunkedMessages = false; err = commandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_KEY_NOT_FOUND); @@ -1948,9 +1950,9 @@ void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhere ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; - CHIP_ERROR err = basicCommandPathRegistry.Add(requestCommandPath1, MakeOptional(static_cast(1))); + CHIP_ERROR err = basicCommandPathRegistry.Add(requestCommandPath1, std::make_optional(static_cast(1))); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = basicCommandPathRegistry.Add(requestCommandPath2, MakeOptional(static_cast(2))); + err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); uint32_t sizeToLeave = 0; @@ -1977,9 +1979,9 @@ void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhere ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; - CHIP_ERROR err = basicCommandPathRegistry.Add(requestCommandPath1, MakeOptional(static_cast(1))); + CHIP_ERROR err = basicCommandPathRegistry.Add(requestCommandPath1, std::make_optional(static_cast(1))); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = basicCommandPathRegistry.Add(requestCommandPath2, MakeOptional(static_cast(2))); + err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); uint32_t sizeToLeave = 0; @@ -2005,9 +2007,9 @@ void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhere ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; - CHIP_ERROR err = basicCommandPathRegistry.Add(requestCommandPath1, MakeOptional(static_cast(1))); + CHIP_ERROR err = basicCommandPathRegistry.Add(requestCommandPath1, std::make_optional(static_cast(1))); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = basicCommandPathRegistry.Add(requestCommandPath2, MakeOptional(static_cast(2))); + err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); uint32_t sizeToLeave = 0; diff --git a/src/app/tests/TestICDManager.cpp b/src/app/tests/TestICDManager.cpp index fd93a146cf2755..6e814ebb01f579 100644 --- a/src/app/tests/TestICDManager.cpp +++ b/src/app/tests/TestICDManager.cpp @@ -77,9 +77,27 @@ enum class ICDTestEventTriggerEvent : uint64_t class TestICDStateObserver : public app::ICDStateObserver { public: - void OnEnterActiveMode() {} - void OnTransitionToIdle() {} - void OnICDModeChange() {} + void OnEnterActiveMode() { mOnEnterActiveModeCalled = true; } + void OnEnterIdleMode() { mOnEnterIdleModeCalled = true; } + void OnTransitionToIdle() { mOnTransitionToIdleCalled = true; } + void OnICDModeChange() { mOnICDModeChangeCalled = true; } + + void ResetOnEnterActiveMode() { mOnEnterActiveModeCalled = false; } + void ResetOnEnterIdleMode() { mOnEnterIdleModeCalled = false; } + void ResetOnTransitionToIdle() { mOnTransitionToIdleCalled = false; } + void ResetOnICDModeChange() { mOnICDModeChangeCalled = false; } + void ResetAll() + { + ResetOnEnterActiveMode(); + ResetOnEnterIdleMode(); + ResetOnTransitionToIdle(); + ResetOnICDModeChange(); + } + + bool mOnEnterActiveModeCalled = false; + bool mOnEnterIdleModeCalled = false; + bool mOnICDModeChangeCalled = false; + bool mOnTransitionToIdleCalled = false; }; class TestSubscriptionsInfoProvider : public SubscriptionsInfoProvider @@ -123,10 +141,10 @@ class TestContext : public chip::Test::AppContext // Performs setup for each individual test in the test suite CHIP_ERROR SetUp() override { - ReturnErrorOnFailure(chip::Test::AppContext::SetUp()); - mICDManager.Init(&testStorage, &GetFabricTable(), &mKeystore, &GetExchangeManager(), &mSubInfoProvider); + mICDStateObserver.ResetAll(); mICDManager.RegisterObserver(&mICDStateObserver); + mICDManager.Init(&testStorage, &GetFabricTable(), &mKeystore, &GetExchangeManager(), &mSubInfoProvider); return CHIP_NO_ERROR; } @@ -196,7 +214,7 @@ class TestICDManager /** * @brief Test verifies that the ICDManager starts its timers correctly based on if it will have any messages to send - * when the IdleModeDuration expires + * when the IdleMode timer expires */ static void TestICDModeDurationsWith0ActiveModeDurationWithoutActiveSub(nlTestSuite * aSuite, void * aContext) { @@ -254,7 +272,7 @@ class TestICDManager AdvanceClockAndRunEventLoop(ctx, icdConfigData.GetActiveModeThreshold() + 1_ms16); NL_TEST_ASSERT(aSuite, ctx->mICDManager.mOperationalState == ICDManager::OperationalState::IdleMode); - // Expire IdleModeDuration - Device should be in ActiveMode since it has an ICDM registration + // Expire IdleMode timer - Device should be in ActiveMode since it has an ICDM registration AdvanceClockAndRunEventLoop(ctx, icdConfigData.GetIdleModeDuration() + 1_s); NL_TEST_ASSERT(aSuite, ctx->mICDManager.mOperationalState == ICDManager::OperationalState::ActiveMode); @@ -276,7 +294,7 @@ class TestICDManager /** * @brief Test verifies that the ICDManager remains in IdleMode since it will not have any messages to send - * when the IdleModeDuration expires + * when the IdleMode timer expires */ static void TestICDModeDurationsWith0ActiveModeDurationWithActiveSub(nlTestSuite * aSuite, void * aContext) { @@ -334,7 +352,7 @@ class TestICDManager AdvanceClockAndRunEventLoop(ctx, icdConfigData.GetActiveModeThreshold() + 1_ms16); NL_TEST_ASSERT(aSuite, ctx->mICDManager.mOperationalState == ICDManager::OperationalState::IdleMode); - // Expire IdleModeDuration - Device stay in IdleMode since it has an active subscription for the ICDM entry + // Expire IdleMode timer - Device stay in IdleMode since it has an active subscription for the ICDM entry AdvanceClockAndRunEventLoop(ctx, icdConfigData.GetIdleModeDuration() + 1_s); NL_TEST_ASSERT(aSuite, ctx->mICDManager.mOperationalState == ICDManager::OperationalState::IdleMode); @@ -414,9 +432,9 @@ class TestICDManager NL_TEST_ASSERT(aSuite, ctx->mICDManager.mOperationalState == ICDManager::OperationalState::IdleMode); } - /* - * Test that verifies that the ICDManager is the correct operating mode based on entries - * in the ICDMonitoringTable + /** + * @brief Test that verifies that the ICDManager is in the correct operating mode based on entries + * in the ICDMonitoringTable */ static void TestICDMRegisterUnregisterEvents(nlTestSuite * aSuite, void * aContext) { @@ -554,7 +572,9 @@ class TestICDManager NL_TEST_ASSERT(aSuite, ctx->mICDManager.mOperationalState == ICDManager::OperationalState::IdleMode); } - /* Test that verifies the logic of the ICDManager when it receives a StayActiveRequest*/ + /** + * @brief Test verifies the logic of the ICDManager when it receives a StayActiveRequest + */ static void TestICDMStayActive(nlTestSuite * aSuite, void * aContext) { TestContext * ctx = static_cast(aContext); @@ -568,7 +588,7 @@ class TestICDManager notifier.NotifySubscriptionReport(); NL_TEST_ASSERT(aSuite, ctx->mICDManager.mOperationalState == ICDManager::OperationalState::ActiveMode); - // Advance time by the ActiveModeDuration - 1 + // Advance time just before ActiveMode timer expires AdvanceClockAndRunEventLoop(ctx, icdConfigData.GetActiveModeDuration() - 1_ms32); // Confirm ICD manager is in active mode NL_TEST_ASSERT(aSuite, ctx->mICDManager.mOperationalState == ICDManager::OperationalState::ActiveMode); @@ -580,7 +600,7 @@ class TestICDManager NL_TEST_ASSERT(aSuite, stayActivePromisedMs == stayActiveRequestedMs); // Advance time by the duration of the stay stayActiveRequestedMs - 1 ms - AdvanceClockAndRunEventLoop(ctx, System::Clock::Milliseconds32(stayActiveRequestedMs) - 1_ms32); + AdvanceClockAndRunEventLoop(ctx, Milliseconds32(stayActiveRequestedMs) - 1_ms32); // Confirm ICD manager is in active mode NL_TEST_ASSERT(aSuite, ctx->mICDManager.mOperationalState == ICDManager::OperationalState::ActiveMode); @@ -601,7 +621,7 @@ class TestICDManager NL_TEST_ASSERT(aSuite, stayActivePromisedMs == 30000); // Advance time by the duration of the max stay active duration - 1 ms - AdvanceClockAndRunEventLoop(ctx, System::Clock::Milliseconds32(30000) - 1_ms32); + AdvanceClockAndRunEventLoop(ctx, Milliseconds32(30000) - 1_ms32); NL_TEST_ASSERT(aSuite, ctx->mICDManager.mOperationalState == ICDManager::OperationalState::ActiveMode); // Advance time by 1ms and Confirm ICD manager is in idle mode @@ -621,7 +641,7 @@ class TestICDManager NL_TEST_ASSERT(aSuite, stayActivePromisedMs == 30000); // Advance time by the duration of the stay active request - 20000 ms - AdvanceClockAndRunEventLoop(ctx, System::Clock::Milliseconds32(stayActiveRequestedMs) - 20000_ms32); + AdvanceClockAndRunEventLoop(ctx, Milliseconds32(stayActiveRequestedMs) - 20000_ms32); // Confirm ICD manager is in active mode, we should have 20000 seconds left at that point NL_TEST_ASSERT(aSuite, ctx->mICDManager.mOperationalState == ICDManager::OperationalState::ActiveMode); @@ -721,6 +741,329 @@ class TestICDManager ctx->mICDManager.HandleEventTrigger(static_cast(ICDTestEventTriggerEvent::kRemoveActiveModeReq)); NL_TEST_ASSERT(aSuite, ctx->mICDManager.mOperationalState == ICDManager::OperationalState::IdleMode); } + + /** + * @brief Test verifies when OnEnterIdleMode is called during normal operations. + * Without the ActiveMode timer being extended + */ + static void TestICDStateObserverOnEnterIdleModeActiveModeDuration(nlTestSuite * aSuite, void * aContext) + { + TestContext * ctx = static_cast(aContext); + + // Verify that ICDManager starts in IdleMode and calls OnEnterIdleMode + NL_TEST_ASSERT(aSuite, ctx->mICDStateObserver.mOnEnterIdleModeCalled); + ctx->mICDStateObserver.ResetOnEnterIdleMode(); + + // Advance clock just before IdleMode timer expires + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetIdleModeDuration() - 1_s); + NL_TEST_ASSERT(aSuite, !ctx->mICDStateObserver.mOnEnterIdleModeCalled); + + // Expire IdleModeInterval + AdvanceClockAndRunEventLoop(ctx, 1_s); + NL_TEST_ASSERT(aSuite, !ctx->mICDStateObserver.mOnEnterIdleModeCalled); + + // Advance clock Just before ActiveMode timer expires + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetActiveModeDuration() - 1_ms32); + NL_TEST_ASSERT(aSuite, !ctx->mICDStateObserver.mOnEnterIdleModeCalled); + + // Expire ActiveMode timer + AdvanceClockAndRunEventLoop(ctx, 1_ms32); + NL_TEST_ASSERT(aSuite, ctx->mICDStateObserver.mOnEnterIdleModeCalled); + } + + /** + * @brief Test verifies when OnEnterIdleMode is called with the ActiveMode timer gets extended + */ + static void TestICDStateObserverOnEnterIdleModeActiveModeThreshold(nlTestSuite * aSuite, void * aContext) + { + TestContext * ctx = static_cast(aContext); + + // Verify that ICDManager starts in IdleMode and calls OnEnterIdleMode + NL_TEST_ASSERT(aSuite, ctx->mICDStateObserver.mOnEnterIdleModeCalled); + ctx->mICDStateObserver.ResetOnEnterIdleMode(); + + // Advance clock just before the IdleMode timer expires + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetIdleModeDuration() - 1_s); + NL_TEST_ASSERT(aSuite, !ctx->mICDStateObserver.mOnEnterIdleModeCalled); + + // Expire IdleMode timer + AdvanceClockAndRunEventLoop(ctx, 1_s); + NL_TEST_ASSERT(aSuite, !ctx->mICDStateObserver.mOnEnterIdleModeCalled); + + // Advance clock Just before ActiveMode timer expires + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetActiveModeDuration() - 1_ms32); + NL_TEST_ASSERT(aSuite, !ctx->mICDStateObserver.mOnEnterIdleModeCalled); + + // Increase ActiveMode timer by one ActiveModeThreshold + ICDNotifier::GetInstance().NotifyNetworkActivityNotification(); + NL_TEST_ASSERT(aSuite, !ctx->mICDStateObserver.mOnEnterIdleModeCalled); + + // Advance clock Just before ActiveMode timer expires + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetActiveModeThreshold() - 1_ms32); + NL_TEST_ASSERT(aSuite, !ctx->mICDStateObserver.mOnEnterIdleModeCalled); + + // Expire ActiveMode timer + AdvanceClockAndRunEventLoop(ctx, 1_ms32); + NL_TEST_ASSERT(aSuite, ctx->mICDStateObserver.mOnEnterIdleModeCalled); + } + + static void TestICDStateObserverOnEnterActiveMode(nlTestSuite * aSuite, void * aContext) + { + TestContext * ctx = static_cast(aContext); + + // Verify OnEnterActiveMode wasn't called at Init + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnEnterActiveModeCalled)); + + // Advance clock just before IdleMode timer expires + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetIdleModeDuration() - 1_s); + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnEnterActiveModeCalled)); + + // Expire IdleMode timer and check wether OnEnterActiveMode was called + AdvanceClockAndRunEventLoop(ctx, 1_s); + NL_TEST_ASSERT(aSuite, ctx->mICDStateObserver.mOnEnterActiveModeCalled); + ctx->mICDStateObserver.ResetOnEnterActiveMode(); + + // Advance clock just before the ActiveMode timer expires + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetActiveModeDuration() - 1_ms32); + + // Verify OnEnterActiveMde wasn't called + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnEnterActiveModeCalled)); + + // Increase ActiveMode timer by one ActiveModeThreshold + ICDNotifier::GetInstance().NotifyNetworkActivityNotification(); + + // Verify OnEnterActiveMde wasn't called + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnEnterActiveModeCalled)); + + // Advance clock just before ActiveMode timer expires + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetActiveModeThreshold() - 1_ms32); + + // Verify OnEnterActiveMde wasn't called + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnEnterActiveModeCalled)); + + // Expire ActiveMode timer + AdvanceClockAndRunEventLoop(ctx, 1_ms32); + + // Verify OnEnterActiveMde wasn't called + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnEnterActiveModeCalled)); + + // Advance clock just before IdleMode timer expires + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetIdleModeDuration() - 1_s); + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnEnterActiveModeCalled)); + + // Expire IdleMode timer and check OnEnterActiveMode was called + AdvanceClockAndRunEventLoop(ctx, 1_s); + NL_TEST_ASSERT(aSuite, ctx->mICDStateObserver.mOnEnterActiveModeCalled); + } + + static void TestICDStateObserverOnICDModeChange(nlTestSuite * aSuite, void * aContext) + { + TestContext * ctx = static_cast(aContext); + typedef ICDListener::ICDManagementEvents ICDMEvent; + + // Since we don't have a registration, we stay in SIT mode. No changes + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnICDModeChangeCalled)); + + // Trigger register event to force ICDManager to re-evaluate OperatingMode + ICDNotifier::GetInstance().NotifyICDManagementEvent(ICDMEvent::kTableUpdated); + + // Since we don't have a registration, we stay in SIT mode. No changes + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnICDModeChangeCalled)); + + // Add an entry to the ICDMonitoringTable + ICDMonitoringTable table(ctx->testStorage, kTestFabricIndex1, kMaxTestClients, &(ctx->mKeystore)); + + ICDMonitoringEntry entry(&(ctx->mKeystore)); + entry.checkInNodeID = kClientNodeId11; + entry.monitoredSubject = kClientNodeId11; + NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == entry.SetKey(ByteSpan(kKeyBuffer1a))); + NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == table.Set(0, entry)); + + // Trigger register event after first entry was added + ICDNotifier::GetInstance().NotifyICDManagementEvent(ICDMEvent::kTableUpdated); + + // We have a registration. Transition to LIT mode + NL_TEST_ASSERT(aSuite, ctx->mICDStateObserver.mOnICDModeChangeCalled); + ctx->mICDStateObserver.ResetOnICDModeChange(); + + // Trigger register event to force ICDManager to re-evaluate OperatingMode + ICDNotifier::GetInstance().NotifyICDManagementEvent(ICDMEvent::kTableUpdated); + + // We have a registration. We stay in LIT mode. No changes. + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnICDModeChangeCalled)); + + // Remove entry from the ICDMonitoringTable + NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == table.Remove(0)); + ICDNotifier::GetInstance().NotifyICDManagementEvent(ICDMEvent::kTableUpdated); + + // Since we don't have a registration anymore. Transition to SIT mode. + NL_TEST_ASSERT(aSuite, ctx->mICDStateObserver.mOnICDModeChangeCalled); + ctx->mICDStateObserver.ResetOnICDModeChange(); + } + + static void TestICDStateObserverOnICDModeChangeOnInit(nlTestSuite * aSuite, void * aContext) + { + TestContext * ctx = static_cast(aContext); + + ICDMonitoringTable table(ctx->testStorage, kTestFabricIndex1, kMaxTestClients, &(ctx->mKeystore)); + + // Since we don't have a registration, we stay in SIT mode. No changes + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnICDModeChangeCalled)); + + // Add an entry to the ICDMonitoringTable + ICDMonitoringEntry entry(&(ctx->mKeystore)); + entry.checkInNodeID = kClientNodeId11; + entry.monitoredSubject = kClientNodeId11; + NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == entry.SetKey(ByteSpan(kKeyBuffer1a))); + NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == table.Set(0, entry)); + + // Shut down and reinit ICDManager - We should go to LIT mode since we have a registration + ctx->mICDManager.Shutdown(); + ctx->mICDManager.RegisterObserver(&(ctx->mICDStateObserver)); + ctx->mICDManager.Init(&(ctx->testStorage), &(ctx->GetFabricTable()), &(ctx->mKeystore), &(ctx->GetExchangeManager()), + &(ctx->mSubInfoProvider)); + + // We have a registration, transition to LIT mode + NL_TEST_ASSERT(aSuite, ctx->mICDStateObserver.mOnICDModeChangeCalled); + ctx->mICDStateObserver.ResetOnICDModeChange(); + + // Remove entry from the ICDMonitoringTable + NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == table.Remove(0)); + } + + /** + * @brief Test verifies the OnTransitionToIdleMode event when the ActiveModeDuration is greater than the + * ICD_ACTIVE_TIME_JITTER_MS + */ + static void TestICDStateObserverOnTransitionToIdleModeGreaterActiveModeDuration(nlTestSuite * aSuite, void * aContext) + { + TestContext * ctx = static_cast(aContext); + + // Set New durations for test case - ActiveModeDuration must be longuer than ICD_ACTIVE_TIME_JITTER_MS + Milliseconds32 oldActiveModeDuration = ICDConfigurationData::GetInstance().GetActiveModeDuration(); + ICDConfigurationData::GetInstance().SetModeDurations( + MakeOptional(Milliseconds32(200) + Milliseconds32(ICD_ACTIVE_TIME_JITTER_MS)), NullOptional); + + // Advance clock just before IdleMode timer expires + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetIdleModeDuration() - 1_s); + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnTransitionToIdleCalled)); + + // Expire IdleMode timer + AdvanceClockAndRunEventLoop(ctx, 1_s); + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnTransitionToIdleCalled)); + + // Advance time just before OnTransitionToIdleMode is called + AdvanceClockAndRunEventLoop( + ctx, ICDConfigurationData::GetInstance().GetActiveModeDuration() - Milliseconds32(ICD_ACTIVE_TIME_JITTER_MS) - 1_ms32); + + // Check mOnTransitionToIdleCalled has not been called + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnTransitionToIdleCalled)); + + // Increase ActiveMode timer by one ActiveModeThreshold + ICDNotifier::GetInstance().NotifyNetworkActivityNotification(); + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnTransitionToIdleCalled)); + + // Advance time just before OnTransitionToIdleMode is called + AdvanceClockAndRunEventLoop( + ctx, ICDConfigurationData::GetInstance().GetActiveModeThreshold() - Milliseconds32(ICD_ACTIVE_TIME_JITTER_MS) - 1_ms32); + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnTransitionToIdleCalled)); + + // Expire OnTransitionToIdleMode + AdvanceClockAndRunEventLoop(ctx, 1_ms32); + // Check mOnTransitionToIdleCalled has been called + NL_TEST_ASSERT(aSuite, ctx->mICDStateObserver.mOnTransitionToIdleCalled); + ctx->mICDStateObserver.ResetOnTransitionToIdle(); + + // Expire ActiveMode timer + AdvanceClockAndRunEventLoop(ctx, Milliseconds32(ICD_ACTIVE_TIME_JITTER_MS)); + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnTransitionToIdleCalled)); + + // Reset Old durations + ICDConfigurationData::GetInstance().SetModeDurations(MakeOptional(oldActiveModeDuration), NullOptional); + } + + /** + * @brief Test verifies the OnTransitionToIdleMode event when the ActiveModeDuration is equal to the + * ICD_ACTIVE_TIME_JITTER_MS. + */ + static void TestICDStateObserverOnTransitionToIdleModeEqualActiveModeDuration(nlTestSuite * aSuite, void * aContext) + { + TestContext * ctx = static_cast(aContext); + + // Set New durations for test case - ActiveModeDuration must be equal to ICD_ACTIVE_TIME_JITTER_MS + Milliseconds32 oldActiveModeDuration = ICDConfigurationData::GetInstance().GetActiveModeDuration(); + ICDConfigurationData::GetInstance().SetModeDurations( + MakeOptional(Milliseconds32(ICD_ACTIVE_TIME_JITTER_MS)), NullOptional); + + // Advance clock just before IdleMode timer expires + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetIdleModeDuration() - 1_s); + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnTransitionToIdleCalled)); + + // Expire IdleMode timer + AdvanceClockAndRunEventLoop(ctx, 1_s); + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnTransitionToIdleCalled)); + + // Expire OnTransitionToIdleMode + AdvanceClockAndRunEventLoop(ctx, 1_ms32); + NL_TEST_ASSERT(aSuite, ctx->mICDStateObserver.mOnTransitionToIdleCalled); + + // Reset Old durations + ICDConfigurationData::GetInstance().SetModeDurations(MakeOptional(oldActiveModeDuration), NullOptional); + } + + /** + * @brief Test verifies the OnTransitionToIdleMode event when the ActiveModeDuration is 0 and without an ActiveMode req + */ + static void TestICDStateObserverOnTransitionToIdleMode0ActiveModeDurationWithoutReq(nlTestSuite * aSuite, void * aContext) + { + TestContext * ctx = static_cast(aContext); + + // Set New durations for test case - ActiveModeDuration equal 0 + Milliseconds32 oldActiveModeDuration = ICDConfigurationData::GetInstance().GetActiveModeDuration(); + ICDConfigurationData::GetInstance().SetModeDurations(MakeOptional(0), NullOptional); + + // Advance clock just before IdleMode timer expires + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetIdleModeDuration() - 1_s); + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnTransitionToIdleCalled)); + + // Expire IdleMode timer + AdvanceClockAndRunEventLoop(ctx, 1_s); + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnTransitionToIdleCalled)); + + // Increase time by 1 - Should not trigger OnTransitionToIdle. + // Timer length is one ActiveModeThreshold + AdvanceClockAndRunEventLoop(ctx, 1_ms32); + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnTransitionToIdleCalled)); + + // Expire ActiveModeThreshold + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetActiveModeThreshold()); + NL_TEST_ASSERT(aSuite, ctx->mICDStateObserver.mOnTransitionToIdleCalled); + + // Reset Old durations + ICDConfigurationData::GetInstance().SetModeDurations(MakeOptional(oldActiveModeDuration), NullOptional); + } + + /** + * @brief Test verifies the OnTransitionToIdleMode event when the ActiveModeDuration is 0 with an ActiveMode req + */ + static void TestICDStateObserverOnTransitionToIdleMode0ActiveModeDurationWittReq(nlTestSuite * aSuite, void * aContext) + { + TestContext * ctx = static_cast(aContext); + + // Set New durations for test case - ActiveModeDuration equal 0 + Milliseconds32 oldActiveModeDuration = ICDConfigurationData::GetInstance().GetActiveModeDuration(); + ICDConfigurationData::GetInstance().SetModeDurations(MakeOptional(0), NullOptional); + + // Add ActiveMode req for the Test event trigger event + ctx->mICDManager.HandleEventTrigger(static_cast(ICDTestEventTriggerEvent::kAddActiveModeReq)); + + // Expire IdleMode timer + AdvanceClockAndRunEventLoop(ctx, ICDConfigurationData::GetInstance().GetIdleModeDuration()); + NL_TEST_ASSERT(aSuite, !(ctx->mICDStateObserver.mOnTransitionToIdleCalled)); + + // Reset Old durations + ICDConfigurationData::GetInstance().SetModeDurations(MakeOptional(oldActiveModeDuration), NullOptional); + } }; } // namespace app @@ -740,6 +1083,22 @@ static const nlTest sTests[] = { NL_TEST_DEF("TestICDStayActive", TestICDManager::TestICDMStayActive), NL_TEST_DEF("TestShouldCheckInMsgsBeSentAtActiveModeFunction", TestICDManager::TestShouldCheckInMsgsBeSentAtActiveModeFunction), NL_TEST_DEF("TestHandleTestEventTriggerActiveModeReq", TestICDManager::TestHandleTestEventTriggerActiveModeReq), + NL_TEST_DEF("TestICDStateObserverOnEnterIdleModeActiveModeDuration", + TestICDManager::TestICDStateObserverOnEnterIdleModeActiveModeDuration), + NL_TEST_DEF("TestICDStateObserverOnEnterIdleModeActiveModeThreshold", + TestICDManager::TestICDStateObserverOnEnterIdleModeActiveModeThreshold), + NL_TEST_DEF("TestICDStateObserverOnEnterActiveMode", TestICDManager::TestICDStateObserverOnEnterActiveMode), + NL_TEST_DEF("TestICDStateObserverOnICDModeChange", TestICDManager::TestICDStateObserverOnICDModeChange), + NL_TEST_DEF("TestICDStateObserverOnICDModeChangeOnInit", TestICDManager::TestICDStateObserverOnICDModeChangeOnInit), + NL_TEST_DEF("TestICDStateObserverOnTransitionToIdleModeGreaterActiveModeDuration", + TestICDManager::TestICDStateObserverOnTransitionToIdleModeGreaterActiveModeDuration), + NL_TEST_DEF("TestICDStateObserverOnTransitionToIdleModeEqualActiveModeDuration", + TestICDManager::TestICDStateObserverOnTransitionToIdleModeEqualActiveModeDuration), + NL_TEST_DEF("TestICDStateObserverOnTransitionToIdleMode0ActiveModeDurationWithoutReq", + TestICDManager::TestICDStateObserverOnTransitionToIdleMode0ActiveModeDurationWithoutReq), + // TODO(#33074): When the OnTransitionToIdle edge is fixed, we can enable this test + // NL_TEST_DEF("TestICDStateObserverOnTransitionToIdleMode0ActiveModeDurationWittReq", + // TestICDManager::TestICDStateObserverOnTransitionToIdleMode0ActiveModeDurationWittReq), NL_TEST_SENTINEL(), }; diff --git a/src/app/tests/TestPendingNotificationMap.cpp b/src/app/tests/TestPendingNotificationMap.cpp index 31aa133977d1be..98e27cb5f7b45a 100644 --- a/src/app/tests/TestPendingNotificationMap.cpp +++ b/src/app/tests/TestPendingNotificationMap.cpp @@ -46,7 +46,7 @@ void CreateDefaultFullBindingTable(BindingTable & table) { for (uint8_t i = 0; i < MATTER_BINDING_TABLE_SIZE; i++) { - table.Add(EmberBindingTableEntry::ForNode(i / 10, i % 5, 0, 0, MakeOptional(i))); + table.Add(EmberBindingTableEntry::ForNode(i / 10, i % 5, 0, 0, std::make_optional(i))); } } diff --git a/src/app/tests/suites/TestIcdManagementCluster.yaml b/src/app/tests/suites/TestIcdManagementCluster.yaml index 3d0081504c19bf..f7f207ab8df310 100644 --- a/src/app/tests/suites/TestIcdManagementCluster.yaml +++ b/src/app/tests/suites/TestIcdManagementCluster.yaml @@ -87,7 +87,10 @@ tests: command: "readAttribute" attribute: "ICDCounter" response: - value: beforeRebootICDCounter + 101 + constraints: + # It is possible ICD hasn't had time to send a Check-In message after reboot + minValue: beforeRebootICDCounter + 100 + maxValue: beforeRebootICDCounter + 101 - label: "Verify the ICD is operating as a LIT ICD" command: "readAttribute" diff --git a/src/app/util/binding-table.cpp b/src/app/util/binding-table.cpp index b08d41d7f074b4..ce3c45f196b3c9 100644 --- a/src/app/util/binding-table.cpp +++ b/src/app/util/binding-table.cpp @@ -97,9 +97,9 @@ CHIP_ERROR BindingTable::SaveEntryToStorage(uint8_t index, uint8_t nextIndex) ReturnErrorOnFailure(writer.StartContainer(TLV::AnonymousTag(), TLV::TLVType::kTLVType_Structure, container)); ReturnErrorOnFailure(writer.Put(TLV::ContextTag(kTagFabricIndex), entry.fabricIndex)); ReturnErrorOnFailure(writer.Put(TLV::ContextTag(kTagLocalEndpoint), entry.local)); - if (entry.clusterId.HasValue()) + if (entry.clusterId.has_value()) { - ReturnErrorOnFailure(writer.Put(TLV::ContextTag(kTagCluster), entry.clusterId.Value())); + ReturnErrorOnFailure(writer.Put(TLV::ContextTag(kTagCluster), *entry.clusterId)); } if (entry.type == MATTER_UNICAST_BINDING) { @@ -202,12 +202,12 @@ CHIP_ERROR BindingTable::LoadEntryFromStorage(uint8_t index, uint8_t & nextIndex { ClusterId clusterId; ReturnErrorOnFailure(reader.Get(clusterId)); - entry.clusterId.SetValue(clusterId); + entry.clusterId.emplace(clusterId); ReturnErrorOnFailure(reader.Next()); } else { - entry.clusterId = NullOptional; + entry.clusterId = std::nullopt; } if (reader.GetTag() == TLV::ContextTag(kTagRemoteEndpoint)) { diff --git a/src/app/util/types_stub.h b/src/app/util/types_stub.h index fd789da788b01d..fecfa044964af8 100644 --- a/src/app/util/types_stub.h +++ b/src/app/util/types_stub.h @@ -19,9 +19,10 @@ #include // For mem* functions. +#include + #include #include -#include static_assert(sizeof(chip::NodeId) == sizeof(uint64_t), "Unexpected node if size"); @@ -74,7 +75,7 @@ typedef uint16_t EmberPanId; struct EmberBindingTableEntry { static EmberBindingTableEntry ForNode(chip::FabricIndex fabric, chip::NodeId node, chip::EndpointId localEndpoint, - chip::EndpointId remoteEndpoint, chip::Optional cluster) + chip::EndpointId remoteEndpoint, std::optional cluster) { EmberBindingTableEntry entry = { .type = MATTER_UNICAST_BINDING, @@ -88,7 +89,7 @@ struct EmberBindingTableEntry } static EmberBindingTableEntry ForGroup(chip::FabricIndex fabric, chip::GroupId group, chip::EndpointId localEndpoint, - chip::Optional cluster) + std::optional cluster) { EmberBindingTableEntry entry = { .type = MATTER_MULTICAST_BINDING, @@ -114,7 +115,7 @@ struct EmberBindingTableEntry * that a binding can be used to to send messages with any cluster ID, not * just that listed in the binding. */ - chip::Optional clusterId; + std::optional clusterId; /** The endpoint on the remote node (specified by \c identifier). */ chip::EndpointId remote; /** A 64-bit destination identifier. This is either: diff --git a/src/app/zap-templates/app-templates.json b/src/app/zap-templates/app-templates.json index 1d41e127165c01..d55bae36312e03 100644 --- a/src/app/zap-templates/app-templates.json +++ b/src/app/zap-templates/app-templates.json @@ -1,6 +1,8 @@ { "name": "CHIP Application templates", "version": "chip-v1", + "requiredFeatureLevel": 102, + "category": "matter", "helpers": [ "partials/helper.js", "common/ListHelper.js", diff --git a/src/app/zap-templates/zcl/data-model/chip/administrator-commissioning-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/administrator-commissioning-cluster.xml index 0668f2dea4ae7c..3532c89b931880 100644 --- a/src/app/zap-templates/zcl/data-model/chip/administrator-commissioning-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/administrator-commissioning-cluster.xml @@ -38,6 +38,11 @@ limitations under the License. ADMINISTRATOR_COMMISSIONING_CLUSTER Commands to trigger a Node to allow a new Administrator to commission it. + + + + + WindowStatus AdminFabricIndex AdminVendorId @@ -64,9 +69,4 @@ limitations under the License. - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/air-quality-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/air-quality-cluster.xml index f2ce941007bf59..bbc57510e85dce 100644 --- a/src/app/zap-templates/zcl/data-model/chip/air-quality-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/air-quality-cluster.xml @@ -25,19 +25,25 @@ limitations under the License. true true + + + + + + + + + + + + + + + AirQuality - - - - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/application-launcher-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/application-launcher-cluster.xml index 7a50d97d666b5f..8aaca6201074dd 100644 --- a/src/app/zap-templates/zcl/data-model/chip/application-launcher-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/application-launcher-cluster.xml @@ -25,6 +25,12 @@ limitations under the License. true This cluster provides an interface for launching content on a media player device such as a TV or Speaker. + + + + + + CatalogList CurrentApp @@ -75,9 +81,4 @@ limitations under the License. - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/audio-output-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/audio-output-cluster.xml index 2067d048d4e569..acaa9deadb6a3b 100644 --- a/src/app/zap-templates/zcl/data-model/chip/audio-output-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/audio-output-cluster.xml @@ -24,6 +24,13 @@ limitations under the License. true true This cluster provides an interface for controlling the Output on a media device such as a TV. + + + + + + + OutputList CurrentOutput @@ -58,9 +65,4 @@ limitations under the License. - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/boolean-state-configuration-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/boolean-state-configuration-cluster.xml index 2b5f81eed744e1..f60623455c8d24 100644 --- a/src/app/zap-templates/zcl/data-model/chip/boolean-state-configuration-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/boolean-state-configuration-cluster.xml @@ -17,14 +17,6 @@ limitations under the License. - - - - - - - - @@ -46,6 +38,26 @@ limitations under the License. This cluster is used to configure a boolean sensor. + + + + + + + + + + + + + + + + + + + + CurrentSensitivityLevel SupportedSensitivityLevels DefaultSensitivityLevel diff --git a/src/app/zap-templates/zcl/data-model/chip/channel-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/channel-cluster.xml index 460fedd40c89c1..25ec7b7062f97a 100644 --- a/src/app/zap-templates/zcl/data-model/chip/channel-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/channel-cluster.xml @@ -25,6 +25,22 @@ limitations under the License. true This cluster provides an interface for controlling the current Channel on a device. + + + + + + + + + + + + + + + + ChannelList Lineup CurrentChannel @@ -192,12 +208,4 @@ limitations under the License. - - - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/color-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/color-control-cluster.xml index 0dcb76abac44ea..749731069494f5 100644 --- a/src/app/zap-templates/zcl/data-model/chip/color-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/color-control-cluster.xml @@ -15,14 +15,7 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - - - - - - + @@ -107,6 +100,24 @@ limitations under the License. + + + + + + + + + + + + + + + + + + CurrentHue CurrentSaturation diff --git a/src/app/zap-templates/zcl/data-model/chip/concentration-measurement-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/concentration-measurement-cluster.xml index c671c5b3e58373..4d03c539103970 100644 --- a/src/app/zap-templates/zcl/data-model/chip/concentration-measurement-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/concentration-measurement-cluster.xml @@ -29,6 +29,35 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MeasuredValue MinMeasuredValue MaxMeasuredValue @@ -54,6 +83,35 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MeasuredValue MinMeasuredValue @@ -80,6 +138,35 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MeasuredValue MinMeasuredValue MaxMeasuredValue @@ -105,6 +192,35 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MeasuredValue MinMeasuredValue MaxMeasuredValue @@ -130,6 +246,35 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MeasuredValue MinMeasuredValue MaxMeasuredValue @@ -155,6 +300,35 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MeasuredValue MinMeasuredValue MaxMeasuredValue @@ -180,6 +354,35 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MeasuredValue MinMeasuredValue MaxMeasuredValue @@ -205,6 +408,35 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MeasuredValue MinMeasuredValue MaxMeasuredValue @@ -230,6 +462,35 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MeasuredValue MinMeasuredValue MaxMeasuredValue @@ -255,6 +516,35 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MeasuredValue MinMeasuredValue MaxMeasuredValue @@ -268,26 +558,6 @@ limitations under the License. LevelValue - - - - - - - - - - - - - - - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/content-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/content-control-cluster.xml index d8077e9e9276cc..06468c114c42dc 100644 --- a/src/app/zap-templates/zcl/data-model/chip/content-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/content-control-cluster.xml @@ -24,6 +24,25 @@ limitations under the License. true true This cluster is used for managing the content control (including "parental control") settings on a media device such as a TV, or Set-top Box. + + + + + + + + + + + + + + + + + + + Enabled OnDemandRatings OnDemandRatingThreshold @@ -96,13 +115,4 @@ limitations under the License. - - - - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/content-launch-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/content-launch-cluster.xml index 037998053d512f..3c59ae1f9c90ad 100644 --- a/src/app/zap-templates/zcl/data-model/chip/content-launch-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/content-launch-cluster.xml @@ -177,11 +177,12 @@ limitations under the License. - - - - - - - + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/descriptor-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/descriptor-cluster.xml index f95d2acb1b2f40..639b965cfc9bf9 100644 --- a/src/app/zap-templates/zcl/data-model/chip/descriptor-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/descriptor-cluster.xml @@ -31,11 +31,6 @@ limitations under the License. - - - - - General Descriptor @@ -45,6 +40,10 @@ limitations under the License. + + + + DeviceTypeList ServerList ClientList diff --git a/src/app/zap-templates/zcl/data-model/chip/device-energy-management-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/device-energy-management-cluster.xml index 85762181765590..3f921f4e554409 100644 --- a/src/app/zap-templates/zcl/data-model/chip/device-energy-management-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/device-energy-management-cluster.xml @@ -16,16 +16,7 @@ limitations under the License. --> - - - - - - - - - - + Device Energy Management @@ -37,6 +28,73 @@ limitations under the License. This cluster allows a client to manage the power draw of a device. An example of such a client could be an Energy Management System (EMS) which controls an Energy Smart Appliance (ESA). + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ESAType ESACanGenerate diff --git a/src/app/zap-templates/zcl/data-model/chip/device-energy-management-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/device-energy-management-mode-cluster.xml index b41555e2fe03cd..043fb4a1833502 100644 --- a/src/app/zap-templates/zcl/data-model/chip/device-energy-management-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/device-energy-management-mode-cluster.xml @@ -34,6 +34,13 @@ limitations under the License. true Attributes and commands for selecting a mode from a list of supported options. + + + + + + + SupportedModes CurrentMode diff --git a/src/app/zap-templates/zcl/data-model/chip/dishwasher-alarm-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/dishwasher-alarm-cluster.xml index 3dc4ff779bd655..7e41a7a1c03f99 100644 --- a/src/app/zap-templates/zcl/data-model/chip/dishwasher-alarm-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/dishwasher-alarm-cluster.xml @@ -37,6 +37,12 @@ limitations under the License. true true + + + + + + Mask Latch State @@ -60,9 +66,4 @@ limitations under the License. - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/dishwasher-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/dishwasher-mode-cluster.xml index c578c164c0ca0f..436967be2cee89 100644 --- a/src/app/zap-templates/zcl/data-model/chip/dishwasher-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/dishwasher-mode-cluster.xml @@ -33,6 +33,13 @@ limitations under the License. true Attributes and commands for selecting a mode from a list of supported options. + + + + + + + SupportedModes CurrentMode diff --git a/src/app/zap-templates/zcl/data-model/chip/door-lock-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/door-lock-cluster.xml index 1c179f9324422a..cc2bf491f25045 100644 --- a/src/app/zap-templates/zcl/data-model/chip/door-lock-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/door-lock-cluster.xml @@ -64,6 +64,67 @@ limitations under the License. true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - + + + + + + + + + + @@ -815,25 +876,6 @@ limitations under the License. - - - - - - - - - - - - - - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/drlc-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/drlc-cluster.xml index dce7ff59f3fdac..d64bce1c85b7f6 100644 --- a/src/app/zap-templates/zcl/data-model/chip/drlc-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/drlc-cluster.xml @@ -17,16 +17,6 @@ limitations under the License. - - - - - - - - - - @@ -185,6 +175,30 @@ limitations under the License. true + + + + + + + + + + + + + + + + + + + + + + + + LoadControlPrograms NumberOfLoadControlPrograms Events diff --git a/src/app/zap-templates/zcl/data-model/chip/electrical-energy-measurement-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/electrical-energy-measurement-cluster.xml index 55a298ee596e53..0a4039badf7c97 100644 --- a/src/app/zap-templates/zcl/data-model/chip/electrical-energy-measurement-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/electrical-energy-measurement-cluster.xml @@ -16,13 +16,6 @@ limitations under the License. --> - - - - - - - Electrical Energy Measurement Measurement & Sensing @@ -32,6 +25,22 @@ limitations under the License. true This cluster provides a mechanism for querying data about the electrical energy imported or provided by the server. + + + + + + + + + + + + + + + + Accuracy CumulativeEnergyImported diff --git a/src/app/zap-templates/zcl/data-model/chip/electrical-power-measurement-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/electrical-power-measurement-cluster.xml index e723982ee0ffe8..69be8e08570f39 100644 --- a/src/app/zap-templates/zcl/data-model/chip/electrical-power-measurement-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/electrical-power-measurement-cluster.xml @@ -16,14 +16,6 @@ limitations under the License. --> - - - - - - - - Electrical Power Measurement Measurement & Sensing @@ -33,6 +25,31 @@ limitations under the License. true This cluster provides a mechanism for querying data about electrical power as measured by the server. + + + + + + + + + + + + + + + + + + + + + + + + + PowerMode NumberOfMeasurementTypes diff --git a/src/app/zap-templates/zcl/data-model/chip/energy-evse-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/energy-evse-cluster.xml index 107cc9cab7b103..cbc0882ac1b3ac 100644 --- a/src/app/zap-templates/zcl/data-model/chip/energy-evse-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/energy-evse-cluster.xml @@ -96,6 +96,24 @@ limitations under the License. Electric Vehicle Supply Equipment (EVSE) is equipment used to charge an Electric Vehicle (EV) or Plug-In Hybrid Electric Vehicle. This cluster provides an interface to the functionality of Electric Vehicle Supply Equipment (EVSE) management. + + + + + + + + + + + + + + + + + + State @@ -224,13 +242,5 @@ limitations under the License. - - - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/energy-evse-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/energy-evse-mode-cluster.xml index 4418502ae5e389..22e5562ed33f7f 100644 --- a/src/app/zap-templates/zcl/data-model/chip/energy-evse-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/energy-evse-mode-cluster.xml @@ -33,6 +33,13 @@ limitations under the License. true Attributes and commands for selecting a mode from a list of supported options. + + + + + + + SupportedModes CurrentMode diff --git a/src/app/zap-templates/zcl/data-model/chip/energy-preference-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/energy-preference-cluster.xml index 32893bd82a68e9..a5e1ea8e950ae1 100644 --- a/src/app/zap-templates/zcl/data-model/chip/energy-preference-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/energy-preference-cluster.xml @@ -24,6 +24,15 @@ limitations under the License. + + + + + + + + + EnergyBalances @@ -49,12 +58,6 @@ limitations under the License. - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/ethernet-network-diagnostics-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/ethernet-network-diagnostics-cluster.xml index 830814b55dd2f3..f2cf3173c68b29 100644 --- a/src/app/zap-templates/zcl/data-model/chip/ethernet-network-diagnostics-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/ethernet-network-diagnostics-cluster.xml @@ -29,17 +29,22 @@ limitations under the License. - - - - - General Ethernet Network Diagnostics 0x0037 ETHERNET_NETWORK_DIAGNOSTICS_CLUSTER The Ethernet Network Diagnostics Cluster provides a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. + + + + + + + + + + PHYRate FullDuplex PacketRxCount diff --git a/src/app/zap-templates/zcl/data-model/chip/fan-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/fan-control-cluster.xml index c2deff336eae46..6cf763dd30ba26 100644 --- a/src/app/zap-templates/zcl/data-model/chip/fan-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/fan-control-cluster.xml @@ -17,16 +17,6 @@ limitations under the License. - - - - - - - - - - @@ -85,6 +75,27 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + + FanMode FanModeSequence PercentSetting diff --git a/src/app/zap-templates/zcl/data-model/chip/general-diagnostics-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/general-diagnostics-cluster.xml index 26e14006a6cca8..26f0e5708dd280 100644 --- a/src/app/zap-templates/zcl/data-model/chip/general-diagnostics-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/general-diagnostics-cluster.xml @@ -17,11 +17,6 @@ limitations under the License. - - - - - @@ -90,6 +85,13 @@ limitations under the License. GENERAL_DIAGNOSTICS_CLUSTER The General Diagnostics Cluster, along with other diagnostics clusters, provide a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. + + + + + + + NetworkInterfaces RebootCount + + + + + + + + + + + + + + + + + + + + + + + + + + + IdleModeDuration ActiveModeDuration ActiveModeThreshold diff --git a/src/app/zap-templates/zcl/data-model/chip/keypad-input-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/keypad-input-cluster.xml index d4f6ffbba9a742..b43ace5c0c8383 100644 --- a/src/app/zap-templates/zcl/data-model/chip/keypad-input-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/keypad-input-cluster.xml @@ -25,6 +25,18 @@ limitations under the License. true This cluster provides an interface for controlling a device like a TV using action commands such as UP, DOWN, and SELECT. + + + + + + + + + + + + Upon receipt, this SHALL process a keycode as input to the media device. @@ -140,11 +152,5 @@ limitations under the License. - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/laundry-washer-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/laundry-washer-mode-cluster.xml index fff4fdcaac0dfb..99e4ef50c9ca7b 100644 --- a/src/app/zap-templates/zcl/data-model/chip/laundry-washer-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/laundry-washer-mode-cluster.xml @@ -34,6 +34,13 @@ limitations under the License. true Attributes and commands for selecting a mode from a list of supported options. + + + + + + + SupportedModes CurrentMode diff --git a/src/app/zap-templates/zcl/data-model/chip/level-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/level-control-cluster.xml index dca3fb6f3532d1..79a7da56a448e0 100644 --- a/src/app/zap-templates/zcl/data-model/chip/level-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/level-control-cluster.xml @@ -17,12 +17,6 @@ limitations under the License. - - - - - - @@ -54,6 +48,20 @@ limitations under the License. + + + + + + + + + + + + CurrentLevel RemainingTime MinLevel diff --git a/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml b/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml index 96ed6fdc2da625..795f7a71cf54bc 100644 --- a/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml +++ b/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml @@ -86,7 +86,18 @@ limitations under the License. - + + + + + + + + + + + + @@ -253,6 +264,11 @@ limitations under the License. CopySceneResponse + + + + + ON_OFF GLOBAL_SCENE_CONTROL ON_TIME @@ -266,6 +282,14 @@ limitations under the License. OnWithTimedOff + + + + + + + + CURRENT_LEVEL OPTIONS LEVEL_CONTROL_REMAINING_TIME @@ -341,6 +365,11 @@ limitations under the License. CopySceneResponse + + + + + ON_OFF GLOBAL_SCENE_CONTROL ON_TIME @@ -354,6 +383,14 @@ limitations under the License. OnWithTimedOff + + + + + + + + CURRENT_LEVEL OPTIONS LEVEL_CONTROL_REMAINING_TIME @@ -426,6 +463,11 @@ limitations under the License. CopySceneResponse + + + + + ON_OFF GLOBAL_SCENE_CONTROL ON_TIME @@ -439,6 +481,14 @@ limitations under the License. OnWithTimedOff + + + + + + + + CURRENT_LEVEL OPTIONS LEVEL_CONTROL_REMAINING_TIME @@ -455,6 +505,11 @@ limitations under the License. StopWithOnOff + + + + + COLOR_CONTROL_REMAINING_TIME COLOR_CONTROL_COLOR_TEMPERATURE COLOR_CONTROL_COLOR_MODE @@ -525,6 +580,11 @@ limitations under the License. GetSceneMembershipResponse + + + + + ON_OFF GLOBAL_SCENE_CONTROL ON_TIME @@ -538,6 +598,14 @@ limitations under the License. OnWithTimedOff + + + + + + + + CURRENT_LEVEL OPTIONS LEVEL_CONTROL_REMAINING_TIME @@ -554,6 +622,23 @@ limitations under the License. StopWithOnOff + + + + + + + + + + + + + + + + + COLOR_CONTROL_REMAINING_TIME COLOR_CONTROL_CURRENT_X COLOR_CONTROL_CURRENT_Y @@ -628,6 +713,11 @@ limitations under the License. GetSceneMembershipResponse + + + + + ON_OFF GLOBAL_SCENE_CONTROL ON_TIME @@ -641,6 +731,14 @@ limitations under the License. OnWithTimedOff + + + + + + + + CURRENT_LEVEL OPTIONS LEVEL_CONTROL_REMAINING_TIME @@ -709,6 +807,11 @@ limitations under the License. GetSceneMembershipResponse + + + + + ON_OFF GLOBAL_SCENE_CONTROL ON_TIME @@ -722,6 +825,14 @@ limitations under the License. OnWithTimedOff + + + + + + + + CURRENT_LEVEL OPTIONS LEVEL_CONTROL_REMAINING_TIME @@ -1377,7 +1488,29 @@ limitations under the License. CLIENT_LIST PARTS_LIST - + + + + + + + + + + + + + + + + + + + + + + + @@ -1457,7 +1590,15 @@ limitations under the License. RemoveAllGroups AddGroupIfIdentifying - + + + + + + + + + @@ -1486,7 +1627,15 @@ limitations under the License. - + + + + + + + + + @@ -1674,7 +1823,13 @@ limitations under the License. - + + + + + + + @@ -1829,7 +1984,13 @@ limitations under the License. - + + + + + + + @@ -1877,6 +2038,11 @@ limitations under the License. Identify + + + + + ON_OFF Off On @@ -1976,10 +2142,22 @@ limitations under the License. Endpoint - + + + + + + + - + + + + + + + @@ -2008,7 +2186,16 @@ limitations under the License. - + + + + + + + + + + @@ -2025,7 +2212,13 @@ limitations under the License. - + + + + + + + @@ -2040,8 +2233,20 @@ limitations under the License. - - + + + + + + + + + + + + + + @@ -2058,8 +2263,20 @@ limitations under the License. - - + + + + + + + + + + + + + + @@ -2078,7 +2295,19 @@ limitations under the License. - + + + + + + + + + + + + + @@ -2110,8 +2339,20 @@ limitations under the License. - - + + + + + + + + + + + + + + @@ -2375,6 +2616,11 @@ limitations under the License. + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/media-input-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/media-input-cluster.xml index 028ab467af7c0c..597b285cc1b5dd 100644 --- a/src/app/zap-templates/zcl/data-model/chip/media-input-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/media-input-cluster.xml @@ -26,6 +26,12 @@ limitations under the License. This cluster provides an interface for controlling the Input Selector on a media device such as a TV. + + + + + + InputList CurrentInput @@ -75,9 +81,5 @@ limitations under the License. - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/media-playback-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/media-playback-cluster.xml index 32c2da12ed0780..a77b8fa4befb4c 100644 --- a/src/app/zap-templates/zcl/data-model/chip/media-playback-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/media-playback-cluster.xml @@ -27,6 +27,25 @@ limitations under the License. This cluster provides an interface for controlling Media Playback (PLAY, PAUSE, etc) on a media device such as a TV or Speaker. + + + + + + + + + + + + + + + + + + + CurrentState StartTime Duration @@ -161,14 +180,6 @@ limitations under the License. - - - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/messages-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/messages-cluster.xml index 16b1527625d320..741ba801f5c092 100644 --- a/src/app/zap-templates/zcl/data-model/chip/messages-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/messages-cluster.xml @@ -17,13 +17,6 @@ limitations under the License. - - - - - - - @@ -78,6 +71,26 @@ limitations under the License. true true + + + + + + + + + + + + + + + + + + + + Messages ActiveMessageIDs diff --git a/src/app/zap-templates/zcl/data-model/chip/microwave-oven-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/microwave-oven-control-cluster.xml index ab13fc51e10f29..5567bc99461893 100644 --- a/src/app/zap-templates/zcl/data-model/chip/microwave-oven-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/microwave-oven-control-cluster.xml @@ -17,12 +17,6 @@ limitations under the License. - - - - - - Microwave Oven Control @@ -32,6 +26,21 @@ limitations under the License. MICROWAVE_OVEN_CONTROL_CLUSTER true true + + + + + + + + + + + + + + + CookTime MaxCookTime PowerSetting diff --git a/src/app/zap-templates/zcl/data-model/chip/microwave-oven-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/microwave-oven-mode-cluster.xml index 826d77ecd9f42a..b26f022f3cc9b4 100644 --- a/src/app/zap-templates/zcl/data-model/chip/microwave-oven-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/microwave-oven-mode-cluster.xml @@ -32,6 +32,13 @@ limitations under the License. true Attributes and commands for selecting a mode from a list of supported options. + + + + + + + SupportedModes CurrentMode diff --git a/src/app/zap-templates/zcl/data-model/chip/mode-base-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/mode-base-cluster.xml index abacba4bafe631..111df8eca07eff 100644 --- a/src/app/zap-templates/zcl/data-model/chip/mode-base-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/mode-base-cluster.xml @@ -86,17 +86,5 @@ This is because zap does not currently support generating code for clusters that - - - - - - - - - - - - - + diff --git a/src/app/zap-templates/zcl/data-model/chip/mode-select-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/mode-select-cluster.xml index 0462a48e8bc513..443acb1c955c36 100644 --- a/src/app/zap-templates/zcl/data-model/chip/mode-select-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/mode-select-cluster.xml @@ -40,6 +40,12 @@ limitations under the License. + + + + + + Attributes and commands for selecting a mode from a list of supported options. Description @@ -59,8 +65,5 @@ limitations under the License. - - - - + diff --git a/src/app/zap-templates/zcl/data-model/chip/network-commissioning-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/network-commissioning-cluster.xml index 340effa347298d..964923be4f2dfa 100644 --- a/src/app/zap-templates/zcl/data-model/chip/network-commissioning-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/network-commissioning-cluster.xml @@ -88,14 +88,6 @@ limitations under the License. - - - - - - - - Network Commissioning CHIP @@ -105,6 +97,21 @@ limitations under the License. true true + + + + + + + + + + + + + + + MaxNetworks diff --git a/src/app/zap-templates/zcl/data-model/chip/onoff-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/onoff-cluster.xml index b5b5aa913229e8..04dcfed83766e8 100644 --- a/src/app/zap-templates/zcl/data-model/chip/onoff-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/onoff-cluster.xml @@ -55,6 +55,33 @@ limitations under the License. Attributes and commands for switching devices between 'On' and 'Off' states. + + + + + + + + + + + + + + + + + + + + + + + + + + + OnOff GlobalSceneControl OnTime @@ -95,10 +122,4 @@ limitations under the License. - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/oven-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/oven-mode-cluster.xml index d97be938d74d2d..2508b4741602b3 100644 --- a/src/app/zap-templates/zcl/data-model/chip/oven-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/oven-mode-cluster.xml @@ -39,6 +39,13 @@ limitations under the License. true Attributes and commands for selecting a mode from a list of supported options. + + + + + + + SupportedModes CurrentMode diff --git a/src/app/zap-templates/zcl/data-model/chip/power-source-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/power-source-cluster.xml index 913df128cc758e..5701dc6ec61e65 100644 --- a/src/app/zap-templates/zcl/data-model/chip/power-source-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/power-source-cluster.xml @@ -24,6 +24,25 @@ limitations under the License. true true This cluster is used to describe the configuration and capabilities of a physical power source that provides power to the Node. + + + + + + + + + + + + + + + + + + + Status Order @@ -80,13 +99,6 @@ limitations under the License. - - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/power-topology-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/power-topology-cluster.xml index 9eef1e03c6c023..2fdddcbe3560da 100644 --- a/src/app/zap-templates/zcl/data-model/chip/power-topology-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/power-topology-cluster.xml @@ -16,13 +16,7 @@ limitations under the License. --> - - - - - - - + Measurement & Sensing Power Topology @@ -32,6 +26,24 @@ limitations under the License. true true + + + + + + + + + + + + + + + + + + AvailableEndpoints ActiveEndpoints diff --git a/src/app/zap-templates/zcl/data-model/chip/pressure-measurement-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/pressure-measurement-cluster.xml index f66c546abd60ce..f9487af7f3a9e2 100644 --- a/src/app/zap-templates/zcl/data-model/chip/pressure-measurement-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/pressure-measurement-cluster.xml @@ -25,6 +25,13 @@ limitations under the License. true true + + + + + + + MeasuredValue MinMeasuredValue MaxMeasuredValue @@ -36,8 +43,4 @@ limitations under the License. Scale - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/pump-configuration-and-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/pump-configuration-and-control-cluster.xml index 7aa34bc6554b68..74416092e7c7f8 100644 --- a/src/app/zap-templates/zcl/data-model/chip/pump-configuration-and-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/pump-configuration-and-control-cluster.xml @@ -25,6 +25,31 @@ limitations under the License. true true + + + + + + + + + + + + + + + + + + + + + + + + + MaxPressure MaxSpeed MaxFlow @@ -149,15 +174,5 @@ limitations under the License. - - - - - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/refrigerator-alarm.xml b/src/app/zap-templates/zcl/data-model/chip/refrigerator-alarm.xml index 21bf7da48bd02e..58fa70163f65ea 100644 --- a/src/app/zap-templates/zcl/data-model/chip/refrigerator-alarm.xml +++ b/src/app/zap-templates/zcl/data-model/chip/refrigerator-alarm.xml @@ -28,6 +28,7 @@ limitations under the License. REFRIGERATOR_ALARM_CLUSTER true true + Mask State Supported diff --git a/src/app/zap-templates/zcl/data-model/chip/refrigerator-and-temperature-controlled-cabinet-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/refrigerator-and-temperature-controlled-cabinet-mode-cluster.xml index a8f9605b81a1bc..e5ff239c18afa6 100644 --- a/src/app/zap-templates/zcl/data-model/chip/refrigerator-and-temperature-controlled-cabinet-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/refrigerator-and-temperature-controlled-cabinet-mode-cluster.xml @@ -32,6 +32,13 @@ limitations under the License. true Attributes and commands for selecting a mode from a list of supported options. + + + + + + + SupportedModes CurrentMode diff --git a/src/app/zap-templates/zcl/data-model/chip/resource-monitoring-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/resource-monitoring-cluster.xml index 4be5dbddc12478..66de9ee66cbebd 100644 --- a/src/app/zap-templates/zcl/data-model/chip/resource-monitoring-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/resource-monitoring-cluster.xml @@ -25,6 +25,18 @@ limitations under the License. true true + + + + + + + + + + + + Condition DegradationDirection @@ -48,6 +60,18 @@ limitations under the License. true true + + + + + + + + + + + + Condition DegradationDirection @@ -62,14 +86,6 @@ limitations under the License. - - - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/rvc-clean-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/rvc-clean-mode-cluster.xml index 3c8686b6d90fb3..c528759d2a8cb7 100644 --- a/src/app/zap-templates/zcl/data-model/chip/rvc-clean-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/rvc-clean-mode-cluster.xml @@ -38,6 +38,7 @@ limitations under the License. true Attributes and commands for selecting a mode from a list of supported options. + SupportedModes CurrentMode @@ -62,9 +63,9 @@ limitations under the License. - - - - + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/rvc-run-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/rvc-run-mode-cluster.xml index f2d24e62ede0f4..f13f86ac2dc97e 100644 --- a/src/app/zap-templates/zcl/data-model/chip/rvc-run-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/rvc-run-mode-cluster.xml @@ -69,9 +69,8 @@ limitations under the License. - - - - - + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/scene.xml b/src/app/zap-templates/zcl/data-model/chip/scene.xml index e16047b9c14c07..0c1189093c4e79 100644 --- a/src/app/zap-templates/zcl/data-model/chip/scene.xml +++ b/src/app/zap-templates/zcl/data-model/chip/scene.xml @@ -51,6 +51,12 @@ limitations under the License. true true + + + + + + LastConfiguredBy SceneTableSize @@ -195,8 +201,4 @@ limitations under the License. - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/smoke-co-alarm-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/smoke-co-alarm-cluster.xml index c6827dd1c4bd48..31ae0bba9e7d99 100644 --- a/src/app/zap-templates/zcl/data-model/chip/smoke-co-alarm-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/smoke-co-alarm-cluster.xml @@ -36,6 +36,15 @@ limitations under the License. + + + + + + + + + ExpressedState SmokeState @@ -148,9 +157,4 @@ limitations under the License. - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/software-diagnostics-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/software-diagnostics-cluster.xml index 41dfb3a156693b..3ac2ba42e8e22e 100644 --- a/src/app/zap-templates/zcl/data-model/chip/software-diagnostics-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/software-diagnostics-cluster.xml @@ -30,6 +30,13 @@ limitations under the License. 0x0034 SOFTWARE_DIAGNOSTICS_CLUSTER The Software Diagnostics Cluster provides a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. + + + + + + + ThreadMetrics CurrentHeapFree CurrentHeapUsed @@ -45,8 +52,5 @@ limitations under the License. - - - - + diff --git a/src/app/zap-templates/zcl/data-model/chip/switch-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/switch-cluster.xml index 7df57e3ebd26c1..c5e69b3c51ff39 100644 --- a/src/app/zap-templates/zcl/data-model/chip/switch-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/switch-cluster.xml @@ -30,6 +30,36 @@ Interactions with the switch device are exposed as attributes (for the latching + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NumberOfPositions CurrentPosition MultiPressMax @@ -66,13 +96,5 @@ Interactions with the switch device are exposed as attributes (for the latching - - - - - - - - diff --git a/src/app/zap-templates/zcl/data-model/chip/temperature-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/temperature-control-cluster.xml index 7509e9b44579cb..da0c0bcee983bb 100644 --- a/src/app/zap-templates/zcl/data-model/chip/temperature-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/temperature-control-cluster.xml @@ -25,6 +25,21 @@ limitations under the License. TEMPERATURE_CONTROL_CLUSTER true true + + + + + + + + + + + + + + + TemperatureSetpoint MinTemperature MaxTemperature @@ -38,10 +53,5 @@ limitations under the License. - - - - - - + diff --git a/src/app/zap-templates/zcl/data-model/chip/thermostat-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/thermostat-cluster.xml index 948c0937a3fd10..62e9a6d883516d 100644 --- a/src/app/zap-templates/zcl/data-model/chip/thermostat-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/thermostat-cluster.xml @@ -16,20 +16,7 @@ limitations under the License. --> - - - - - - - - - - - - - - + @@ -290,6 +277,57 @@ limitations under the License. true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + LocalTemperature diff --git a/src/app/zap-templates/zcl/data-model/chip/thread-network-diagnostics-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/thread-network-diagnostics-cluster.xml index e56aeca08f2592..77ec8699615156 100644 --- a/src/app/zap-templates/zcl/data-model/chip/thread-network-diagnostics-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/thread-network-diagnostics-cluster.xml @@ -92,6 +92,22 @@ limitations under the License. THREAD_NETWORK_DIAGNOSTICS_CLUSTER The Thread Network Diagnostics Cluster provides a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems + + + + + + + + + + + + + + + + Channel RoutingRole NetworkName @@ -169,11 +185,5 @@ limitations under the License. - - - - - - - + diff --git a/src/app/zap-templates/zcl/data-model/chip/time-format-localization-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/time-format-localization-cluster.xml index 39ba6d316712e3..6ade7abe2e446c 100644 --- a/src/app/zap-templates/zcl/data-model/chip/time-format-localization-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/time-format-localization-cluster.xml @@ -23,11 +23,6 @@ limitations under the License. - - - - - @@ -55,6 +50,13 @@ limitations under the License. may have differing preferences for how dates and times are conveyed. As such, Nodes that visually or audibly convey time information need a mechanism by which they can be configured to use a user’s preferred format. + + + + + + + HourFormat diff --git a/src/app/zap-templates/zcl/data-model/chip/time-synchronization-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/time-synchronization-cluster.xml index 17271c56352c03..9336a6a944735e 100644 --- a/src/app/zap-templates/zcl/data-model/chip/time-synchronization-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/time-synchronization-cluster.xml @@ -17,13 +17,6 @@ limitations under the License. - - - - - - - @@ -106,6 +99,21 @@ limitations under the License. Accurate time is required for a number of reasons, including scheduling, display and validating security materials. + + + + + + + + + + + + + + + UTCTime Granularity TimeSource diff --git a/src/app/zap-templates/zcl/data-model/chip/timer-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/timer-cluster.xml index 1b1156b54e5480..d849313d269a83 100644 --- a/src/app/zap-templates/zcl/data-model/chip/timer-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/timer-cluster.xml @@ -18,10 +18,6 @@ limitations under the License. - - - - @@ -42,6 +38,13 @@ limitations under the License. + + + + + + + SetTime TimeRemaining TimerState diff --git a/src/app/zap-templates/zcl/data-model/chip/unit-localization-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/unit-localization-cluster.xml index febb19ed595e36..fb6238add46a4f 100644 --- a/src/app/zap-templates/zcl/data-model/chip/unit-localization-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/unit-localization-cluster.xml @@ -34,14 +34,18 @@ limitations under the License. user. As such, Nodes that visually or audibly convey measurable values to the user need a mechanism by which they can be configured to use a user’s preferred unit. + + + + + + + TemperatureUnit - - - - + diff --git a/src/app/zap-templates/zcl/data-model/chip/valve-configuration-and-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/valve-configuration-and-control-cluster.xml index 0818b3637c892a..4bb545112be846 100644 --- a/src/app/zap-templates/zcl/data-model/chip/valve-configuration-and-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/valve-configuration-and-control-cluster.xml @@ -17,11 +17,6 @@ limitations under the License. - - - - - @@ -55,6 +50,13 @@ limitations under the License. This cluster is used to configure a valve. + + + + + + + OpenDuration diff --git a/src/app/zap-templates/zcl/data-model/chip/washer-controls-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/washer-controls-cluster.xml index 69a50f4a7ee8be..2dc01920ae3e37 100644 --- a/src/app/zap-templates/zcl/data-model/chip/washer-controls-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/washer-controls-cluster.xml @@ -17,11 +17,6 @@ limitations under the License. - - - - - @@ -42,6 +37,15 @@ limitations under the License. + + + + + + + + + SpinSpeeds SpinSpeedCurrent NumberOfRinses diff --git a/src/app/zap-templates/zcl/data-model/chip/wifi-network-diagnostics-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/wifi-network-diagnostics-cluster.xml index a2d0ca758de91e..33d3f661fd3834 100644 --- a/src/app/zap-templates/zcl/data-model/chip/wifi-network-diagnostics-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/wifi-network-diagnostics-cluster.xml @@ -47,17 +47,23 @@ limitations under the License. - - - - - + General WiFi Network Diagnostics 0x0036 WIFI_NETWORK_DIAGNOSTICS_CLUSTER The Wi-Fi Network Diagnostics Cluster provides a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. + + + + + + + + + + BSSID SecurityType WiFiVersion diff --git a/src/app/zap-templates/zcl/data-model/chip/window-covering.xml b/src/app/zap-templates/zcl/data-model/chip/window-covering.xml index e98329a72812a0..b7224f0fb67ea0 100644 --- a/src/app/zap-templates/zcl/data-model/chip/window-covering.xml +++ b/src/app/zap-templates/zcl/data-model/chip/window-covering.xml @@ -33,6 +33,28 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + + + Type @@ -211,12 +233,4 @@ limitations under the License. - - - - - - - - diff --git a/src/app/zap-templates/zcl/zcl-with-test-extensions.json b/src/app/zap-templates/zcl/zcl-with-test-extensions.json index 5bae212dc6d50c..7213b96cf0e012 100644 --- a/src/app/zap-templates/zcl/zcl-with-test-extensions.json +++ b/src/app/zap-templates/zcl/zcl-with-test-extensions.json @@ -2,6 +2,7 @@ "description": "Matter SDK ZCL data with some extensions", "category": "matter", "version": 1, + "requiredFeatureLevel": 102, "xmlRoot": [ ".", "./data-model/chip/", diff --git a/src/app/zap-templates/zcl/zcl.json b/src/app/zap-templates/zcl/zcl.json index dcfbaf6986c23c..8a4159e98f7eb8 100644 --- a/src/app/zap-templates/zcl/zcl.json +++ b/src/app/zap-templates/zcl/zcl.json @@ -2,6 +2,7 @@ "description": "Matter SDK ZCL data", "category": "matter", "version": 1, + "requiredFeatureLevel": 102, "xmlRoot": [ ".", "./data-model/chip/", diff --git a/src/ble/BLEEndPoint.cpp b/src/ble/BLEEndPoint.cpp index 840a668be0a62a..ba6400fc8a19b7 100644 --- a/src/ble/BLEEndPoint.cpp +++ b/src/ble/BLEEndPoint.cpp @@ -25,22 +25,29 @@ * */ -#include -#include +#define _CHIP_BLE_BLE_H +#include "BLEEndPoint.h" -#include - -#if CONFIG_NETWORK_LAYER_BLE -#include +#include +#include +#include #include -#include #include #include - -#include -#include -#include +#include +#include +#include + +#include "BleApplicationDelegate.h" +#include "BleConfig.h" +#include "BleError.h" +#include "BleLayer.h" +#include "BleLayerDelegate.h" +#include "BlePlatformDelegate.h" +#include "BleRole.h" +#include "BleUUID.h" +#include "BtpEngine.h" // Define below to enable extremely verbose, BLE end point-specific debug logging. #undef CHIP_BLE_END_POINT_DEBUG_LOGGING_ENABLED @@ -1498,5 +1505,3 @@ void BLEEndPoint::HandleUnsubscribeTimeout(chip::System::Layer * systemLayer, vo } /* namespace Ble */ } /* namespace chip */ - -#endif /* CONFIG_NETWORK_LAYER_BLE */ diff --git a/src/ble/BLEEndPoint.h b/src/ble/BLEEndPoint.h index 1bce51e1671419..f027a9c2a9c0e6 100644 --- a/src/ble/BLEEndPoint.h +++ b/src/ble/BLEEndPoint.h @@ -27,10 +27,23 @@ #pragma once +#ifndef _CHIP_BLE_BLE_H +#error "Please include instead!" +#endif + +#include + +#include +#include +#include #include +#include -#include -#include +#include "BleConnectionDelegate.h" +#include "BleLayerDelegate.h" +#include "BlePlatformDelegate.h" +#include "BleRole.h" +#include "BtpEngine.h" namespace chip { namespace Ble { @@ -46,8 +59,6 @@ enum // Forward declarations class BleLayer; class BleEndPointPool; -// BLEEndPoint holds a pointer to BleLayerDelegate for messages, while BleLayerDelegate functions also accepts BLEEndPoint. -class BleLayerDelegate; class DLL_EXPORT BLEEndPoint { diff --git a/src/ble/Ble.h b/src/ble/Ble.h index 65b02d81da1768..171d88a90749f3 100644 --- a/src/ble/Ble.h +++ b/src/ble/Ble.h @@ -28,14 +28,22 @@ #include +// Other includes check for the _CHIP_BLE_BLE_H define to ensure that the BLE +// library is included correctly by others (via Ble.h umbrella header). +#define _CHIP_BLE_BLE_H + #include #include #include #include #include +#include #include #include #include +#include + +#undef _CHIP_BLE_BLE_H /** * @namespace Ble diff --git a/src/ble/BleApplicationDelegate.h b/src/ble/BleApplicationDelegate.h index 2584aeb6b908fd..af45b1145155aa 100644 --- a/src/ble/BleApplicationDelegate.h +++ b/src/ble/BleApplicationDelegate.h @@ -24,10 +24,14 @@ #pragma once -#include +#ifndef _CHIP_BLE_BLE_H +#error "Please include instead!" +#endif #include +#include "BleConfig.h" + namespace chip { namespace Ble { diff --git a/src/ble/BleConnectionDelegate.h b/src/ble/BleConnectionDelegate.h index d5e10d29a9a597..d54a09e3ecb416 100644 --- a/src/ble/BleConnectionDelegate.h +++ b/src/ble/BleConnectionDelegate.h @@ -23,12 +23,16 @@ #pragma once -#include -#include +#ifndef _CHIP_BLE_BLE_H +#error "Please include instead!" +#endif #include #include +#include "BleConfig.h" +#include "BleError.h" + namespace chip { namespace Ble { class BleLayer; diff --git a/src/ble/BleError.cpp b/src/ble/BleError.cpp index 10ff63753796b3..340b2e6e1eda7b 100644 --- a/src/ble/BleError.cpp +++ b/src/ble/BleError.cpp @@ -21,14 +21,10 @@ * This file contains functions for working with BLE Layer errors. */ -#include +#define _CHIP_BLE_BLE_H +#include "BleError.h" -#include - -#if CONFIG_NETWORK_LAYER_BLE - -#include -#include +#include namespace chip { namespace Ble { @@ -140,5 +136,3 @@ bool FormatLayerError(char * buf, uint16_t bufSize, CHIP_ERROR err) } /* namespace Ble */ } /* namespace chip */ - -#endif // CONFIG_NETWORK_LAYER_BLE diff --git a/src/ble/BleError.h b/src/ble/BleError.h index a95681a1b96685..ad4b2cdad29c2b 100644 --- a/src/ble/BleError.h +++ b/src/ble/BleError.h @@ -30,7 +30,11 @@ #pragma once -#include "BleConfig.h" +#ifndef _CHIP_BLE_BLE_H +#error "Please include instead!" +#endif + +#include #include diff --git a/src/ble/BleLayer.cpp b/src/ble/BleLayer.cpp index 0472d70ac28d2c..d4a1e3209610a6 100644 --- a/src/ble/BleLayer.cpp +++ b/src/ble/BleLayer.cpp @@ -50,21 +50,28 @@ * drive BLE data and control input up the stack. */ -#include +#define _CHIP_BLE_BLE_H +#include "BleLayer.h" -#if CONFIG_NETWORK_LAYER_BLE - -#include - -#include -#include -#include -#include -#include +#include +#include #include #include +#include #include +#include +#include + +#include "BLEEndPoint.h" +#include "BleApplicationDelegate.h" +#include "BleConfig.h" +#include "BleConnectionDelegate.h" +#include "BleError.h" +#include "BleLayerDelegate.h" +#include "BlePlatformDelegate.h" +#include "BleRole.h" +#include "BleUUID.h" // Magic values expected in first 2 bytes of valid BLE transport capabilities request or response: #define CAPABILITIES_MSG_CHECK_BYTE_1 0b01100101 @@ -788,5 +795,3 @@ void BleLayer::OnConnectionError(void * appState, CHIP_ERROR err) } /* namespace Ble */ } /* namespace chip */ - -#endif /* CONFIG_NETWORK_LAYER_BLE */ diff --git a/src/ble/BleLayer.h b/src/ble/BleLayer.h index a1c4d191672617..d9480cbf74ff79 100644 --- a/src/ble/BleLayer.h +++ b/src/ble/BleLayer.h @@ -47,21 +47,26 @@ #pragma once -#include +#ifndef _CHIP_BLE_BLE_H +#error "Please include instead!" +#endif -#include +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include -#include -#include -#include +#include "BleApplicationDelegate.h" +#include "BleConfig.h" +#include "BleConnectionDelegate.h" +#include "BleLayerDelegate.h" +#include "BlePlatformDelegate.h" +#include "BleRole.h" +#include "BleUUID.h" namespace chip { namespace Ble { @@ -78,10 +83,6 @@ namespace Ble { #define CHIP_BLE_TRANSPORT_PROTOCOL_MIN_SUPPORTED_VERSION kBleTransportProtocolVersion_V4 #define CHIP_BLE_TRANSPORT_PROTOCOL_MAX_SUPPORTED_VERSION kBleTransportProtocolVersion_V4 -/// Forward declarations. -class BleLayer; -class BLEEndPoint; - /// Enum defining versions of CHIP over BLE transport protocol. typedef enum { @@ -344,5 +345,3 @@ class DLL_EXPORT BleLayer } /* namespace Ble */ } /* namespace chip */ - -#include "BLEEndPoint.h" diff --git a/src/ble/BleLayerDelegate.h b/src/ble/BleLayerDelegate.h index 63d4243dbeb3b5..cde31569e5a53e 100644 --- a/src/ble/BleLayerDelegate.h +++ b/src/ble/BleLayerDelegate.h @@ -23,15 +23,23 @@ #pragma once -#include -#include -#include -#include +#ifndef _CHIP_BLE_BLE_H +#error "Please include instead!" +#endif + #include +#include "BleConfig.h" +#include "BleError.h" +#include "BleUUID.h" + namespace chip { namespace Ble { +// BLEEndPoint holds a pointer to BleLayerDelegate for messages, +// while BleLayerDelegate functions also accepts BLEEndPoint. +class BLEEndPoint; + class BleLayerDelegate { public: diff --git a/src/ble/BlePlatformDelegate.h b/src/ble/BlePlatformDelegate.h index 3e5e62736d9f65..0db09441bffae0 100644 --- a/src/ble/BlePlatformDelegate.h +++ b/src/ble/BlePlatformDelegate.h @@ -24,13 +24,16 @@ #pragma once -#include - -#include +#ifndef _CHIP_BLE_BLE_H +#error "Please include instead!" +#endif #include #include +#include "BleConfig.h" +#include "BleUUID.h" + namespace chip { namespace Ble { diff --git a/src/ble/BleRole.h b/src/ble/BleRole.h index e228a478f72be3..75e67dd443c73b 100644 --- a/src/ble/BleRole.h +++ b/src/ble/BleRole.h @@ -18,6 +18,10 @@ #pragma once +#ifndef _CHIP_BLE_BLE_H +#error "Please include instead!" +#endif + namespace chip { namespace Ble { diff --git a/src/ble/BleUUID.cpp b/src/ble/BleUUID.cpp index 2311d33aaeb77e..098595fd721e5c 100644 --- a/src/ble/BleUUID.cpp +++ b/src/ble/BleUUID.cpp @@ -15,16 +15,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#if CONFIG_NETWORK_LAYER_BLE +#define _CHIP_BLE_BLE_H +#include "BleUUID.h" #include #include #include -#include "BleUUID.h" - namespace chip { namespace Ble { @@ -78,5 +76,3 @@ bool StringToUUID(const char * str, ChipBleUUID & uuid) } /* namespace Ble */ } /* namespace chip */ - -#endif /* CONFIG_NETWORK_LAYER_BLE */ diff --git a/src/ble/BleUUID.h b/src/ble/BleUUID.h index 76fe0f322fec6a..315af9e8c76a32 100644 --- a/src/ble/BleUUID.h +++ b/src/ble/BleUUID.h @@ -15,9 +15,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #pragma once -#include +#ifndef _CHIP_BLE_BLE_H +#error "Please include instead!" +#endif + +#include namespace chip { namespace Ble { diff --git a/src/ble/BtpEngine.cpp b/src/ble/BtpEngine.cpp index cb3ac8ee092e2a..3a11c61ea75de9 100644 --- a/src/ble/BtpEngine.cpp +++ b/src/ble/BtpEngine.cpp @@ -25,15 +25,19 @@ * */ -#include +#define _CHIP_BLE_BLE_H +#include "BtpEngine.h" -#if CONFIG_NETWORK_LAYER_BLE - -#include +#include +#include +#include #include #include #include +#include + +#include "BleError.h" // Define below to enable extremely verbose BLE-specific debug logging. #undef CHIP_BTP_PROTOCOL_ENGINE_DEBUG_LOGGING_ENABLED @@ -576,5 +580,3 @@ void BtpEngine::LogStateDebug() const } /* namespace Ble */ } /* namespace chip */ - -#endif /* CONFIG_NETWORK_LAYER_BLE */ diff --git a/src/ble/BtpEngine.h b/src/ble/BtpEngine.h index 0e1ed33789f513..6c40baf635e8d9 100644 --- a/src/ble/BtpEngine.h +++ b/src/ble/BtpEngine.h @@ -27,13 +27,14 @@ #pragma once -#include -#include +#ifndef _CHIP_BLE_BLE_H +#error "Please include instead!" +#endif -#include +#include +#include -#include -#include +#include #include namespace chip { diff --git a/src/ble/CHIPBleServiceData.h b/src/ble/CHIPBleServiceData.h index 6fbee69b7c268f..050cc76a43bca6 100644 --- a/src/ble/CHIPBleServiceData.h +++ b/src/ble/CHIPBleServiceData.h @@ -23,6 +23,12 @@ #pragma once +#ifndef _CHIP_BLE_BLE_H +#error "Please include instead!" +#endif + +#include + #include namespace chip { diff --git a/src/ble/tests/TestBleErrorStr.cpp b/src/ble/tests/TestBleErrorStr.cpp index 1dcb30e6e9878d..6868532823d950 100644 --- a/src/ble/tests/TestBleErrorStr.cpp +++ b/src/ble/tests/TestBleErrorStr.cpp @@ -28,9 +28,11 @@ #include #include -#include #include +#define _CHIP_BLE_BLE_H +#include + #include using namespace chip; diff --git a/src/ble/tests/TestBleUUID.cpp b/src/ble/tests/TestBleUUID.cpp index 70d95bc0336d63..40e425d623c9a4 100644 --- a/src/ble/tests/TestBleUUID.cpp +++ b/src/ble/tests/TestBleUUID.cpp @@ -24,6 +24,7 @@ * */ +#define _CHIP_BLE_BLE_H #include #include diff --git a/src/ble/tests/TestBtpEngine.cpp b/src/ble/tests/TestBtpEngine.cpp index 945c794bb01559..b799ff40e48f75 100644 --- a/src/ble/tests/TestBtpEngine.cpp +++ b/src/ble/tests/TestBtpEngine.cpp @@ -20,11 +20,13 @@ #include #include -#include -#include #include #include +#define _CHIP_BLE_BLE_H +#include +#include + #include using namespace chip; diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 98e3012a49959f..9103a0ba728156 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -61,7 +61,7 @@ #include #if CONFIG_NETWORK_LAYER_BLE -#include +#include #include #endif diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index b035334764b4a0..5290a26fdfbc47 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -72,7 +72,7 @@ #endif #if CONFIG_NETWORK_LAYER_BLE -#include +#include #endif #include diff --git a/src/controller/CHIPDeviceControllerFactory.cpp b/src/controller/CHIPDeviceControllerFactory.cpp index e4e419978d8a2d..248e96cf237f3a 100644 --- a/src/controller/CHIPDeviceControllerFactory.cpp +++ b/src/controller/CHIPDeviceControllerFactory.cpp @@ -73,41 +73,36 @@ CHIP_ERROR DeviceControllerFactory::Init(FactoryInitParams params) return err; } -CHIP_ERROR DeviceControllerFactory::InitSystemState() +CHIP_ERROR DeviceControllerFactory::ReinitSystemStateIfNecessary() { + VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mSystemState->IsShutdown(), CHIP_NO_ERROR); + FactoryInitParams params; - if (mSystemState != nullptr) - { - params.systemLayer = mSystemState->SystemLayer(); - params.udpEndPointManager = mSystemState->UDPEndPointManager(); + params.systemLayer = mSystemState->SystemLayer(); + params.udpEndPointManager = mSystemState->UDPEndPointManager(); #if INET_CONFIG_ENABLE_TCP_ENDPOINT - params.tcpEndPointManager = mSystemState->TCPEndPointManager(); + params.tcpEndPointManager = mSystemState->TCPEndPointManager(); #endif #if CONFIG_NETWORK_LAYER_BLE - params.bleLayer = mSystemState->BleLayer(); + params.bleLayer = mSystemState->BleLayer(); #endif - params.listenPort = mListenPort; - params.fabricIndependentStorage = mFabricIndependentStorage; - params.enableServerInteractions = mEnableServerInteractions; - params.groupDataProvider = mSystemState->GetGroupDataProvider(); - params.sessionKeystore = mSystemState->GetSessionKeystore(); - params.fabricTable = mSystemState->Fabrics(); - params.operationalKeystore = mOperationalKeystore; - params.opCertStore = mOpCertStore; - params.certificateValidityPolicy = mCertificateValidityPolicy; - params.sessionResumptionStorage = mSessionResumptionStorage; - } + params.listenPort = mListenPort; + params.fabricIndependentStorage = mFabricIndependentStorage; + params.enableServerInteractions = mEnableServerInteractions; + params.groupDataProvider = mSystemState->GetGroupDataProvider(); + params.sessionKeystore = mSystemState->GetSessionKeystore(); + params.fabricTable = mSystemState->Fabrics(); + params.operationalKeystore = mOperationalKeystore; + params.opCertStore = mOpCertStore; + params.certificateValidityPolicy = mCertificateValidityPolicy; + params.sessionResumptionStorage = mSessionResumptionStorage; return InitSystemState(params); } CHIP_ERROR DeviceControllerFactory::InitSystemState(FactoryInitParams params) { - if (mSystemState != nullptr && mSystemState->IsInitialized()) - { - return CHIP_NO_ERROR; - } - if (mSystemState != nullptr) { Platform::Delete(mSystemState); @@ -331,10 +326,8 @@ void DeviceControllerFactory::ControllerInitialized(const DeviceController & con CHIP_ERROR DeviceControllerFactory::SetupController(SetupParams params, DeviceController & controller) { - VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(params.controllerVendorId != VendorId::Unspecified, CHIP_ERROR_INVALID_ARGUMENT); - - ReturnErrorOnFailure(InitSystemState()); + ReturnErrorOnFailure(ReinitSystemStateIfNecessary()); ControllerInitParams controllerParams; PopulateInitParams(controllerParams, params); @@ -351,10 +344,8 @@ CHIP_ERROR DeviceControllerFactory::SetupController(SetupParams params, DeviceCo CHIP_ERROR DeviceControllerFactory::SetupCommissioner(SetupParams params, DeviceCommissioner & commissioner) { - VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(params.controllerVendorId != VendorId::Unspecified, CHIP_ERROR_INVALID_ARGUMENT); - - ReturnErrorOnFailure(InitSystemState()); + ReturnErrorOnFailure(ReinitSystemStateIfNecessary()); CommissionerInitParams commissionerParams; @@ -397,6 +388,13 @@ bool DeviceControllerFactory::ReleaseSystemState() return mSystemState->Release(); } +CHIP_ERROR DeviceControllerFactory::EnsureAndRetainSystemState() +{ + ReturnErrorOnFailure(ReinitSystemStateIfNecessary()); + RetainSystemState(); + return CHIP_NO_ERROR; +} + DeviceControllerFactory::~DeviceControllerFactory() { Shutdown(); diff --git a/src/controller/CHIPDeviceControllerFactory.h b/src/controller/CHIPDeviceControllerFactory.h index 19b19e54eab414..d4e50e9c44b57a 100644 --- a/src/controller/CHIPDeviceControllerFactory.h +++ b/src/controller/CHIPDeviceControllerFactory.h @@ -209,6 +209,9 @@ class DeviceControllerFactory // bool ReleaseSystemState(); + // Like RetainSystemState(), but will re-initialize the system state first if necessary. + CHIP_ERROR EnsureAndRetainSystemState(); + // // Retrieve a read-only pointer to the system state object that contains pointers to key stack // singletons. If the pointer is null, it indicates that the DeviceControllerFactory has yet to @@ -272,7 +275,7 @@ class DeviceControllerFactory DeviceControllerFactory() {} void PopulateInitParams(ControllerInitParams & controllerParams, const SetupParams & params); CHIP_ERROR InitSystemState(FactoryInitParams params); - CHIP_ERROR InitSystemState(); + CHIP_ERROR ReinitSystemStateIfNecessary(); void ControllerInitialized(const DeviceController & controller); uint16_t mListenPort; diff --git a/src/controller/CHIPDeviceControllerSystemState.h b/src/controller/CHIPDeviceControllerSystemState.h index 707f1befacec94..8a3be25e591ae0 100644 --- a/src/controller/CHIPDeviceControllerSystemState.h +++ b/src/controller/CHIPDeviceControllerSystemState.h @@ -49,7 +49,7 @@ #endif #if CONFIG_NETWORK_LAYER_BLE -#include +#include #include #endif diff --git a/src/controller/SetUpCodePairer.h b/src/controller/SetUpCodePairer.h index f9dc542f4258a0..e177af7322d391 100644 --- a/src/controller/SetUpCodePairer.h +++ b/src/controller/SetUpCodePairer.h @@ -36,7 +36,7 @@ #include #if CONFIG_NETWORK_LAYER_BLE -#include +#include #endif // CONFIG_NETWORK_BLE #include diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index b62ece066013ca..83c0d029d8ddb7 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -37,7 +37,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/controller/python/chip/ble/LinuxImpl.cpp b/src/controller/python/chip/ble/LinuxImpl.cpp index c61431bd8f9ecd..4e03d41e14949c 100644 --- a/src/controller/python/chip/ble/LinuxImpl.cpp +++ b/src/controller/python/chip/ble/LinuxImpl.cpp @@ -19,7 +19,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/controller/python/chip/ble/darwin/Scanning.mm b/src/controller/python/chip/ble/darwin/Scanning.mm index d3fb928790ab3e..292978b424a787 100644 --- a/src/controller/python/chip/ble/darwin/Scanning.mm +++ b/src/controller/python/chip/ble/darwin/Scanning.mm @@ -1,5 +1,4 @@ -#include -#include +#include #include #include #include diff --git a/src/credentials/FabricTable.h b/src/credentials/FabricTable.h index c61b6176fecb1e..55c1f6965e8c32 100644 --- a/src/credentials/FabricTable.h +++ b/src/credentials/FabricTable.h @@ -298,7 +298,7 @@ class ConstFabricIterator return GetCurrent(); } - bool operator==(const ConstFabricIterator & other) + bool operator==(const ConstFabricIterator & other) const { if (IsAtEnd()) { @@ -308,7 +308,7 @@ class ConstFabricIterator // Pending entry does not participate in finding this. return (mStart == other.mStart) && (mIndex == other.mIndex) && (mMaxSize == other.mMaxSize); } - bool operator!=(const ConstFabricIterator & other) { return !(*this == other); } + bool operator!=(const ConstFabricIterator & other) const { return !(*this == other); } bool IsAtEnd() const { return (mIndex == mMaxSize); } diff --git a/src/credentials/GroupDataProvider.h b/src/credentials/GroupDataProvider.h index 71e55e0e550cd3..6f791b671aadcd 100644 --- a/src/credentials/GroupDataProvider.h +++ b/src/credentials/GroupDataProvider.h @@ -16,7 +16,7 @@ */ #pragma once -#include +#include #include #include @@ -72,7 +72,7 @@ class GroupDataProvider Platform::CopyString(name, groupName); } } - bool operator==(const GroupInfo & other) + bool operator==(const GroupInfo & other) const { return (this->group_id == other.group_id) && !strncmp(this->name, other.name, kGroupNameMax); } @@ -151,7 +151,7 @@ class GroupDataProvider // Number of keys present uint8_t num_keys_used = 0; - bool operator==(const KeySet & other) + bool operator==(const KeySet & other) const { VerifyOrReturnError(this->policy == other.policy && this->num_keys_used == other.num_keys_used, false); return !memcmp(this->epoch_keys, other.epoch_keys, this->num_keys_used * sizeof(EpochKey)); @@ -253,7 +253,7 @@ class GroupDataProvider * @retval An instance of EndpointIterator on success * @retval nullptr if no iterator instances are available. */ - virtual EndpointIterator * IterateEndpoints(FabricIndex fabric_index, Optional group_id = NullOptional) = 0; + virtual EndpointIterator * IterateEndpoints(FabricIndex fabric_index, std::optional group_id = std::nullopt) = 0; // // Group-Key map diff --git a/src/credentials/GroupDataProviderImpl.cpp b/src/credentials/GroupDataProviderImpl.cpp index 90016d7d2f1085..22a935fdb70494 100644 --- a/src/credentials/GroupDataProviderImpl.cpp +++ b/src/credentials/GroupDataProviderImpl.cpp @@ -1208,27 +1208,27 @@ void GroupDataProviderImpl::GroupInfoIteratorImpl::Release() } GroupDataProvider::EndpointIterator * GroupDataProviderImpl::IterateEndpoints(chip::FabricIndex fabric_index, - Optional group_id) + std::optional group_id) { VerifyOrReturnError(IsInitialized(), nullptr); return mEndpointIterators.CreateObject(*this, fabric_index, group_id); } GroupDataProviderImpl::EndpointIteratorImpl::EndpointIteratorImpl(GroupDataProviderImpl & provider, chip::FabricIndex fabric_index, - Optional group_id) : + std::optional group_id) : mProvider(provider), mFabric(fabric_index) { FabricData fabric(fabric_index); VerifyOrReturn(CHIP_NO_ERROR == fabric.Load(provider.mStorage)); - if (group_id.HasValue()) + if (group_id.has_value()) { - GroupData group(fabric_index, group_id.Value()); + GroupData group(fabric_index, *group_id); VerifyOrReturn(CHIP_NO_ERROR == group.Load(provider.mStorage)); - mGroup = group_id.Value(); - mFirstGroup = group_id.Value(); + mGroup = *group_id; + mFirstGroup = *group_id; mGroupCount = 1; mEndpoint = group.first_endpoint; mEndpointCount = group.endpoint_count; diff --git a/src/credentials/GroupDataProviderImpl.h b/src/credentials/GroupDataProviderImpl.h index c06165b59ea6a3..af2c46ddb1d3a1 100644 --- a/src/credentials/GroupDataProviderImpl.h +++ b/src/credentials/GroupDataProviderImpl.h @@ -68,7 +68,7 @@ class GroupDataProviderImpl : public GroupDataProvider CHIP_ERROR RemoveEndpoint(FabricIndex fabric_index, EndpointId endpoint_id) override; // Iterators GroupInfoIterator * IterateGroupInfo(FabricIndex fabric_index) override; - EndpointIterator * IterateEndpoints(FabricIndex fabric_index, Optional group_id = NullOptional) override; + EndpointIterator * IterateEndpoints(FabricIndex fabric_index, std::optional group_id = std::nullopt) override; // // Group-Key map @@ -133,7 +133,7 @@ class GroupDataProviderImpl : public GroupDataProvider class EndpointIteratorImpl : public EndpointIterator { public: - EndpointIteratorImpl(GroupDataProviderImpl & provider, FabricIndex fabric_index, Optional group_id); + EndpointIteratorImpl(GroupDataProviderImpl & provider, FabricIndex fabric_index, std::optional group_id); size_t Count() override; bool Next(GroupEndpoint & output) override; void Release() override; diff --git a/src/darwin/Framework/CHIP/MTRBaseDevice.mm b/src/darwin/Framework/CHIP/MTRBaseDevice.mm index 45113db6a18d25..356e607ad86d4b 100644 --- a/src/darwin/Framework/CHIP/MTRBaseDevice.mm +++ b/src/darwin/Framework/CHIP/MTRBaseDevice.mm @@ -1840,11 +1840,7 @@ static CHIP_ERROR OpenCommissioningWindow(Controller::DeviceController * control CHIP_ERROR OpenCommissioningWindowHelper::OpenCommissioningWindow(Controller::DeviceController * controller, NodeId nodeID, System::Clock::Seconds16 timeout, uint16_t discriminator, const Optional & setupPIN, ResultCallback callback) { - auto * self = new (std::nothrow) OpenCommissioningWindowHelper(controller, callback); - if (self == nullptr) { - return CHIP_ERROR_NO_MEMORY; - } - + auto * self = new OpenCommissioningWindowHelper(controller, callback); SetupPayload unused; CHIP_ERROR err = self->mOpener.OpenCommissioningWindow(nodeID, timeout, Crypto::kSpake2p_Min_PBKDF_Iterations, discriminator, setupPIN, NullOptional, &self->mOnOpenCommissioningWindowCallback, unused); diff --git a/src/darwin/Framework/CHIP/MTRDevice.mm b/src/darwin/Framework/CHIP/MTRDevice.mm index 5226759ebf4b51..374b2e8cc60bc0 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.mm +++ b/src/darwin/Framework/CHIP/MTRDevice.mm @@ -28,6 +28,7 @@ #import "MTRCommandTimedCheck.h" #import "MTRConversion.h" #import "MTRDefines_Internal.h" +#import "MTRDeviceConnectivityMonitor.h" #import "MTRDeviceControllerOverXPC.h" #import "MTRDeviceController_Internal.h" #import "MTRDevice_Internal.h" @@ -355,6 +356,7 @@ @implementation MTRDevice { // _setupSubscription or via the auto-resubscribe behavior of the // ReadClient). Nil if we have had no such failures. NSDate * _Nullable _lastSubscriptionFailureTime; + MTRDeviceConnectivityMonitor * _connectivityMonitor; } - (instancetype)initWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller @@ -669,6 +671,8 @@ - (void)invalidate // subscription. In that case, _internalDeviceState will update when the // subscription is actually terminated. + [self _stopConnectivityMonitoring]; + os_unfair_lock_unlock(&self->_lock); } @@ -861,6 +865,9 @@ - (void)_handleSubscriptionEstablished [self _changeState:MTRDeviceStateReachable]; + // No need to monitor connectivity after subscription establishment + [self _stopConnectivityMonitoring]; + os_unfair_lock_unlock(&self->_lock); os_unfair_lock_lock(&self->_timeSyncLock); @@ -894,6 +901,9 @@ - (void)_handleResubscriptionNeeded // former case we recently had a subscription and do not want to be forcing // retries immediately. _lastSubscriptionFailureTime = [NSDate now]; + + // Set up connectivity monitoring in case network routability changes for the positive, to accellerate resubscription + [self _setupConnectivityMonitoring]; } - (void)_handleSubscriptionReset:(NSNumber * _Nullable)retryDelay @@ -1030,9 +1040,7 @@ - (void)_handleReportBegin for (MTRClusterPath * clusterPath in clusterPaths) { NSNumber * dataVersion = _clusterData[clusterPath].dataVersion; NSDictionary * attributes = nil; -#if MTRDEVICE_ATTRIBUTE_CACHE_STORE_ATTRIBUTES_BY_CLUSTER attributes = [self _attributesForCluster:clusterPath]; -#endif if (dataVersion || attributes) { MTRDeviceClusterData * clusterData = [[MTRDeviceClusterData alloc] initWithDataVersion:dataVersion attributes:attributes]; clusterDataToReturn[clusterPath] = clusterData; @@ -1241,6 +1249,44 @@ - (void)_createDataVersionFilterListFromDictionary:(NSDictionary_deviceController syncGetCompressedFabricID]; + if (!compressedFabricID) { + MTR_LOG_INFO("%@ could not get compressed fabricID", self); + return; + } + + // Now lock for _connectivityMonitor + std::lock_guard lock(self->_lock); + if (self->_connectivityMonitor) { + // already monitoring + return; + } + + self->_connectivityMonitor = [[MTRDeviceConnectivityMonitor alloc] initWithCompressedFabricID:compressedFabricID nodeID:self.nodeID]; + [self->_connectivityMonitor startMonitoringWithHandler:^{ + [self->_deviceController asyncDispatchToMatterQueue:^{ + [self _triggerResubscribeWithReason:"read-through skipped while not subscribed" nodeLikelyReachable:YES]; + } + errorHandler:nil]; + } queue:self.queue]; + }); +} + +- (void)_stopConnectivityMonitoring +{ + os_unfair_lock_assert_owner(&_lock); + + if (_connectivityMonitor) { + [_connectivityMonitor stopMonitoring]; + _connectivityMonitor = nil; + } +} + // assume lock is held - (void)_setupSubscription { @@ -1462,6 +1508,9 @@ - (void)_setupSubscription callback->AdoptClusterStateCache(std::move(clusterStateCache)); callback.release(); }]; + + // Set up connectivity monitoring in case network becomes routable after any part of the subscription process goes into backoff retries. + [self _setupConnectivityMonitoring]; } #ifdef DEBUG @@ -2289,12 +2338,6 @@ - (NSArray *)_getAttributesToReportWithReportedValues:(NSArray * attributeResponseValue in reportedAttributeValues) { MTRAttributePath * attributePath = attributeResponseValue[MTRAttributePathKey]; NSDictionary * attributeDataValue = attributeResponseValue[MTRDataKey]; @@ -2337,20 +2380,7 @@ - (NSArray *)_getAttributesToReportWithReportedValues:(NSArray * std::lock_guard lock(_lock); -#if MTRDEVICE_ATTRIBUTE_CACHE_STORE_ATTRIBUTES_BY_CLUSTER // For each cluster, extract and create the attribute response-value for the read cache // TODO: consider some optimization in how the read cache is structured so there's fewer conversions from this format to what's in the cache for (MTRClusterPath * clusterPath in clusterData) { @@ -2497,7 +2520,6 @@ - (void)setClusterData:(NSDictionary * } } } -#endif [_clusterData addEntriesFromDictionary:clusterData]; } diff --git a/src/darwin/Framework/CHIP/MTRDeviceConnectivityMonitor.h b/src/darwin/Framework/CHIP/MTRDeviceConnectivityMonitor.h new file mode 100644 index 00000000000000..ee07aae159ef29 --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRDeviceConnectivityMonitor.h @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2023 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "MTRDefines_Internal.h" + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^MTRDeviceConnectivityMonitorHandler)(void); + +/** + * Class that a matter dns-sd instance name, and monitors connectivity to the device. + */ +MTR_TESTABLE +@interface MTRDeviceConnectivityMonitor : NSObject +- (instancetype)initWithCompressedFabricID:(NSNumber *)compressedFabricID nodeID:(NSNumber *)nodeID; + +/** + * Any time a path becomes satisfied or route becomes viable, the registered handler will be called. + */ +- (void)startMonitoringWithHandler:(MTRDeviceConnectivityMonitorHandler)handler queue:(dispatch_queue_t)queue; + +/** + * Stops the monitoring. After this method returns no more calls to the handler will be made. + */ +- (void)stopMonitoring; +@end + +NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRDeviceConnectivityMonitor.mm b/src/darwin/Framework/CHIP/MTRDeviceConnectivityMonitor.mm new file mode 100644 index 00000000000000..38c73b63a899d3 --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRDeviceConnectivityMonitor.mm @@ -0,0 +1,257 @@ +/** + * Copyright (c) 2023 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "MTRDeviceConnectivityMonitor.h" +#import "MTRLogging_Internal.h" +#import "MTRUnfairLock.h" + +#import +#import +#import + +#include + +@implementation MTRDeviceConnectivityMonitor { + NSString * _instanceName; + DNSServiceRef _resolver; + NSMutableDictionary * _connections; + + MTRDeviceConnectivityMonitorHandler _monitorHandler; + dispatch_queue_t _handlerQueue; +} + +namespace { +constexpr char kLocalDot[] = "local."; +constexpr char kOperationalType[] = "_matter._tcp"; +constexpr int64_t kSharedConnectionLingerIntervalSeconds = (10); +} + +static os_unfair_lock sConnectivityMonitorLock = OS_UNFAIR_LOCK_INIT; +static NSUInteger sConnectivityMonitorCount; +static DNSServiceRef sSharedResolverConnection; +static dispatch_queue_t sSharedResolverQueue; + +- (instancetype)initWithInstanceName:(NSString *)instanceName +{ + if (self = [super init]) { + _instanceName = [instanceName copy]; + _connections = [NSMutableDictionary dictionary]; + } + return self; +} + +- (instancetype)initWithCompressedFabricID:(NSNumber *)compressedFabricID nodeID:(NSNumber *)nodeID +{ + char instanceName[chip::Dnssd::kMaxOperationalServiceNameSize]; + chip::PeerId peerId(static_cast(compressedFabricID.unsignedLongLongValue), static_cast(nodeID.unsignedLongLongValue)); + CHIP_ERROR err = chip::Dnssd::MakeInstanceName(instanceName, sizeof(instanceName), peerId); + if (err != CHIP_NO_ERROR) { + MTR_LOG_ERROR("%@ could not make instance name", self); + return nil; + } + + return [self initWithInstanceName:[NSString stringWithUTF8String:instanceName]]; +} + +- (void)dealloc +{ + if (_resolver) { + DNSServiceRefDeallocate(_resolver); + } +} + +- (NSString *)description +{ + return [NSString stringWithFormat:@"", _instanceName]; +} + ++ (DNSServiceRef)_sharedResolverConnection +{ + os_unfair_lock_assert_owner(&sConnectivityMonitorLock); + + if (!sSharedResolverConnection) { + DNSServiceErrorType dnsError = DNSServiceCreateConnection(&sSharedResolverConnection); + if (dnsError != kDNSServiceErr_NoError) { + MTR_LOG_ERROR("MTRDeviceConnectivityMonitor: DNSServiceCreateConnection failed %d", dnsError); + return NULL; + } + sSharedResolverQueue = dispatch_queue_create("MTRDeviceConnectivityMonitor", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); + dnsError = DNSServiceSetDispatchQueue(sSharedResolverConnection, sSharedResolverQueue); + if (dnsError != kDNSServiceErr_NoError) { + MTR_LOG_ERROR("%@ cannot set dispatch queue on resolve", self); + DNSServiceRefDeallocate(sSharedResolverConnection); + sSharedResolverConnection = NULL; + sSharedResolverQueue = nil; + return NULL; + } + } + + return sSharedResolverConnection; +} + +- (void)_callHandler +{ + os_unfair_lock_assert_owner(&sConnectivityMonitorLock); + MTRDeviceConnectivityMonitorHandler handlerToCall = self->_monitorHandler; + if (handlerToCall) { + dispatch_async(self->_handlerQueue, handlerToCall); + } +} + +- (void)handleResolvedHostname:(const char *)hostName port:(uint16_t)port error:(DNSServiceErrorType)error +{ + std::lock_guard lock(sConnectivityMonitorLock); + + // dns_sd.h: must check and call deallocate if error is kDNSServiceErr_ServiceNotRunning + if (error == kDNSServiceErr_ServiceNotRunning) { + MTR_LOG_ERROR("%@ disconnected from dns-sd subsystem", self); + [self _stopMonitoring]; + return; + } + + // Create a nw_connection to monitor connectivity if the host name is not being monitored yet + NSString * hostNameString = [NSString stringWithUTF8String:hostName]; + if (!_connections[hostNameString]) { + char portString[6]; + snprintf(portString, sizeof(portString), "%d", ntohs(port)); + nw_endpoint_t endpoint = nw_endpoint_create_host(hostName, portString); + if (!endpoint) { + MTR_LOG_ERROR("%@ failed to create endpoint for %s:%s", self, hostName, portString); + return; + } + nw_parameters_t params = nw_parameters_create_secure_udp(NW_PARAMETERS_DISABLE_PROTOCOL, NW_PARAMETERS_DEFAULT_CONFIGURATION); + if (!params) { + MTR_LOG_ERROR("%@ failed to create udp parameters", self); + return; + } + nw_connection_t connection = nw_connection_create(endpoint, params); + if (!connection) { + MTR_LOG_ERROR("%@ failed to create connection for %s:%s", self, hostName, portString); + return; + } + nw_connection_set_queue(connection, sSharedResolverQueue); + nw_connection_set_path_changed_handler(connection, ^(nw_path_t _Nonnull path) { + nw_path_status_t status = nw_path_get_status(path); + if (status == nw_path_status_satisfied) { + MTR_LOG_INFO("%@ path is satisfied", self); + std::lock_guard lock(sConnectivityMonitorLock); + [self _callHandler]; + } + }); + nw_connection_set_viability_changed_handler(connection, ^(bool viable) { + if (viable) { + std::lock_guard lock(sConnectivityMonitorLock); + MTR_LOG_INFO("%@ connectivity now viable", self); + [self _callHandler]; + } + }); + nw_connection_start(connection); + + _connections[hostNameString] = connection; + } +} + +static void ResolveCallback( + DNSServiceRef sdRef, + DNSServiceFlags flags, + uint32_t interfaceIndex, + DNSServiceErrorType errorCode, + const char * fullName, + const char * hostName, + uint16_t port, /* In network byte order */ + uint16_t txtLen, + const unsigned char * txtRecord, + void * context) +{ + auto * connectivityMonitor = (__bridge MTRDeviceConnectivityMonitor *) context; + [connectivityMonitor handleResolvedHostname:hostName port:port error:errorCode]; +} + +- (void)startMonitoringWithHandler:(MTRDeviceConnectivityMonitorHandler)handler queue:(dispatch_queue_t)queue +{ + std::lock_guard lock(sConnectivityMonitorLock); + + _monitorHandler = handler; + _handlerQueue = queue; + + // If there's already a resolver running, just return + if (_resolver) { + MTR_LOG_INFO("%@ connectivity monitor already running", self); + return; + } + + MTR_LOG_INFO("%@ start connectivity monitoring for %@ (%lu monitoring objects)", self, _instanceName, static_cast(sConnectivityMonitorCount)); + + _resolver = [MTRDeviceConnectivityMonitor _sharedResolverConnection]; + if (!_resolver) { + MTR_LOG_ERROR("%@ failed to get shared resolver connection", self); + return; + } + DNSServiceErrorType dnsError = DNSServiceResolve(&_resolver, + kDNSServiceFlagsShareConnection, + kDNSServiceInterfaceIndexAny, + _instanceName.UTF8String, + kOperationalType, + kLocalDot, + ResolveCallback, + (__bridge void *) self); + if (dnsError != kDNSServiceErr_NoError) { + MTR_LOG_ERROR("%@ failed to create resolver", self); + return; + } + + sConnectivityMonitorCount++; +} + +- (void)_stopMonitoring +{ + os_unfair_lock_assert_owner(&sConnectivityMonitorLock); + for (NSString * hostName in _connections) { + nw_connection_cancel(_connections[hostName]); + } + [_connections removeAllObjects]; + + _monitorHandler = nil; + _handlerQueue = nil; + + if (_resolver) { + DNSServiceRefDeallocate(_resolver); + _resolver = NULL; + + // If no monitor objects exist, schedule to deallocate shared connection and queue + sConnectivityMonitorCount--; + if (!sConnectivityMonitorCount) { + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kSharedConnectionLingerIntervalSeconds * NSEC_PER_SEC), sSharedResolverQueue, ^{ + std::lock_guard lock(sConnectivityMonitorLock); + + if (!sConnectivityMonitorCount) { + MTR_LOG_INFO("MTRDeviceConnectivityMonitor: Closing shared resolver connection"); + DNSServiceRefDeallocate(sSharedResolverConnection); + sSharedResolverConnection = NULL; + sSharedResolverQueue = nil; + } + }); + } + } +} + +- (void)stopMonitoring +{ + MTR_LOG_INFO("%@ stop connectivity monitoring for %@", self, _instanceName); + std::lock_guard lock(sConnectivityMonitorLock); + [self _stopMonitoring]; +} +@end diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index 87490eecf6e7a6..4dfa229e71cc85 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -413,10 +413,6 @@ - (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams } _cppCommissioner = new chip::Controller::DeviceCommissioner(); - if (_cppCommissioner == nullptr) { - [self checkForStartError:CHIP_ERROR_NO_MEMORY logMsg:kErrorCommissionerInit]; - return; - } // nocBuffer might not be used, but if it is it needs to live // long enough (until after we are done using @@ -952,14 +948,6 @@ - (MTRDevice *)_setupDeviceForNodeID:(NSNumber *)nodeID prefetchedClusterData:(N [deviceToReturn setClusterData:prefetchedClusterData]; } } else { -#if !MTRDEVICE_ATTRIBUTE_CACHE_STORE_ATTRIBUTES_BY_CLUSTER - // Load persisted attributes if they exist. - NSArray * attributesFromCache = [_controllerDataStore getStoredAttributesForNodeID:nodeID]; - MTR_LOG_INFO("Loaded %lu attributes from storage for %@", static_cast(attributesFromCache.count), deviceToReturn); - if (attributesFromCache.count) { - [deviceToReturn setAttributeValues:attributesFromCache reportChanges:NO]; - } -#endif // Load persisted cluster data if they exist. NSDictionary * clusterData = [_controllerDataStore getStoredClusterDataForNodeID:nodeID]; MTR_LOG_INFO("Loaded %lu cluster data from storage for %@", static_cast(clusterData.count), deviceToReturn); @@ -1372,6 +1360,13 @@ - (nullable NSNumber *)compressedFabricID return @(_cppCommissioner->GetCompressedFabricId()); } +- (NSNumber * _Nullable)syncGetCompressedFabricID +{ + return [self syncRunOnWorkQueueWithReturnValue:^NSNumber * { + return [self compressedFabricID]; + } error:nil]; +} + - (CHIP_ERROR)isRunningOnFabric:(chip::FabricTable *)fabricTable fabricIndex:(chip::FabricIndex)fabricIndex isRunning:(BOOL *)isRunning diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerDataStore.h b/src/darwin/Framework/CHIP/MTRDeviceControllerDataStore.h index bc3b8f37f90fbb..91a6c0e3142a38 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerDataStore.h +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerDataStore.h @@ -72,12 +72,10 @@ typedef void (^MTRDeviceControllerDataStoreClusterDataHandler)(NSDictionary *)getStoredAttributesForNodeID:(NSNumber *)nodeID; -- (void)storeAttributeValues:(NSArray *)dataValues forNodeID:(NSNumber *)nodeID; - (nullable NSDictionary *)getStoredClusterDataForNodeID:(NSNumber *)nodeID; - (void)storeClusterData:(NSDictionary *)clusterData forNodeID:(NSNumber *)nodeID; -- (void)clearStoredAttributesForNodeID:(NSNumber *)nodeID; -- (void)clearAllStoredAttributes; +- (void)clearStoredClusterDataForNodeID:(NSNumber *)nodeID; +- (void)clearAllStoredClusterData; @end diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerDataStore.mm b/src/darwin/Framework/CHIP/MTRDeviceControllerDataStore.mm index d6c7e8c00dfeb1..cac425c9453ad3 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerDataStore.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerDataStore.mm @@ -306,20 +306,14 @@ - (nullable MTRCASESessionResumptionInfo *)_findResumptionInfoWithKey:(nullable * key: "attrCacheNodeIndex" * value: list of nodeIDs * EndpointID index - * key: "attrCacheEndpointIndex::endpointID" + * key: "attrCacheEndpointIndex:" * value: list of endpoint IDs * ClusterID index - * key: " clusters" + * key: "attrCacheClusterIndex::" * value: list of cluster IDs - * AttributeID index - * key: " attributes" - * value: list of attribute IDs - * Attribute data entry: - * key: " attribute data" - * value: serialized dictionary of attribute data - * - * Attribute data dictionary - * Additional value "serial number" + * Cluster data entry: + * key: "attrCacheClusterData:::" + * value: MTRDeviceClusterData */ - (id)_fetchAttributeCacheValueForKey:(NSString *)key expectedClass:(Class)expectedClass; @@ -371,16 +365,19 @@ - (BOOL)_removeAttributeCacheValueForKey:(NSString *)key - (nullable NSArray *)_fetchNodeIndex { + dispatch_assert_queue(_storageDelegateQueue); return [self _fetchAttributeCacheValueForKey:sAttributeCacheNodeIndexKey expectedClass:[NSArray class]]; } - (BOOL)_storeNodeIndex:(NSArray *)nodeIndex { + dispatch_assert_queue(_storageDelegateQueue); return [self _storeAttributeCacheValue:nodeIndex forKey:sAttributeCacheNodeIndexKey]; } - (BOOL)_deleteNodeIndex { + dispatch_assert_queue(_storageDelegateQueue); return [self _removeAttributeCacheValueForKey:sAttributeCacheNodeIndexKey]; } @@ -393,6 +390,8 @@ - (NSString *)_endpointIndexKeyForNodeID:(NSNumber *)nodeID - (nullable NSArray *)_fetchEndpointIndexForNodeID:(NSNumber *)nodeID { + dispatch_assert_queue(_storageDelegateQueue); + if (!nodeID) { MTR_LOG_ERROR("%s: unexpected nil input", __func__); return nil; @@ -403,6 +402,8 @@ - (NSString *)_endpointIndexKeyForNodeID:(NSNumber *)nodeID - (BOOL)_storeEndpointIndex:(NSArray *)endpointIndex forNodeID:(NSNumber *)nodeID { + dispatch_assert_queue(_storageDelegateQueue); + if (!nodeID) { MTR_LOG_ERROR("%s: unexpected nil input", __func__); return NO; @@ -413,6 +414,8 @@ - (BOOL)_storeEndpointIndex:(NSArray *)endpointIndex forNodeID:(NSNu - (BOOL)_deleteEndpointIndexForNodeID:(NSNumber *)nodeID { + dispatch_assert_queue(_storageDelegateQueue); + if (!nodeID) { MTR_LOG_ERROR("%s: unexpected nil input", __func__); return NO; @@ -430,6 +433,8 @@ - (NSString *)_clusterIndexKeyForNodeID:(NSNumber *)nodeID endpointID:(NSNumber - (nullable NSArray *)_fetchClusterIndexForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID { + dispatch_assert_queue(_storageDelegateQueue); + if (!nodeID || !endpointID) { MTR_LOG_ERROR("%s: unexpected nil input", __func__); return nil; @@ -440,6 +445,8 @@ - (NSString *)_clusterIndexKeyForNodeID:(NSNumber *)nodeID endpointID:(NSNumber - (BOOL)_storeClusterIndex:(NSArray *)clusterIndex forNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID { + dispatch_assert_queue(_storageDelegateQueue); + if (!nodeID || !endpointID) { MTR_LOG_ERROR("%s: unexpected nil input", __func__); return NO; @@ -450,6 +457,8 @@ - (BOOL)_storeClusterIndex:(NSArray *)clusterIndex forNodeID:(NSNumb - (BOOL)_deleteClusterIndexForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID { + dispatch_assert_queue(_storageDelegateQueue); + if (!nodeID || !endpointID) { MTR_LOG_ERROR("%s: unexpected nil input", __func__); return NO; @@ -462,11 +471,13 @@ - (BOOL)_deleteClusterIndexForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)e - (NSString *)_clusterDataKeyForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID { - return [sAttributeCacheClusterDataKeyPrefix stringByAppendingFormat:@":0x%016llX:%0x04X:0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue]; + return [sAttributeCacheClusterDataKeyPrefix stringByAppendingFormat:@":0x%016llX:0x%04X:0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue]; } - (nullable MTRDeviceClusterData *)_fetchClusterDataForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID { + dispatch_assert_queue(_storageDelegateQueue); + if (!nodeID || !endpointID || !clusterID) { MTR_LOG_ERROR("%s: unexpected nil input", __func__); return nil; @@ -477,6 +488,8 @@ - (nullable MTRDeviceClusterData *)_fetchClusterDataForNodeID:(NSNumber *)nodeID - (BOOL)_storeClusterData:(MTRDeviceClusterData *)clusterData forNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID { + dispatch_assert_queue(_storageDelegateQueue); + if (!nodeID || !endpointID || !clusterID || !clusterData) { MTR_LOG_ERROR("%s: unexpected nil input", __func__); return NO; @@ -487,6 +500,8 @@ - (BOOL)_storeClusterData:(MTRDeviceClusterData *)clusterData forNodeID:(NSNumbe - (BOOL)_deleteClusterDataForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID { + dispatch_assert_queue(_storageDelegateQueue); + if (!nodeID || !endpointID || !clusterID) { MTR_LOG_ERROR("%s: unexpected nil input", __func__); return NO; @@ -495,139 +510,22 @@ - (BOOL)_deleteClusterDataForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)en return [self _removeAttributeCacheValueForKey:[self _clusterDataKeyForNodeID:nodeID endpointID:endpointID clusterID:clusterID]]; } -static NSString * sAttributeCacheAttributeIndexKeyPrefix = @"attrCacheAttributeIndex"; - -- (NSString *)_attributeIndexKeyForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID -{ - return [sAttributeCacheAttributeIndexKeyPrefix stringByAppendingFormat:@":0x%016llX:0x%04X:0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue]; -} - -- (nullable NSArray *)_fetchAttributeIndexForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID -{ - return [self _fetchAttributeCacheValueForKey:[self _attributeIndexKeyForNodeID:nodeID endpointID:endpointID clusterID:clusterID] expectedClass:[NSArray class]]; -} - -- (BOOL)_storeAttributeIndex:(NSArray *)attributeIndex forNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID -{ - return [self _storeAttributeCacheValue:attributeIndex forKey:[self _attributeIndexKeyForNodeID:nodeID endpointID:endpointID clusterID:clusterID]]; -} - -- (BOOL)_deleteAttributeIndexForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID -{ - return [self _removeAttributeCacheValueForKey:[self _attributeIndexKeyForNodeID:nodeID endpointID:endpointID clusterID:clusterID]]; -} - -static NSString * sAttributeCacheAttributeValueKeyPrefix = @"attrCacheAttributeValue"; - -- (NSString *)_attributeValueKeyForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID attributeID:(NSNumber *)attributeID -{ - return [sAttributeCacheAttributeValueKeyPrefix stringByAppendingFormat:@":0x%016llX:0x%04X:0x%08lX:0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue, attributeID.unsignedLongValue]; -} - -- (nullable NSDictionary *)_fetchAttributeValueForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID attributeID:(NSNumber *)attributeID -{ - return [self _fetchAttributeCacheValueForKey:[self _attributeValueKeyForNodeID:nodeID endpointID:endpointID clusterID:clusterID attributeID:attributeID] expectedClass:[NSDictionary class]]; -} - -- (BOOL)_storeAttributeValue:(NSDictionary *)value forNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID attributeID:(NSNumber *)attributeID -{ - return [self _storeAttributeCacheValue:value forKey:[self _attributeValueKeyForNodeID:nodeID endpointID:endpointID clusterID:clusterID attributeID:attributeID]]; -} - -- (BOOL)_deleteAttributeValueForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID attributeID:(NSNumber *)attributeID -{ - return [self _removeAttributeCacheValueForKey:[self _attributeValueKeyForNodeID:nodeID endpointID:endpointID clusterID:clusterID attributeID:attributeID]]; -} - #pragma - Attribute Cache management #ifndef ATTRIBUTE_CACHE_VERBOSE_LOGGING #define ATTRIBUTE_CACHE_VERBOSE_LOGGING 0 #endif -- (nullable NSArray *)getStoredAttributesForNodeID:(NSNumber *)nodeID -{ - __block NSMutableArray * attributesToReturn = nil; - dispatch_sync(_storageDelegateQueue, ^{ - // Fetch node index - NSArray * nodeIndex = [self _fetchNodeIndex]; - -#if ATTRIBUTE_CACHE_VERBOSE_LOGGING - MTR_LOG_INFO("Fetch got %lu values for nodeIndex", static_cast(nodeIndex.count)); -#endif - - if (![nodeIndex containsObject:nodeID]) { - // Sanity check and delete if nodeID exists in index - NSArray * endpointIndex = [self _fetchEndpointIndexForNodeID:nodeID]; - if (endpointIndex) { - MTR_LOG_ERROR("Persistent attribute cache contains orphaned entry for nodeID %@ - deleting", nodeID); - [self clearStoredAttributesForNodeID:nodeID]; - } - - MTR_LOG_INFO("Fetch got no value for endpointIndex @ node 0x%016llX", nodeID.unsignedLongLongValue); - attributesToReturn = nil; - return; - } - - // Fetch endpoint index - NSArray * endpointIndex = [self _fetchEndpointIndexForNodeID:nodeID]; - -#if ATTRIBUTE_CACHE_VERBOSE_LOGGING - MTR_LOG_INFO("Fetch got %lu values for endpointIndex @ node 0x%016llX", static_cast(endpointIndex.count), nodeID.unsignedLongLongValue); -#endif - - for (NSNumber * endpointID in endpointIndex) { - // Fetch cluster index - NSArray * clusterIndex = [self _fetchClusterIndexForNodeID:nodeID endpointID:endpointID]; - -#if ATTRIBUTE_CACHE_VERBOSE_LOGGING - MTR_LOG_INFO("Fetch got %lu values for clusterIndex @ node 0x%016llX %u", static_cast(clusterIndex.count), nodeID.unsignedLongLongValue, endpointID.unsignedShortValue); -#endif - - for (NSNumber * clusterID in clusterIndex) { - // Fetch attribute index - NSArray * attributeIndex = [self _fetchAttributeIndexForNodeID:nodeID endpointID:endpointID clusterID:clusterID]; - -#if ATTRIBUTE_CACHE_VERBOSE_LOGGING - MTR_LOG_INFO("Fetch got %lu values for attributeIndex @ node 0x%016llX endpoint %u cluster 0x%08lX", static_cast(attributeIndex.count), nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue); -#endif - - for (NSNumber * attributeID in attributeIndex) { - NSDictionary * value = [self _fetchAttributeValueForNodeID:nodeID endpointID:endpointID clusterID:clusterID attributeID:attributeID]; - -#if ATTRIBUTE_CACHE_VERBOSE_LOGGING - MTR_LOG_INFO("Fetch got %u values for attribute value @ node 0x%016llX endpoint %u cluster 0x%08lX attribute 0x%08lX", value ? 1 : 0, nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue, attributeID.unsignedLongValue); -#endif - - if (value) { - if (!attributesToReturn) { - attributesToReturn = [NSMutableArray array]; - } - - // Construct data-value dictionary and add to array - MTRAttributePath * path = [MTRAttributePath attributePathWithEndpointID:endpointID clusterID:clusterID attributeID:attributeID]; - [attributesToReturn addObject:@ { MTRAttributePathKey : path, MTRDataKey : value }]; - } - } - - // TODO: Add per-cluster integrity check verification - } - } - }); - - return attributesToReturn; -} - #ifdef DEBUG -- (void)unitTestPruneEmptyStoredAttributesBranches +- (void)unitTestPruneEmptyStoredClusterDataBranches { dispatch_sync(_storageDelegateQueue, ^{ - [self _pruneEmptyStoredAttributesBranches]; + [self _pruneEmptyStoredClusterDataBranches]; }); } #endif -- (void)_pruneEmptyStoredAttributesBranches +- (void)_pruneEmptyStoredClusterDataBranches { dispatch_assert_queue(_storageDelegateQueue); @@ -648,36 +546,10 @@ - (void)_pruneEmptyStoredAttributesBranches NSMutableArray * clusterIndexCopy = [clusterIndex mutableCopy]; for (NSNumber * clusterID in clusterIndex) { - // Fetch attribute index - NSArray * attributeIndex = [self _fetchAttributeIndexForNodeID:nodeID endpointID:endpointID clusterID:clusterID]; - NSMutableArray * attributeIndexCopy = [attributeIndex mutableCopy]; - - for (NSNumber * attributeID in attributeIndex) { - NSDictionary * value = [self _fetchAttributeValueForNodeID:nodeID endpointID:endpointID clusterID:clusterID attributeID:attributeID]; - - if (!value) { - [attributeIndexCopy removeObject:attributeID]; - } - } - - if (attributeIndex.count != attributeIndexCopy.count) { - BOOL success; - BOOL clusterDataSuccess = YES; - if (attributeIndexCopy.count) { - success = [self _storeAttributeIndex:attributeIndexCopy forNodeID:nodeID endpointID:endpointID clusterID:clusterID]; - } else { - [clusterIndexCopy removeObject:clusterID]; - success = [self _deleteAttributeIndexForNodeID:nodeID endpointID:endpointID clusterID:clusterID]; - clusterDataSuccess = [self _deleteClusterDataForNodeID:nodeID endpointID:endpointID clusterID:clusterID]; - } - if (!success) { - storeFailures++; - MTR_LOG_INFO("Store failed in _pruneEmptyStoredAttributesBranches for attributeIndex (%lu) @ node 0x%016llX endpoint %u cluster 0x%08lX", static_cast(attributeIndexCopy.count), nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue); - } - if (!clusterDataSuccess) { - storeFailures++; - MTR_LOG_INFO("Store failed in _pruneEmptyStoredAttributesBranches for clusterData @ node 0x%016llX endpoint %u cluster 0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue); - } + // Fetch cluster data, if it exists. + MTRDeviceClusterData * clusterData = [self _fetchClusterDataForNodeID:nodeID endpointID:endpointID clusterID:clusterID]; + if (!clusterData) { + [clusterIndexCopy removeObject:clusterID]; } } @@ -691,7 +563,7 @@ - (void)_pruneEmptyStoredAttributesBranches } if (!success) { storeFailures++; - MTR_LOG_INFO("Store failed in _pruneEmptyStoredAttributesBranches for clusterIndex (%lu) @ node 0x%016llX endpoint %u", static_cast(clusterIndexCopy.count), nodeID.unsignedLongLongValue, endpointID.unsignedShortValue); + MTR_LOG_INFO("Store failed in _pruneEmptyStoredClusterDataBranches for clusterIndex (%lu) @ node 0x%016llX endpoint %u", static_cast(clusterIndexCopy.count), nodeID.unsignedLongLongValue, endpointID.unsignedShortValue); } } } @@ -706,7 +578,7 @@ - (void)_pruneEmptyStoredAttributesBranches } if (!success) { storeFailures++; - MTR_LOG_INFO("Store failed in _pruneEmptyStoredAttributesBranches for endpointIndex (%lu) @ node 0x%016llX", static_cast(endpointIndexCopy.count), nodeID.unsignedLongLongValue); + MTR_LOG_INFO("Store failed in _pruneEmptyStoredClusterDataBranches for endpointIndex (%lu) @ node 0x%016llX", static_cast(endpointIndexCopy.count), nodeID.unsignedLongLongValue); } } } @@ -720,114 +592,23 @@ - (void)_pruneEmptyStoredAttributesBranches } if (!success) { storeFailures++; - MTR_LOG_INFO("Store failed in _pruneEmptyStoredAttributesBranches for nodeIndex (%lu)", static_cast(nodeIndexCopy.count)); + MTR_LOG_INFO("Store failed in _pruneEmptyStoredClusterDataBranches for nodeIndex (%lu)", static_cast(nodeIndexCopy.count)); } } if (storeFailures) { - MTR_LOG_ERROR("Store failed in _pruneEmptyStoredAttributesBranches: failure count %lu", static_cast(storeFailures)); + MTR_LOG_ERROR("Store failed in _pruneEmptyStoredClusterDataBranches: failure count %lu", static_cast(storeFailures)); } } -- (void)storeAttributeValues:(NSArray *)dataValues forNodeID:(NSNumber *)nodeID +- (void)_clearStoredClusterDataForNodeID:(NSNumber *)nodeID { - dispatch_async(_storageDelegateQueue, ^{ - NSUInteger storeFailures = 0; - - for (NSDictionary * dataValue in dataValues) { - MTRAttributePath * path = dataValue[MTRAttributePathKey]; - NSDictionary * value = dataValue[MTRDataKey]; - -#if ATTRIBUTE_CACHE_VERBOSE_LOGGING - MTR_LOG_INFO("Attempt to store attribute value @ node 0x%016llX endpoint %u cluster 0x%08lX attribute 0x%08lX", nodeID.unsignedLongLongValue, path.endpoint.unsignedShortValue, path.cluster.unsignedLongValue, path.attribute.unsignedLongValue); -#endif - - BOOL storeFailed = NO; - // Ensure node index exists - NSArray * nodeIndex = [self _fetchNodeIndex]; - if (!nodeIndex) { - nodeIndex = [NSArray arrayWithObject:nodeID]; - storeFailed = ![self _storeNodeIndex:nodeIndex]; - } else if (![nodeIndex containsObject:nodeID]) { - storeFailed = ![self _storeNodeIndex:[nodeIndex arrayByAddingObject:nodeID]]; - } - if (storeFailed) { - storeFailures++; - MTR_LOG_INFO("Store failed for nodeIndex"); - continue; - } - - // Ensure endpoint index exists - NSArray * endpointIndex = [self _fetchEndpointIndexForNodeID:nodeID]; - if (!endpointIndex) { - endpointIndex = [NSArray arrayWithObject:path.endpoint]; - storeFailed = ![self _storeEndpointIndex:endpointIndex forNodeID:nodeID]; - } else if (![endpointIndex containsObject:path.endpoint]) { - storeFailed = ![self _storeEndpointIndex:[endpointIndex arrayByAddingObject:path.endpoint] forNodeID:nodeID]; - } - if (storeFailed) { - storeFailures++; - MTR_LOG_INFO("Store failed for endpointIndex @ node 0x%016llX", nodeID.unsignedLongLongValue); - continue; - } - - // Ensure cluster index exists - NSArray * clusterIndex = [self _fetchClusterIndexForNodeID:nodeID endpointID:path.endpoint]; - if (!clusterIndex) { - clusterIndex = [NSArray arrayWithObject:path.cluster]; - storeFailed = ![self _storeClusterIndex:clusterIndex forNodeID:nodeID endpointID:path.endpoint]; - } else if (![clusterIndex containsObject:path.cluster]) { - storeFailed = ![self _storeClusterIndex:[clusterIndex arrayByAddingObject:path.cluster] forNodeID:nodeID endpointID:path.endpoint]; - } - if (storeFailed) { - storeFailures++; - MTR_LOG_INFO("Store failed for clusterIndex @ node 0x%016llX endpoint %u", nodeID.unsignedLongLongValue, path.endpoint.unsignedShortValue); - continue; - } - - // TODO: Add per-cluster integrity check calculation and store with cluster - // TODO: Think about adding more integrity check for endpoint and node levels as well - - // Ensure attribute index exists - NSArray * attributeIndex = [self _fetchAttributeIndexForNodeID:nodeID endpointID:path.endpoint clusterID:path.cluster]; - if (!attributeIndex) { - attributeIndex = [NSArray arrayWithObject:path.attribute]; - storeFailed = ![self _storeAttributeIndex:attributeIndex forNodeID:nodeID endpointID:path.endpoint clusterID:path.cluster]; - } else if (![attributeIndex containsObject:path.attribute]) { - storeFailed = ![self _storeAttributeIndex:[attributeIndex arrayByAddingObject:path.attribute] forNodeID:nodeID endpointID:path.endpoint clusterID:path.cluster]; - } - if (storeFailed) { - storeFailures++; - MTR_LOG_INFO("Store failed for attributeIndex @ node 0x%016llX endpoint %u cluster 0x%08lX", nodeID.unsignedLongLongValue, path.endpoint.unsignedShortValue, path.cluster.unsignedLongValue); - continue; - } - - // Store value - storeFailed = ![self _storeAttributeValue:value forNodeID:nodeID endpointID:path.endpoint clusterID:path.cluster attributeID:path.attribute]; - if (storeFailed) { - storeFailures++; - MTR_LOG_INFO("Store failed for attribute value @ node 0x%016llX endpoint %u cluster 0x%08lX attribute 0x%08lX", nodeID.unsignedLongLongValue, path.endpoint.unsignedShortValue, path.cluster.unsignedLongValue, path.attribute.unsignedLongValue); - } - } - - // In the rare event that store fails, allow all attribute store attempts to go through and prune empty branches at the end altogether. - if (storeFailures) { - [self _pruneEmptyStoredAttributesBranches]; - MTR_LOG_ERROR("Store failed in -storeAttributeValues:forNodeID: failure count %lu", static_cast(storeFailures)); - } - }); -} + dispatch_assert_queue(_storageDelegateQueue); -- (void)_clearStoredAttributesForNodeID:(NSNumber *)nodeID -{ NSUInteger endpointsClearAttempts = 0; - NSUInteger clustersClearAttempts = 0; NSUInteger clusterDataClearAttempts = 0; - NSUInteger attributesClearAttempts = 0; NSUInteger endpointsCleared = 0; - NSUInteger clustersCleared = 0; NSUInteger clusterDataCleared = 0; - NSUInteger attributesCleared = 0; // Fetch endpoint index NSArray * endpointIndex = [self _fetchEndpointIndexForNodeID:nodeID]; @@ -837,30 +618,9 @@ - (void)_clearStoredAttributesForNodeID:(NSNumber *)nodeID // Fetch cluster index NSArray * clusterIndex = [self _fetchClusterIndexForNodeID:nodeID endpointID:endpointID]; - clustersClearAttempts += clusterIndex.count; clusterDataClearAttempts += clusterIndex.count; // Assuming every cluster has cluster data for (NSNumber * clusterID in clusterIndex) { - // Fetch attribute index - NSArray * attributeIndex = [self _fetchAttributeIndexForNodeID:nodeID endpointID:endpointID clusterID:clusterID]; - - attributesClearAttempts += attributeIndex.count; - for (NSNumber * attributeID in attributeIndex) { - BOOL success = [self _deleteAttributeValueForNodeID:nodeID endpointID:endpointID clusterID:clusterID attributeID:attributeID]; - if (!success) { - MTR_LOG_INFO("Delete failed for attribute value @ node 0x%016llX endpoint %u cluster 0x%08lX attribute 0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue, attributeID.unsignedLongValue); - } else { - attributesCleared++; - } - } - - BOOL success = [self _deleteAttributeIndexForNodeID:nodeID endpointID:endpointID clusterID:clusterID]; - if (!success) { - MTR_LOG_INFO("Delete failed for attributeIndex @ node 0x%016llX endpoint %u cluster 0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue); - } else { - clustersCleared++; - } - - success = [self _deleteClusterDataForNodeID:nodeID endpointID:endpointID clusterID:clusterID]; + BOOL success = [self _deleteClusterDataForNodeID:nodeID endpointID:endpointID clusterID:clusterID]; if (!success) { MTR_LOG_INFO("Delete failed for clusterData @ node 0x%016llX endpoint %u cluster 0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue); } else { @@ -878,16 +638,16 @@ - (void)_clearStoredAttributesForNodeID:(NSNumber *)nodeID BOOL success = [self _deleteEndpointIndexForNodeID:nodeID]; if (!success) { - MTR_LOG_INFO("Delete failed for endpointrIndex @ node 0x%016llX", nodeID.unsignedLongLongValue); + MTR_LOG_INFO("Delete failed for endpointIndex @ node 0x%016llX", nodeID.unsignedLongLongValue); } - MTR_LOG_INFO("clearStoredAttributesForNodeID: deleted endpoints %lu/%lu clusters %lu/%lu clusterData %lu/%lu attributes %lu/%lu", static_cast(endpointsCleared), static_cast(endpointsClearAttempts), static_cast(clustersCleared), static_cast(clustersClearAttempts), static_cast(clusterDataCleared), static_cast(clusterDataClearAttempts), static_cast(attributesCleared), static_cast(attributesClearAttempts)); + MTR_LOG_INFO("clearStoredClusterDataForNodeID: deleted endpoints %lu/%lu clusters %lu/%lu", static_cast(endpointsCleared), static_cast(endpointsClearAttempts), static_cast(clusterDataCleared), static_cast(clusterDataClearAttempts)); } -- (void)clearStoredAttributesForNodeID:(NSNumber *)nodeID +- (void)clearStoredClusterDataForNodeID:(NSNumber *)nodeID { dispatch_async(_storageDelegateQueue, ^{ - [self _clearStoredAttributesForNodeID:nodeID]; + [self _clearStoredClusterDataForNodeID:nodeID]; NSArray * nodeIndex = [self _fetchNodeIndex]; NSMutableArray * nodeIndexCopy = [nodeIndex mutableCopy]; [nodeIndexCopy removeObject:nodeID]; @@ -905,14 +665,14 @@ - (void)clearStoredAttributesForNodeID:(NSNumber *)nodeID }); } -- (void)clearAllStoredAttributes +- (void)clearAllStoredClusterData { dispatch_async(_storageDelegateQueue, ^{ // Fetch node index NSArray * nodeIndex = [self _fetchNodeIndex]; for (NSNumber * nodeID in nodeIndex) { - [self _clearStoredAttributesForNodeID:nodeID]; + [self _clearStoredClusterDataForNodeID:nodeID]; } BOOL success = [self _deleteNodeIndex]; @@ -943,7 +703,10 @@ - (void)clearAllStoredAttributes NSArray * endpointIndex = [self _fetchEndpointIndexForNodeID:nodeID]; if (endpointIndex) { MTR_LOG_ERROR("Persistent attribute cache contains orphaned entry for nodeID %@ - deleting", nodeID); - [self clearStoredAttributesForNodeID:nodeID]; + // _clearStoredClusterDataForNodeID because we are are already + // on the _storageDelegateQueue and do not need to modify the + // node index in this case. + [self _clearStoredClusterDataForNodeID:nodeID]; } MTR_LOG_INFO("Fetch got no value for endpointIndex @ node 0x%016llX", nodeID.unsignedLongLongValue); @@ -1203,10 +966,10 @@ - (void)storeClusterData:(NSDictionary } } - // In the rare event that store fails, allow all attribute store attempts to go through and prune empty branches at the end altogether. + // In the rare event that store fails, allow all cluster data store attempts to go through and prune empty branches at the end altogether. if (storeFailures) { - [self _pruneEmptyStoredAttributesBranches]; - MTR_LOG_ERROR("Store failed in -storeAttributeValues:forNodeID: failure count %lu", static_cast(storeFailures)); + [self _pruneEmptyStoredClusterDataBranches]; + MTR_LOG_ERROR("Store failed in -storeClusterData:forNodeID: failure count %lu", static_cast(storeFailures)); } }); } diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm index 4b5ccc7d9477d4..25939d6ae5c64e 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm @@ -67,12 +67,6 @@ using namespace chip; using namespace chip::Controller; -static NSString * const kErrorPersistentStorageInit = @"Init failure while creating a persistent storage delegate"; -static NSString * const kErrorSessionResumptionStorageInit = @"Init failure while creating a session resumption storage delegate"; -static NSString * const kErrorControllerFactoryInit = @"Init failure while initializing controller factory"; -static NSString * const kErrorKeystoreInit = @"Init failure while initializing persistent storage keystore"; -static NSString * const kErrorCertStoreInit = @"Init failure while initializing persistent storage operational certificate store"; - static bool sExitHandlerRegistered = false; static void ShutdownOnExit() { @@ -228,21 +222,6 @@ - (void)_assertCurrentQueueIsNotMatterQueue VerifyOrDie(!DeviceLayer::PlatformMgrImpl().IsWorkQueueCurrentQueue()); } -- (BOOL)checkIsRunning:(NSError * __autoreleasing *)error -{ - [self _assertCurrentQueueIsNotMatterQueue]; - - if ([self isRunning]) { - return YES; - } - - if (error != nil) { - *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]; - } - - return NO; -} - - (void)cleanupStartupObjects { assertChipStackLockedByCurrentThread(); @@ -293,7 +272,7 @@ - (CHIP_ERROR)_initFabricTable:(FabricTable &)fabricTable { [self _assertCurrentQueueIsNotMatterQueue]; - if (!self.isRunning) { + if (!_running) { // Note: reading _running from outside of the Matter work queue return nil; } @@ -339,40 +318,25 @@ - (BOOL)_startControllerFactory:(MTRDeviceControllerFactoryParams *)startupParam { [self _assertCurrentQueueIsNotMatterQueue]; - if ([self isRunning]) { - MTR_LOG_DEBUG("Ignoring duplicate call to startup, Matter controller factory already started..."); - return YES; - } - - __block CHIP_ERROR errorCode = CHIP_NO_ERROR; + __block CHIP_ERROR err = CHIP_ERROR_INTERNAL; dispatch_sync(_chipWorkQueue, ^{ - if ([self isRunning]) { - return; + if (_running) { + // TODO: When treating a duplicate call as success we should validate parameters match + MTR_LOG_DEBUG("Ignoring duplicate call to startup, Matter controller factory already started..."); + ExitNow(err = CHIP_NO_ERROR); } StartupMetricsCollection(); InitializeServerAccessControl(); if (startupParams.hasStorage) { - _persistentStorageDelegate = new (std::nothrow) MTRPersistentStorageDelegateBridge(startupParams.storage); + _persistentStorageDelegate = new MTRPersistentStorageDelegateBridge(startupParams.storage); _sessionResumptionStorage = nullptr; _usingPerControllerStorage = NO; } else { - _persistentStorageDelegate = new (std::nothrow) MTRDemuxingStorage(self); - _sessionResumptionStorage = new (std::nothrow) MTRSessionResumptionStorageBridge(self); + _persistentStorageDelegate = new MTRDemuxingStorage(self); + _sessionResumptionStorage = new MTRSessionResumptionStorageBridge(self); _usingPerControllerStorage = YES; - - if (_sessionResumptionStorage == nil) { - MTR_LOG_ERROR("Error: %@", kErrorSessionResumptionStorageInit); - errorCode = CHIP_ERROR_NO_MEMORY; - return; - } - } - - if (_persistentStorageDelegate == nil) { - MTR_LOG_ERROR("Error: %@", kErrorPersistentStorageInit); - errorCode = CHIP_ERROR_NO_MEMORY; - return; } _otaProviderDelegate = startupParams.otaProviderDelegate; @@ -383,63 +347,42 @@ - (BOOL)_startControllerFactory:(MTRDeviceControllerFactoryParams *)startupParam // TODO: Allow passing a different keystore implementation via startupParams. _keystore = new PersistentStorageOperationalKeystore(); - if (_keystore == nullptr) { - MTR_LOG_ERROR("Error: %@", kErrorKeystoreInit); - errorCode = CHIP_ERROR_NO_MEMORY; - return; - } - - errorCode = _keystore->Init(_persistentStorageDelegate); - if (errorCode != CHIP_NO_ERROR) { - MTR_LOG_ERROR("Error: %@", kErrorKeystoreInit); - return; - } + SuccessOrExit(err = _keystore->Init(_persistentStorageDelegate)); // TODO Allow passing a different opcert store implementation via startupParams. _opCertStore = new Credentials::PersistentStorageOpCertStore(); - if (_opCertStore == nullptr) { - MTR_LOG_ERROR("Error: %@", kErrorCertStoreInit); - errorCode = CHIP_ERROR_NO_MEMORY; - return; - } - - errorCode = _opCertStore->Init(_persistentStorageDelegate); - if (errorCode != CHIP_NO_ERROR) { - MTR_LOG_ERROR("Error: %@", kErrorCertStoreInit); - return; - } + SuccessOrExit(err = _opCertStore->Init(_persistentStorageDelegate)); _productAttestationAuthorityCertificates = [startupParams.productAttestationAuthorityCertificates copy]; _certificationDeclarationCertificates = [startupParams.certificationDeclarationCertificates copy]; - chip::Controller::FactoryInitParams params; - if (startupParams.port != nil) { - params.listenPort = [startupParams.port unsignedShortValue]; - } - params.enableServerInteractions = startupParams.shouldStartServer; - - params.groupDataProvider = &_groupDataProvider; - params.sessionKeystore = &_sessionKeystore; - params.fabricIndependentStorage = _persistentStorageDelegate; - params.operationalKeystore = _keystore; - params.opCertStore = _opCertStore; - params.certificateValidityPolicy = &_certificateValidityPolicy; - params.sessionResumptionStorage = _sessionResumptionStorage; - errorCode = _controllerFactory->Init(params); - if (errorCode != CHIP_NO_ERROR) { - MTR_LOG_ERROR("Error: %@", kErrorControllerFactoryInit); - return; + { + chip::Controller::FactoryInitParams params; + if (startupParams.port != nil) { + params.listenPort = [startupParams.port unsignedShortValue]; + } + params.enableServerInteractions = startupParams.shouldStartServer; + + params.groupDataProvider = &_groupDataProvider; + params.sessionKeystore = &_sessionKeystore; + params.fabricIndependentStorage = _persistentStorageDelegate; + params.operationalKeystore = _keystore; + params.opCertStore = _opCertStore; + params.certificateValidityPolicy = &_certificateValidityPolicy; + params.sessionResumptionStorage = _sessionResumptionStorage; + SuccessOrExit(err = _controllerFactory->Init(params)); } // This needs to happen after DeviceControllerFactory::Init, // because that creates (lazily, by calling functions with // static variables in them) some static-lifetime objects. if (!sExitHandlerRegistered) { - int ret = atexit(ShutdownOnExit); - if (ret != 0) { - MTR_LOG_ERROR("Error registering exit handler: %d", ret); - return; + if (atexit(ShutdownOnExit) != 0) { + char error[128]; + strerror_r(errno, error, sizeof(error)); + MTR_LOG_ERROR("Warning: Failed to register atexit handler: %s", error); } + sExitHandlerRegistered = true; } HeapObjectPoolExitHandling::IgnoreLeaksOnExit(); @@ -452,20 +395,24 @@ - (BOOL)_startControllerFactory:(MTRDeviceControllerFactoryParams *)startupParam _controllerFactory->RetainSystemState(); _controllerFactory->ReleaseSystemState(); - self->_advertiseOperational = startupParams.shouldStartServer; - self->_running = YES; - }); + _advertiseOperational = startupParams.shouldStartServer; + _running = YES; + err = CHIP_NO_ERROR; - if (![self isRunning]) { - dispatch_sync(_chipWorkQueue, ^{ + exit: + if (err != CHIP_NO_ERROR) { + // Note: Since we have failed no later than _controllerFactory->Init(), + // there is no need to call _controllerFactory->Shutdown() here. [self cleanupStartupObjects]; - }); + } + }); + if (err != CHIP_NO_ERROR) { + MTR_LOG_ERROR("Failed to start Matter controller factory: %" CHIP_ERROR_FORMAT, err.Format()); if (error != nil) { - *error = [MTRError errorForCHIPErrorCode:errorCode]; + *error = [MTRError errorForCHIPErrorCode:err]; } return NO; } - return YES; } @@ -473,26 +420,19 @@ - (void)stopControllerFactory { [self _assertCurrentQueueIsNotMatterQueue]; - if (![self isRunning]) { - return; - } - while ([_controllers count] != 0) { [_controllers[0] shutdown]; } dispatch_sync(_chipWorkQueue, ^{ + VerifyOrReturn(_running); + MTR_LOG_INFO("Shutting down the Matter controller factory"); _controllerFactory->Shutdown(); - [self cleanupStartupObjects]; + _running = NO; + _advertiseOperational = NO; }); - - // NOTE: we do not call cleanupInitObjects because we can be restarted, and - // that does not re-create the objects that we create inside init. - // Maybe we should be creating them in startup? - - _running = NO; } /** @@ -540,7 +480,7 @@ - (MTRDeviceController * _Nullable)_startDeviceController:(MTRDeviceController * return nil; } - if (![self isRunning]) { + if (!_running) { // Note: reading _running from outside of the Matter work queue if (storageDelegate != nil) { MTR_LOG_DEFAULT("Auto-starting Matter controller factory in per-controller storage mode"); auto * params = [[MTRDeviceControllerFactoryParams alloc] initWithoutStorage]; @@ -744,13 +684,8 @@ - (MTRDeviceController * _Nullable)createControllerOnExistingFabric:(MTRDeviceCo keystore:self->_keystore advertiseOperational:self->_advertiseOperational params:startupParams]; - if (params == nil) { - fabricError = CHIP_ERROR_NO_MEMORY; - } else { - params.productAttestationAuthorityCertificates = self->_productAttestationAuthorityCertificates; - params.certificationDeclarationCertificates = self->_certificationDeclarationCertificates; - } - + params.productAttestationAuthorityCertificates = self->_productAttestationAuthorityCertificates; + params.certificationDeclarationCertificates = self->_certificationDeclarationCertificates; return params; } error:error]; @@ -800,12 +735,8 @@ - (MTRDeviceController * _Nullable)createControllerOnNewFabric:(MTRDeviceControl keystore:self->_keystore advertiseOperational:self->_advertiseOperational params:startupParams]; - if (params == nil) { - fabricError = CHIP_ERROR_NO_MEMORY; - } else { - params.productAttestationAuthorityCertificates = self->_productAttestationAuthorityCertificates; - params.certificationDeclarationCertificates = self->_certificationDeclarationCertificates; - } + params.productAttestationAuthorityCertificates = self->_productAttestationAuthorityCertificates; + params.certificationDeclarationCertificates = self->_certificationDeclarationCertificates; return params; } error:error]; @@ -907,12 +838,6 @@ - (MTRDeviceController * _Nullable)maybeInitializeOTAProvider:(MTRDeviceControll - (void)resetOperationalAdvertising { - if (![self checkIsRunning:nil]) { - // No need to reset anything; we are not running, so not - // advertising. - return; - } - if (!_advertiseOperational) { // No need to reset anything; we are not advertising the things that // would need to get reset. diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h index aa9c8c1e906ee3..4235f17cb5a0dc 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h @@ -256,6 +256,8 @@ NS_ASSUME_NONNULL_BEGIN - (MTRDevice *)deviceForNodeID:(NSNumber *)nodeID; - (void)removeDevice:(MTRDevice *)device; +- (NSNumber * _Nullable)syncGetCompressedFabricID; + @end NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRDevice_Internal.h b/src/darwin/Framework/CHIP/MTRDevice_Internal.h index 28833060ba6c27..57ee5446f3ba50 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDevice_Internal.h @@ -30,9 +30,6 @@ typedef NSDictionary * MTRDeviceDataValueDictionary; typedef void (^MTRDevicePerformAsyncBlock)(MTRBaseDevice * baseDevice); -// Whether to store attributes by cluster instead of as individual entries for each attribute -#define MTRDEVICE_ATTRIBUTE_CACHE_STORE_ATTRIBUTES_BY_CLUSTER 1 - /** * Information about a cluster, currently is just data version */ diff --git a/src/darwin/Framework/CHIP/MTRError.h b/src/darwin/Framework/CHIP/MTRError.h index 3068a1b2405779..84cca7abde7cdf 100644 --- a/src/darwin/Framework/CHIP/MTRError.h +++ b/src/darwin/Framework/CHIP/MTRError.h @@ -138,8 +138,8 @@ typedef NS_ERROR_ENUM(MTRInteractionErrorDomain, MTRInteractionErrorCode){ MTRInteractionErrorCodePathsExhausted = 0xc8, MTRInteractionErrorCodeTimedRequestMismatch = 0xc9, MTRInteractionErrorCodeFailsafeRequired = 0xca, - MTRInteractionErrorInvalidInState MTR_NEWLY_AVAILABLE = 0xcb, - MTRInteractionErrorNoCommandResponse MTR_NEWLY_AVAILABLE = 0xcc, + MTRInteractionErrorCodeInvalidInState MTR_NEWLY_AVAILABLE = 0xcb, + MTRInteractionErrorCodeNoCommandResponse MTR_NEWLY_AVAILABLE = 0xcc, }; // clang-format on diff --git a/src/darwin/Framework/CHIP/MTRManualSetupPayloadParser.mm b/src/darwin/Framework/CHIP/MTRManualSetupPayloadParser.mm index 2f909fdc4b2e37..c1716b513b38a6 100644 --- a/src/darwin/Framework/CHIP/MTRManualSetupPayloadParser.mm +++ b/src/darwin/Framework/CHIP/MTRManualSetupPayloadParser.mm @@ -50,19 +50,11 @@ - (MTRSetupPayload *)populatePayload:(NSError * __autoreleasing *)error chip::SetupPayload cPlusPluspayload; MTRSetupPayload * payload; - if (_chipManualSetupPayloadParser) { - CHIP_ERROR chipError = _chipManualSetupPayloadParser->populatePayload(cPlusPluspayload); - - if (chipError == CHIP_NO_ERROR) { - payload = [[MTRSetupPayload alloc] initWithSetupPayload:cPlusPluspayload]; - } else if (error) { - *error = [MTRError errorForCHIPErrorCode:chipError]; - } - } else { - // Memory init has failed - if (error) { - *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_NO_MEMORY]; - } + CHIP_ERROR chipError = _chipManualSetupPayloadParser->populatePayload(cPlusPluspayload); + if (chipError == CHIP_NO_ERROR) { + payload = [[MTRSetupPayload alloc] initWithSetupPayload:cPlusPluspayload]; + } else if (error) { + *error = [MTRError errorForCHIPErrorCode:chipError]; } return payload; diff --git a/src/darwin/Framework/CHIP/MTROperationalCredentialsDelegate.mm b/src/darwin/Framework/CHIP/MTROperationalCredentialsDelegate.mm index 888e3ddba38bfc..fa280c81e63bab 100644 --- a/src/darwin/Framework/CHIP/MTROperationalCredentialsDelegate.mm +++ b/src/darwin/Framework/CHIP/MTROperationalCredentialsDelegate.mm @@ -64,17 +64,8 @@ // Make copies of the certificates, just in case the API consumer // has them as MutableData. - mRootCert = [NSData dataWithData:rootCert]; - if (mRootCert == nil) { - return CHIP_ERROR_NO_MEMORY; - } - - if (icaCert != nil) { - mIntermediateCert = [NSData dataWithData:icaCert]; - if (mIntermediateCert == nil) { - return CHIP_ERROR_NO_MEMORY; - } - } + mRootCert = [rootCert copy]; + mIntermediateCert = [icaCert copy]; return CHIP_NO_ERROR; } diff --git a/src/darwin/Framework/CHIP/MTRQRCodeSetupPayloadParser.mm b/src/darwin/Framework/CHIP/MTRQRCodeSetupPayloadParser.mm index 53b8e733367a4f..acfa613bc6626f 100644 --- a/src/darwin/Framework/CHIP/MTRQRCodeSetupPayloadParser.mm +++ b/src/darwin/Framework/CHIP/MTRQRCodeSetupPayloadParser.mm @@ -50,19 +50,11 @@ - (MTRSetupPayload *)populatePayload:(NSError * __autoreleasing *)error chip::SetupPayload cPlusPluspayload; MTRSetupPayload * payload; - if (_chipQRCodeSetupPayloadParser) { - CHIP_ERROR chipError = _chipQRCodeSetupPayloadParser->populatePayload(cPlusPluspayload); - - if (chipError == CHIP_NO_ERROR) { - payload = [[MTRSetupPayload alloc] initWithSetupPayload:cPlusPluspayload]; - } else if (error) { - *error = [MTRError errorForCHIPErrorCode:chipError]; - } - } else { - // Memory init has failed - if (error) { - *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_NO_MEMORY]; - } + CHIP_ERROR chipError = _chipQRCodeSetupPayloadParser->populatePayload(cPlusPluspayload); + if (chipError == CHIP_NO_ERROR) { + payload = [[MTRSetupPayload alloc] initWithSetupPayload:cPlusPluspayload]; + } else if (error) { + *error = [MTRError errorForCHIPErrorCode:chipError]; } return payload; diff --git a/src/darwin/Framework/CHIPTests/MTRControllerTests.m b/src/darwin/Framework/CHIPTests/MTRControllerTests.m index 63a5baf32b64d5..975625ea55df4b 100644 --- a/src/darwin/Framework/CHIPTests/MTRControllerTests.m +++ b/src/darwin/Framework/CHIPTests/MTRControllerTests.m @@ -62,6 +62,10 @@ - (void)testFactoryLifecycle XCTAssertTrue([factory startControllerFactory:factoryParams error:nil]); XCTAssertTrue([factory isRunning]); + // Starting again with identical params is a no-op + __auto_type * factoryParams2 = [[MTRDeviceControllerFactoryParams alloc] initWithStorage:storage]; + XCTAssertTrue([factory startControllerFactory:factoryParams2 error:nil]); + [factory stopControllerFactory]; XCTAssertFalse([factory isRunning]); diff --git a/src/darwin/Framework/CHIPTests/MTRDeviceConnectivityMonitorTests.m b/src/darwin/Framework/CHIPTests/MTRDeviceConnectivityMonitorTests.m new file mode 100644 index 00000000000000..2c3cabc2ef39ee --- /dev/null +++ b/src/darwin/Framework/CHIPTests/MTRDeviceConnectivityMonitorTests.m @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2023 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import +#import + +#import "MTRDeviceConnectivityMonitor.h" + +@interface MTRDeviceConnectivityMonitor (Test) +- (instancetype)initWithInstanceName:(NSString *)instanceName; +@end + +@interface MTRDeviceConnectivityMonitorTests : XCTestCase +@end + +@implementation MTRDeviceConnectivityMonitorTests + +static DNSServiceRef sSharedConnection; + ++ (void)setUp +{ + DNSServiceErrorType dnsError = DNSServiceCreateConnection(&sSharedConnection); + XCTAssertEqual(dnsError, kDNSServiceErr_NoError); +} + ++ (void)tearDown +{ + DNSServiceRefDeallocate(sSharedConnection); +} + +static char kLocalDot[] = "local."; +static char kOperationalType[] = "_matter._tcp"; + +static void test001_MonitorTest_RegisterCallback( + DNSServiceRef sdRef, + DNSServiceFlags flags, + DNSServiceErrorType errorCode, + const char * name, + const char * regtype, + const char * domain, + void * context) +{ +} + +- (void)test001_BasicMonitorTest +{ + dispatch_queue_t testQueue = dispatch_queue_create("connectivity-monitor-test-queue", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); + DNSServiceRef testAdvertiser; + DNSServiceFlags flags = kDNSServiceFlagsNoAutoRename; + char testInstanceName[] = "testinstance-name"; + char testHostName[] = "localhost"; + uint16_t testPort = htons(15000); + DNSServiceErrorType dnsError = DNSServiceRegister(&testAdvertiser, flags, 0, testInstanceName, kOperationalType, kLocalDot, testHostName, testPort, 0, NULL, test001_MonitorTest_RegisterCallback, NULL); + XCTAssertEqual(dnsError, kDNSServiceErr_NoError); + + XCTestExpectation * connectivityMonitorCallbackExpectation = [self expectationWithDescription:@"Got connectivity monitor callback"]; + __block BOOL gotConnectivityMonitorCallback = NO; + + MTRDeviceConnectivityMonitor * monitor = [[MTRDeviceConnectivityMonitor alloc] initWithInstanceName:@(testInstanceName)]; + [monitor startMonitoringWithHandler:^{ + if (!gotConnectivityMonitorCallback) { + gotConnectivityMonitorCallback = YES; + [connectivityMonitorCallbackExpectation fulfill]; + } + } queue:testQueue]; + + [self waitForExpectations:@[ connectivityMonitorCallbackExpectation ] timeout:5]; + + [monitor stopMonitoring]; + DNSServiceRefDeallocate(testAdvertiser); +} + +@end diff --git a/src/darwin/Framework/CHIPTests/MTRDeviceTests.m b/src/darwin/Framework/CHIPTests/MTRDeviceTests.m index 4f97026ed6644f..d13f319faaa9e9 100644 --- a/src/darwin/Framework/CHIPTests/MTRDeviceTests.m +++ b/src/darwin/Framework/CHIPTests/MTRDeviceTests.m @@ -179,9 +179,9 @@ + (void)tearDown // Restore testing setting to previous state, and remove all persisted attributes MTRDeviceControllerLocalTestStorage.localTestStorageEnabled = slocalTestStorageEnabledBeforeUnitTest; - [sController.controllerDataStore clearAllStoredAttributes]; - NSArray * storedAttributesAfterClear = [sController.controllerDataStore getStoredAttributesForNodeID:@(kDeviceId)]; - XCTAssertEqual(storedAttributesAfterClear.count, 0); + [sController.controllerDataStore clearAllStoredClusterData]; + NSDictionary * storedClusterDataAfterClear = [sController.controllerDataStore getStoredClusterDataForNodeID:@(kDeviceId)]; + XCTAssertEqual(storedClusterDataAfterClear.count, 0); MTRDeviceController * controller = sController; XCTAssertNotNil(controller); @@ -1346,9 +1346,9 @@ - (void)test016_FailedSubscribeWithCacheReadDuringFailure - (void)test017_TestMTRDeviceBasics { // Ensure the test starts with clean slate, even with MTRDeviceControllerLocalTestStorage enabled - [sController.controllerDataStore clearAllStoredAttributes]; - NSArray * storedAttributesAfterClear = [sController.controllerDataStore getStoredAttributesForNodeID:@(kDeviceId)]; - XCTAssertEqual(storedAttributesAfterClear.count, 0); + [sController.controllerDataStore clearAllStoredClusterData]; + NSDictionary * storedClusterDataAfterClear = [sController.controllerDataStore getStoredClusterDataForNodeID:@(kDeviceId)]; + XCTAssertEqual(storedClusterDataAfterClear.count, 0); __auto_type * device = [MTRDevice deviceWithNodeID:kDeviceId deviceController:sController]; dispatch_queue_t queue = dispatch_get_main_queue(); @@ -2571,9 +2571,9 @@ - (void)test028_TimeZoneAndDST - (void)test029_MTRDeviceWriteCoalescing { // Ensure the test starts with clean slate, even with MTRDeviceControllerLocalTestStorage enabled - [sController.controllerDataStore clearAllStoredAttributes]; - NSArray * storedAttributesAfterClear = [sController.controllerDataStore getStoredAttributesForNodeID:@(kDeviceId)]; - XCTAssertEqual(storedAttributesAfterClear.count, 0); + [sController.controllerDataStore clearAllStoredClusterData]; + NSDictionary * storedClusterDataAfterClear = [sController.controllerDataStore getStoredClusterDataForNodeID:@(kDeviceId)]; + XCTAssertEqual(storedClusterDataAfterClear.count, 0); __auto_type * device = [MTRDevice deviceWithNodeID:kDeviceId deviceController:sController]; dispatch_queue_t queue = dispatch_get_main_queue(); @@ -2910,9 +2910,9 @@ - (void)test031_MTRDeviceAttributeCacheLocalTestStorage // First start with clean slate by removing the MTRDevice and clearing the persisted cache __auto_type * device = [MTRDevice deviceWithNodeID:@(kDeviceId) controller:sController]; [sController removeDevice:device]; - [sController.controllerDataStore clearAllStoredAttributes]; - NSArray * storedAttributesAfterClear = [sController.controllerDataStore getStoredAttributesForNodeID:@(kDeviceId)]; - XCTAssertEqual(storedAttributesAfterClear.count, 0); + [sController.controllerDataStore clearAllStoredClusterData]; + NSDictionary * storedClusterDataAfterClear = [sController.controllerDataStore getStoredClusterDataForNodeID:@(kDeviceId)]; + XCTAssertEqual(storedClusterDataAfterClear.count, 0); // Now recreate device and get subscription primed device = [MTRDevice deviceWithNodeID:@(kDeviceId) controller:sController]; @@ -2934,13 +2934,8 @@ - (void)test031_MTRDeviceAttributeCacheLocalTestStorage NSUInteger attributesReportedWithFirstSubscription = [device unitTestAttributesReportedSinceLastCheck]; -#if MTRDEVICE_ATTRIBUTE_CACHE_STORE_ATTRIBUTES_BY_CLUSTER NSDictionary * dataStoreClusterDataAfterFirstSubscription = [sController.controllerDataStore getStoredClusterDataForNodeID:@(kDeviceId)]; XCTAssertTrue(dataStoreClusterDataAfterFirstSubscription.count > 0); -#else - NSArray * dataStoreValuesAfterFirstSubscription = [sController.controllerDataStore getStoredAttributesForNodeID:@(kDeviceId)]; - XCTAssertTrue(dataStoreValuesAfterFirstSubscription.count > 0); -#endif // Now remove device, resubscribe, and see that it succeeds [sController removeDevice:device]; @@ -2971,8 +2966,13 @@ - (void)test031_MTRDeviceAttributeCacheLocalTestStorage // 2) Some attributes do change on resubscribe // * With all-clusts-app as of 2024-02-10, out of 1287 persisted attributes, still 450 attributes were reported with filter // And so conservatively, assert that data version filters save at least 300 entries. - NSArray * dataStoreValuesAfterSecondSubscription = [sController.controllerDataStore getStoredAttributesForNodeID:@(kDeviceId)]; - NSUInteger storedAttributeCountDifferenceFromMTRDeviceReport = dataStoreValuesAfterSecondSubscription.count - attributesReportedWithSecondSubscription; + NSDictionary * storedClusterDataAfterSecondSubscription = [sController.controllerDataStore getStoredClusterDataForNodeID:@(kDeviceId)]; + NSUInteger dataStoreAttributeCountAfterSecondSubscription = 0; + for (NSNumber * clusterID in storedClusterDataAfterSecondSubscription) { + MTRDeviceClusterData * clusterData = storedClusterDataAfterSecondSubscription[clusterID]; + dataStoreAttributeCountAfterSecondSubscription += clusterData.attributes.count; + } + NSUInteger storedAttributeCountDifferenceFromMTRDeviceReport = dataStoreAttributeCountAfterSecondSubscription - attributesReportedWithSecondSubscription; XCTAssertTrue(storedAttributeCountDifferenceFromMTRDeviceReport > 300); } diff --git a/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m b/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m index df98530a81db18..bea49d957653c7 100644 --- a/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m +++ b/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m @@ -19,6 +19,7 @@ // system dependencies #import +#import "MTRDeviceControllerLocalTestStorage.h" #import "MTRDeviceTestDelegate.h" #import "MTRDevice_Internal.h" #import "MTRErrorTestUtils.h" @@ -181,6 +182,7 @@ @interface MTRPerControllerStorageTests : XCTestCase @implementation MTRPerControllerStorageTests { dispatch_queue_t _storageQueue; + BOOL _localTestStorageEnabledBeforeUnitTest; } - (void)setUp @@ -189,6 +191,12 @@ - (void)setUp [super setUp]; [self setContinueAfterFailure:NO]; + // Make sure local test storage is off, because we assume that the storage + // delegate we provide is in fact used for local storage as part of our + // tests. + _localTestStorageEnabledBeforeUnitTest = MTRDeviceControllerLocalTestStorage.localTestStorageEnabled; + MTRDeviceControllerLocalTestStorage.localTestStorageEnabled = NO; + _storageQueue = dispatch_queue_create("test.storage.queue", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); } @@ -197,6 +205,10 @@ - (void)tearDown // Per-test teardown, runs after each test. [self stopFactory]; _storageQueue = nil; + + // Restore local test storage setting to previous state. + MTRDeviceControllerLocalTestStorage.localTestStorageEnabled = _localTestStorageEnabledBeforeUnitTest; + [super tearDown]; } @@ -1081,132 +1093,137 @@ - (void)test008_TestDataStoreDirect XCTAssertEqualObjects(controller.controllerNodeID, nodeID); - NSArray * testAttributes = @[ - @{ MTRAttributePathKey : [MTRAttributePath attributePathWithEndpointID:@(1) clusterID:@(1) attributeID:@(1)], MTRDataKey : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(111) } }, - @{ MTRAttributePathKey : [MTRAttributePath attributePathWithEndpointID:@(1) clusterID:@(1) attributeID:@(2)], MTRDataKey : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(112) } }, - @{ MTRAttributePathKey : [MTRAttributePath attributePathWithEndpointID:@(1) clusterID:@(1) attributeID:@(3)], MTRDataKey : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(113) } }, - - @{ MTRAttributePathKey : [MTRAttributePath attributePathWithEndpointID:@(1) clusterID:@(2) attributeID:@(1)], MTRDataKey : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(121) } }, - @{ MTRAttributePathKey : [MTRAttributePath attributePathWithEndpointID:@(1) clusterID:@(2) attributeID:@(2)], MTRDataKey : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(122) } }, - @{ MTRAttributePathKey : [MTRAttributePath attributePathWithEndpointID:@(1) clusterID:@(2) attributeID:@(3)], MTRDataKey : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(123) } }, - - @{ MTRAttributePathKey : [MTRAttributePath attributePathWithEndpointID:@(2) clusterID:@(1) attributeID:@(1)], MTRDataKey : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(211) } }, - @{ MTRAttributePathKey : [MTRAttributePath attributePathWithEndpointID:@(2) clusterID:@(1) attributeID:@(2)], MTRDataKey : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(212) } }, - @{ MTRAttributePathKey : [MTRAttributePath attributePathWithEndpointID:@(2) clusterID:@(1) attributeID:@(3)], MTRDataKey : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(213) } }, - ]; - [controller.controllerDataStore storeAttributeValues:testAttributes forNodeID:@(1001)]; - [controller.controllerDataStore storeAttributeValues:testAttributes forNodeID:@(1002)]; - [controller.controllerDataStore storeAttributeValues:testAttributes forNodeID:@(1003)]; - MTRDeviceClusterData * testClusterData1 = [[MTRDeviceClusterData alloc] init]; testClusterData1.dataVersion = @(1); + testClusterData1.attributes = @{ + @(1) : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(111) }, + @(2) : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(112) }, + @(3) : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(113) }, + }; MTRDeviceClusterData * testClusterData2 = [[MTRDeviceClusterData alloc] init]; testClusterData2.dataVersion = @(2); + testClusterData2.attributes = @{ + @(1) : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(121) }, + @(2) : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(122) }, + @(3) : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(123) }, + }; MTRDeviceClusterData * testClusterData3 = [[MTRDeviceClusterData alloc] init]; testClusterData3.dataVersion = @(3); + testClusterData3.attributes = @{ + @(1) : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(211) }, + @(2) : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(212) }, + @(3) : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(213) }, + }; NSDictionary * testClusterData = @{ [MTRClusterPath clusterPathWithEndpointID:@(1) clusterID:@(1)] : testClusterData1, [MTRClusterPath clusterPathWithEndpointID:@(1) clusterID:@(2)] : testClusterData2, - [MTRClusterPath clusterPathWithEndpointID:@(1) clusterID:@(3)] : testClusterData3, + [MTRClusterPath clusterPathWithEndpointID:@(2) clusterID:@(3)] : testClusterData3, }; [controller.controllerDataStore storeClusterData:testClusterData forNodeID:@(1001)]; + [controller.controllerDataStore storeClusterData:testClusterData forNodeID:@(1002)]; + [controller.controllerDataStore storeClusterData:testClusterData forNodeID:@(1003)]; - // Check values are written and can be fetched - NSArray * dataStoreValues = [controller.controllerDataStore getStoredAttributesForNodeID:@(1001)]; - XCTAssertEqual(dataStoreValues.count, 9); - dataStoreValues = [controller.controllerDataStore getStoredAttributesForNodeID:@(1002)]; - XCTAssertEqual(dataStoreValues.count, 9); - dataStoreValues = [controller.controllerDataStore getStoredAttributesForNodeID:@(1003)]; - XCTAssertEqual(dataStoreValues.count, 9); - - // Check values - NSUInteger unexpectedValues = 0; - for (NSDictionary * responseValue in dataStoreValues) { - MTRAttributePath * path = responseValue[MTRAttributePathKey]; - XCTAssertNotNil(path); - NSDictionary * dataValue = responseValue[MTRDataKey]; - XCTAssertNotNil(dataValue); - NSString * type = dataValue[MTRTypeKey]; - XCTAssertNotNil(type); - XCTAssertEqualObjects(type, MTRUnsignedIntegerValueType); - NSNumber * value = dataValue[MTRValueKey]; - XCTAssertNotNil(value); - - if ([path.endpoint isEqualToNumber:@(1)] && [path.cluster isEqualToNumber:@(1)] && [path.attribute isEqualToNumber:@(1)]) { - XCTAssertEqualObjects(value, @(111)); - } else if ([path.endpoint isEqualToNumber:@(1)] && [path.cluster isEqualToNumber:@(1)] && [path.attribute isEqualToNumber:@(2)]) { - XCTAssertEqualObjects(value, @(112)); - } else if ([path.endpoint isEqualToNumber:@(1)] && [path.cluster isEqualToNumber:@(1)] && [path.attribute isEqualToNumber:@(3)]) { - XCTAssertEqualObjects(value, @(113)); - } else if ([path.endpoint isEqualToNumber:@(1)] && [path.cluster isEqualToNumber:@(2)] && [path.attribute isEqualToNumber:@(1)]) { - XCTAssertEqualObjects(value, @(121)); - } else if ([path.endpoint isEqualToNumber:@(1)] && [path.cluster isEqualToNumber:@(2)] && [path.attribute isEqualToNumber:@(2)]) { - XCTAssertEqualObjects(value, @(122)); - } else if ([path.endpoint isEqualToNumber:@(1)] && [path.cluster isEqualToNumber:@(2)] && [path.attribute isEqualToNumber:@(3)]) { - XCTAssertEqualObjects(value, @(123)); - } else if ([path.endpoint isEqualToNumber:@(2)] && [path.cluster isEqualToNumber:@(1)] && [path.attribute isEqualToNumber:@(1)]) { - XCTAssertEqualObjects(value, @(211)); - } else if ([path.endpoint isEqualToNumber:@(2)] && [path.cluster isEqualToNumber:@(1)] && [path.attribute isEqualToNumber:@(2)]) { - XCTAssertEqualObjects(value, @(212)); - } else if ([path.endpoint isEqualToNumber:@(2)] && [path.cluster isEqualToNumber:@(1)] && [path.attribute isEqualToNumber:@(3)]) { - XCTAssertEqualObjects(value, @(213)); - } else { - unexpectedValues++; + for (NSNumber * nodeID in @[ @(1001), @(1002), @(1003) ]) { + NSDictionary * dataStoreClusterData = [controller.controllerDataStore getStoredClusterDataForNodeID:nodeID]; + for (MTRClusterPath * path in testClusterData) { + XCTAssertEqualObjects(testClusterData[path], dataStoreClusterData[path]); } } - XCTAssertEqual(unexpectedValues, 0); - NSDictionary * dataStoreClusterData = [controller.controllerDataStore getStoredClusterDataForNodeID:@(1001)]; - for (MTRClusterPath * path in testClusterData) { - XCTAssertEqualObjects(testClusterData[path].dataVersion, dataStoreClusterData[path].dataVersion); + [controller.controllerDataStore clearStoredClusterDataForNodeID:@(1001)]; + XCTAssertNil([controller.controllerDataStore getStoredClusterDataForNodeID:@(1001)]); + for (NSNumber * nodeID in @[ @(1002), @(1003) ]) { + NSDictionary * dataStoreClusterData = [controller.controllerDataStore getStoredClusterDataForNodeID:nodeID]; + for (MTRClusterPath * path in testClusterData) { + XCTAssertEqualObjects(testClusterData[path], dataStoreClusterData[path]); + } } - [controller.controllerDataStore clearStoredAttributesForNodeID:@(1001)]; - dataStoreValues = [controller.controllerDataStore getStoredAttributesForNodeID:@(1001)]; - XCTAssertEqual(dataStoreValues.count, 0); - dataStoreValues = [controller.controllerDataStore getStoredAttributesForNodeID:@(1002)]; - XCTAssertEqual(dataStoreValues.count, 9); - dataStoreValues = [controller.controllerDataStore getStoredAttributesForNodeID:@(1003)]; - XCTAssertEqual(dataStoreValues.count, 9); - - [controller.controllerDataStore clearAllStoredAttributes]; - dataStoreValues = [controller.controllerDataStore getStoredAttributesForNodeID:@(1001)]; - XCTAssertEqual(dataStoreValues.count, 0); - dataStoreValues = [controller.controllerDataStore getStoredAttributesForNodeID:@(1002)]; - XCTAssertEqual(dataStoreValues.count, 0); - dataStoreValues = [controller.controllerDataStore getStoredAttributesForNodeID:@(1003)]; - XCTAssertEqual(dataStoreValues.count, 0); + [controller.controllerDataStore clearAllStoredClusterData]; + for (NSNumber * nodeID in @[ @(1001), @(1002), @(1003) ]) { + XCTAssertNil([controller.controllerDataStore getStoredClusterDataForNodeID:nodeID]); + } // Test MTRDeviceControllerDataStore _pruneEmptyStoredAttributesBranches // - Clear cache - // - Store an attribute - // - Manually delete it from the test storage delegate + // - Store some cluster data + // - Manually delete parts of the data from the test storage delegate // - Call _pruneEmptyStoredAttributesBranches - [controller.controllerDataStore clearAllStoredAttributes]; + [controller.controllerDataStore storeClusterData:testClusterData forNodeID:@(2001)]; + [controller.controllerDataStore storeClusterData:testClusterData forNodeID:@(2002)]; - NSArray * testAttribute = @[ - @{ MTRAttributePathKey : [MTRAttributePath attributePathWithEndpointID:@(1) clusterID:@(1) attributeID:@(1)], MTRDataKey : @ { MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(111) } }, - ]; - [controller.controllerDataStore storeAttributeValues:testAttribute forNodeID:@(2001)]; + NSString * testClusterIndexKey1 = [controller.controllerDataStore _clusterIndexKeyForNodeID:@(2001) endpointID:@(1)]; + NSString * testClusterIndexKey2 = [controller.controllerDataStore _clusterIndexKeyForNodeID:@(2001) endpointID:@(2)]; + NSString * testClusterIndexKey3 = [controller.controllerDataStore _clusterIndexKeyForNodeID:@(2002) endpointID:@(1)]; + NSString * testClusterIndexKey4 = [controller.controllerDataStore _clusterIndexKeyForNodeID:@(2002) endpointID:@(2)]; + NSString * testEndpointIndexKey1 = [controller.controllerDataStore _endpointIndexKeyForNodeID:@(2001)]; + NSString * testEndpointIndexKey2 = [controller.controllerDataStore _endpointIndexKeyForNodeID:@(2002)]; + NSString * testNodeIndexKey = @"attrCacheNodeIndex"; // store is async, so remove on the same queue to ensure order dispatch_sync(_storageQueue, ^{ - NSString * testAttributeValueKey = [controller.controllerDataStore _attributeValueKeyForNodeID:@(2001) endpointID:@(1) clusterID:@(1) attributeID:@(1)]; - [storageDelegate controller:controller removeValueForKey:testAttributeValueKey securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + // Ensure that the indices we expect are populated. + XCTAssertNotNil([storageDelegate controller:controller valueForKey:testClusterIndexKey1 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]); + XCTAssertNotNil([storageDelegate controller:controller valueForKey:testClusterIndexKey2 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]); + XCTAssertNotNil([storageDelegate controller:controller valueForKey:testClusterIndexKey3 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]); + XCTAssertNotNil([storageDelegate controller:controller valueForKey:testClusterIndexKey4 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]); + XCTAssertNotNil([storageDelegate controller:controller valueForKey:testEndpointIndexKey1 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]); + XCTAssertNotNil([storageDelegate controller:controller valueForKey:testEndpointIndexKey2 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]); + XCTAssertNotNil([storageDelegate controller:controller valueForKey:testNodeIndexKey securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]); + + // Remove all three MTRDeviceClusterData for node 2001 + NSString * testClusterDataKey = [controller.controllerDataStore _clusterDataKeyForNodeID:@(2001) endpointID:@(1) clusterID:@(1)]; + [storageDelegate controller:controller removeValueForKey:testClusterDataKey securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + testClusterDataKey = [controller.controllerDataStore _clusterDataKeyForNodeID:@(2001) endpointID:@(1) clusterID:@(2)]; + [storageDelegate controller:controller removeValueForKey:testClusterDataKey securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + testClusterDataKey = [controller.controllerDataStore _clusterDataKeyForNodeID:@(2001) endpointID:@(2) clusterID:@(3)]; + [storageDelegate controller:controller removeValueForKey:testClusterDataKey securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + + // Remove the two MTRDeviceClusterData under endpoint 1 for node 2002 + testClusterDataKey = [controller.controllerDataStore _clusterDataKeyForNodeID:@(2002) endpointID:@(1) clusterID:@(1)]; + [storageDelegate controller:controller removeValueForKey:testClusterDataKey securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + testClusterDataKey = [controller.controllerDataStore _clusterDataKeyForNodeID:@(2002) endpointID:@(1) clusterID:@(2)]; + [storageDelegate controller:controller removeValueForKey:testClusterDataKey securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + }); + + [controller.controllerDataStore unitTestPruneEmptyStoredClusterDataBranches]; + + // Now check the indexes are pruned. There should be no more cluster + // indices or endpoint indices for node 2001. + id testClusterIndex1 = [storageDelegate controller:controller valueForKey:testClusterIndexKey1 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + XCTAssertNil(testClusterIndex1); + id testClusterIndex2 = [storageDelegate controller:controller valueForKey:testClusterIndexKey2 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + XCTAssertNil(testClusterIndex2); + id testEndpointIndex1 = [storageDelegate controller:controller valueForKey:testEndpointIndexKey1 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + XCTAssertNil(testEndpointIndex1); + + // There should be no more cluster index for endpoint 1 for node 2, but + // we should still have a cluster index for endpoint 2, and an endpoint index. + id testClusterIndex3 = [storageDelegate controller:controller valueForKey:testClusterIndexKey3 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + XCTAssertNil(testClusterIndex3); + id testClusterIndex4 = [storageDelegate controller:controller valueForKey:testClusterIndexKey4 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + XCTAssertNotNil(testClusterIndex4); + id testEndpointIndex2 = [storageDelegate controller:controller valueForKey:testEndpointIndexKey2 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + XCTAssertNotNil(testClusterIndex4); + + // We should still have a node index. + id testNodeIndex = [storageDelegate controller:controller valueForKey:testNodeIndexKey securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + XCTAssertNotNil(testNodeIndex); + + // Again, remove on the storage queue to ensure order. + dispatch_sync(_storageQueue, ^{ + NSString * testClusterDataKey = [controller.controllerDataStore _clusterDataKeyForNodeID:@(2002) endpointID:@(2) clusterID:@(3)]; + [storageDelegate controller:controller removeValueForKey:testClusterDataKey securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; }); - [controller.controllerDataStore unitTestPruneEmptyStoredAttributesBranches]; - - // Now check the indexes are pruned - NSString * testAttributeIndexKey = [controller.controllerDataStore _attributeIndexKeyForNodeID:@(2001) endpointID:@(1) clusterID:@(1)]; - id testAttributeIndex = [storageDelegate controller:controller valueForKey:testAttributeIndexKey securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; - XCTAssertNil(testAttributeIndex); - NSString * testClusterIndexKey = [controller.controllerDataStore _clusterIndexKeyForNodeID:@(2001) endpointID:@(1)]; - id testClusterIndex = [storageDelegate controller:controller valueForKey:testClusterIndexKey securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; - XCTAssertNil(testClusterIndex); - NSString * testEndpointIndexKey = [controller.controllerDataStore _endpointIndexKeyForNodeID:@(2001)]; - id testEndpointIndex = [storageDelegate controller:controller valueForKey:testEndpointIndexKey securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; - XCTAssertNil(testEndpointIndex); - id testNodeIndex = [storageDelegate controller:controller valueForKey:@"attrCacheNodeIndex" securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + + [controller.controllerDataStore unitTestPruneEmptyStoredClusterDataBranches]; + + // All the indices should be pruned now. + testClusterIndex4 = [storageDelegate controller:controller valueForKey:testClusterIndexKey4 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + XCTAssertNil(testClusterIndex4); + testEndpointIndex2 = [storageDelegate controller:controller valueForKey:testEndpointIndexKey2 securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; + XCTAssertNil(testClusterIndex4); + testNodeIndex = [storageDelegate controller:controller valueForKey:testNodeIndexKey securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; XCTAssertNil(testNodeIndex); // Now test bulk write @@ -1275,11 +1292,11 @@ - (void)test008_TestDataStoreDirect [storageDelegate controller:controller storeValues:testBulkValues securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared]; }); // Verify that the store resulted in the correct values - dataStoreClusterData = [controller.controllerDataStore getStoredClusterDataForNodeID:@(3001)]; + NSDictionary * dataStoreClusterData = [controller.controllerDataStore getStoredClusterDataForNodeID:@(3001)]; XCTAssertEqualObjects(dataStoreClusterData, bulkTestClusterDataDictionary); // clear information before the next test - [controller.controllerDataStore clearStoredAttributesForNodeID:@(3001)]; + [controller.controllerDataStore clearStoredClusterDataForNodeID:@(3001)]; // Now test bulk store through data store [controller.controllerDataStore storeClusterData:bulkTestClusterDataDictionary forNodeID:@(3001)]; @@ -1356,7 +1373,6 @@ - (void)doDataStoreMTRDeviceTestWithStorageDelegate:(id * dataStoreClusterData = [controller.controllerDataStore getStoredClusterDataForNodeID:deviceID]; for (MTRClusterPath * path in dataStoreClusterData) { MTRDeviceClusterData * data = dataStoreClusterData[path]; @@ -1367,21 +1383,6 @@ - (void)doDataStoreMTRDeviceTestWithStorageDelegate:(id *)getStoredAttributesForNodeID:(NSNumber *)nodeID; - (nullable NSDictionary *)getStoredClusterDataForNodeID:(NSNumber *)nodeID; -- (void)storeAttributeValues:(NSArray *)dataValues forNodeID:(NSNumber *)nodeID; - (void)storeClusterData:(NSDictionary *)clusterData forNodeID:(NSNumber *)nodeID; -- (void)clearStoredAttributesForNodeID:(NSNumber *)nodeID; -- (void)clearAllStoredAttributes; -- (void)unitTestPruneEmptyStoredAttributesBranches; +- (void)clearStoredClusterDataForNodeID:(NSNumber *)nodeID; +- (void)clearAllStoredClusterData; +- (void)unitTestPruneEmptyStoredClusterDataBranches; - (NSString *)_endpointIndexKeyForNodeID:(NSNumber *)nodeID; - (NSString *)_clusterIndexKeyForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID; - (NSString *)_clusterDataKeyForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID; -- (NSString *)_attributeIndexKeyForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID; -- (NSString *)_attributeValueKeyForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID attributeID:(NSNumber *)attributeID; @end // Declare internal methods for testing diff --git a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj index 846db8bd08ee26..78ff18793ebd5c 100644 --- a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj @@ -264,6 +264,9 @@ 75A202E52BA8DBAC00A771DD /* reporting.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 75A202E42BA8DBAC00A771DD /* reporting.cpp */; }; 75A202E62BA8DBAC00A771DD /* reporting.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 75A202E42BA8DBAC00A771DD /* reporting.cpp */; }; 75B0D01E2B71B47F002074DD /* MTRDeviceTestDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 75B0D01D2B71B47F002074DD /* MTRDeviceTestDelegate.m */; }; + 75B3269C2BCDB9D600E17C4E /* MTRDeviceConnectivityMonitor.h in Headers */ = {isa = PBXBuildFile; fileRef = 75B3269B2BCDB9D600E17C4E /* MTRDeviceConnectivityMonitor.h */; }; + 75B3269E2BCDB9EA00E17C4E /* MTRDeviceConnectivityMonitor.mm in Sources */ = {isa = PBXBuildFile; fileRef = 75B3269D2BCDB9EA00E17C4E /* MTRDeviceConnectivityMonitor.mm */; }; + 75B326A22BCF12E900E17C4E /* MTRDeviceConnectivityMonitorTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 75B326A12BCF12E900E17C4E /* MTRDeviceConnectivityMonitorTests.m */; }; 75B765C12A1D71BC0014719B /* MTRAttributeSpecifiedCheck.h in Headers */ = {isa = PBXBuildFile; fileRef = 75B765C02A1D71BC0014719B /* MTRAttributeSpecifiedCheck.h */; }; 75B765C32A1D82D30014719B /* MTRAttributeSpecifiedCheck.mm in Sources */ = {isa = PBXBuildFile; fileRef = 75B765C22A1D82D30014719B /* MTRAttributeSpecifiedCheck.mm */; }; 8874C1322B69C7060084BEFD /* MTRMetricsTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 8874C1312B69C7060084BEFD /* MTRMetricsTests.m */; }; @@ -673,6 +676,9 @@ 75A202E42BA8DBAC00A771DD /* reporting.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = reporting.cpp; sourceTree = ""; }; 75B0D01C2B71B46F002074DD /* MTRDeviceTestDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRDeviceTestDelegate.h; sourceTree = ""; }; 75B0D01D2B71B47F002074DD /* MTRDeviceTestDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MTRDeviceTestDelegate.m; sourceTree = ""; }; + 75B3269B2BCDB9D600E17C4E /* MTRDeviceConnectivityMonitor.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRDeviceConnectivityMonitor.h; sourceTree = ""; }; + 75B3269D2BCDB9EA00E17C4E /* MTRDeviceConnectivityMonitor.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRDeviceConnectivityMonitor.mm; sourceTree = ""; }; + 75B326A12BCF12E900E17C4E /* MTRDeviceConnectivityMonitorTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MTRDeviceConnectivityMonitorTests.m; sourceTree = ""; }; 75B765BF2A1D70F80014719B /* MTRAttributeSpecifiedCheck-src.zapt */ = {isa = PBXFileReference; lastKnownFileType = text; path = "MTRAttributeSpecifiedCheck-src.zapt"; sourceTree = ""; }; 75B765C02A1D71BC0014719B /* MTRAttributeSpecifiedCheck.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRAttributeSpecifiedCheck.h; sourceTree = ""; }; 75B765C22A1D82D30014719B /* MTRAttributeSpecifiedCheck.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRAttributeSpecifiedCheck.mm; sourceTree = ""; }; @@ -1273,6 +1279,8 @@ 88EBF8CC27FABDD500686BC1 /* MTRDeviceAttestationDelegateBridge.mm */, 2C5EEEF4268A85C400CAE3D3 /* MTRDeviceConnectionBridge.h */, 2C5EEEF5268A85C400CAE3D3 /* MTRDeviceConnectionBridge.mm */, + 75B3269B2BCDB9D600E17C4E /* MTRDeviceConnectivityMonitor.h */, + 75B3269D2BCDB9EA00E17C4E /* MTRDeviceConnectivityMonitor.mm */, 991DC0822475F45400C13860 /* MTRDeviceController.h */, 5136660F28067D540025EDAE /* MTRDeviceController_Internal.h */, 991DC0872475F47D00C13860 /* MTRDeviceController.mm */, @@ -1372,6 +1380,7 @@ 99C65E0F267282F1003402F6 /* MTRControllerTests.m */, 51A2F1312A00402A00F03298 /* MTRDataValueParserTests.m */, 5AE6D4E327A99041001F2493 /* MTRDeviceTests.m */, + 75B326A12BCF12E900E17C4E /* MTRDeviceConnectivityMonitorTests.m */, 51D9CB0A2BA37DCE0049D6DB /* MTRDSTOffsetTests.m */, 3D0C484A29DA4FA0006D811F /* MTRErrorTests.m */, 5173A47829C0E82300F67F48 /* MTRFabricInfoTests.m */, @@ -1559,6 +1568,7 @@ 3D843717294979230070D20A /* MTRClusters_Internal.h in Headers */, 7596A85728788557004DAE0E /* MTRClusters.h in Headers */, 99D466E12798936D0089A18F /* MTRCommissioningParameters.h in Headers */, + 75B3269C2BCDB9D600E17C4E /* MTRDeviceConnectivityMonitor.h in Headers */, 5136661528067D550025EDAE /* MTRDeviceControllerFactory_Internal.h in Headers */, 515C1C70284F9FFB00A48F0C /* MTRFramework.h in Headers */, 7534F12928BFF20300390851 /* MTRDeviceAttestationDelegate_Internal.h in Headers */, @@ -1929,6 +1939,7 @@ 510470FB2A2F7DF60053EA7E /* MTRBackwardsCompatShims.mm in Sources */, 5173A47629C0E2ED00F67F48 /* MTRFabricInfo.mm in Sources */, 5ACDDD7D27CD16D200EFD68A /* MTRClusterStateCacheContainer.mm in Sources */, + 75B3269E2BCDB9EA00E17C4E /* MTRDeviceConnectivityMonitor.mm in Sources */, 513DDB8A2761F6F900DAA01A /* MTRAttributeTLVValueDecoder.mm in Sources */, 5117DD3829A931AE00FFA1AA /* MTROperationalBrowser.mm in Sources */, 514C79F02B62ADDA00DD6D7B /* descriptor.cpp in Sources */, @@ -1980,6 +1991,7 @@ 518D3F832AA132DC008E0007 /* MTRTestPerControllerStorage.m in Sources */, 51339B1F2A0DA64D00C798C1 /* MTRCertificateValidityTests.m in Sources */, 5173A47929C0E82300F67F48 /* MTRFabricInfoTests.m in Sources */, + 75B326A22BCF12E900E17C4E /* MTRDeviceConnectivityMonitorTests.m in Sources */, 5143851E2A65885500EDC8E6 /* MTRSwiftPairingTests.swift in Sources */, 75B0D01E2B71B47F002074DD /* MTRDeviceTestDelegate.m in Sources */, 3D0C484B29DA4FA0006D811F /* MTRErrorTests.m in Sources */, diff --git a/src/include/platform/CHIPDeviceEvent.h b/src/include/platform/CHIPDeviceEvent.h index 729937e1c07fc0..cbab1d9817aed2 100644 --- a/src/include/platform/CHIPDeviceEvent.h +++ b/src/include/platform/CHIPDeviceEvent.h @@ -369,7 +369,7 @@ typedef void (*AsyncWorkFunct)(intptr_t arg); #include CHIPDEVICEPLATFORMEVENT_HEADER #endif // defined(CHIP_DEVICE_LAYER_TARGET) -#include +#include #include #include #include diff --git a/src/include/platform/ConnectivityManager.h b/src/include/platform/ConnectivityManager.h index 5699caf1a1ef5b..817019b3c1c63c 100644 --- a/src/include/platform/ConnectivityManager.h +++ b/src/include/platform/ConnectivityManager.h @@ -182,6 +182,7 @@ class ConnectivityManager void MaintainOnDemandWiFiAP(); System::Clock::Timeout GetWiFiAPIdleTimeout(); void SetWiFiAPIdleTimeout(System::Clock::Timeout val); + CHIP_ERROR DisconnectNetwork(); // Thread Methods bool IsThreadEnabled(); @@ -560,5 +561,10 @@ inline void ConnectivityManager::OnWiFiStationProvisionChange() static_cast(this)->_OnWiFiStationProvisionChange(); } +inline CHIP_ERROR ConnectivityManager::DisconnectNetwork() +{ + return static_cast(this)->_DisconnectNetwork(); +} + } // namespace DeviceLayer } // namespace chip diff --git a/src/include/platform/DiagnosticDataProvider.h b/src/include/platform/DiagnosticDataProvider.h index a99ca6ee61beb1..2430673bc55724 100644 --- a/src/include/platform/DiagnosticDataProvider.h +++ b/src/include/platform/DiagnosticDataProvider.h @@ -91,6 +91,29 @@ class WiFiDiagnosticsDelegate virtual void OnConnectionStatusChanged(uint8_t connectionStatus) {} }; +/** + * Defines the Thread Diagnostics Delegate class to notify Thread network events. + */ +class ThreadDiagnosticsDelegate +{ +public: + virtual ~ThreadDiagnosticsDelegate() {} + + /** + * @brief + * Called when the Node’s connection status to a Thread network has changed. + */ + virtual void OnConnectionStatusChanged(app::Clusters::ThreadNetworkDiagnostics::ConnectionStatusEnum newConnectionStatus) {} + + /** + * @brief + * Called when the Node detects change in the set of current Thread network faults. + */ + virtual void OnNetworkFaultChanged(const GeneralFaults & previous, + const GeneralFaults & current) + {} +}; + /** * Provides access to runtime and build-time configuration information for a chip device. */ @@ -99,6 +122,8 @@ class DiagnosticDataProvider public: void SetWiFiDiagnosticsDelegate(WiFiDiagnosticsDelegate * delegate) { mWiFiDiagnosticsDelegate = delegate; } WiFiDiagnosticsDelegate * GetWiFiDiagnosticsDelegate() const { return mWiFiDiagnosticsDelegate; } + void SetThreadDiagnosticsDelegate(ThreadDiagnosticsDelegate * delegate) { mThreadDiagnosticsDelegate = delegate; } + ThreadDiagnosticsDelegate * GetThreadDiagnosticsDelegate() const { return mThreadDiagnosticsDelegate; } /** * General Diagnostics methods. @@ -238,7 +263,8 @@ class DiagnosticDataProvider virtual ~DiagnosticDataProvider() = default; private: - WiFiDiagnosticsDelegate * mWiFiDiagnosticsDelegate = nullptr; + WiFiDiagnosticsDelegate * mWiFiDiagnosticsDelegate = nullptr; + ThreadDiagnosticsDelegate * mThreadDiagnosticsDelegate = nullptr; // No copy, move or assignment. DiagnosticDataProvider(const DiagnosticDataProvider &) = delete; diff --git a/src/include/platform/internal/GenericConfigurationManagerImpl.ipp b/src/include/platform/internal/GenericConfigurationManagerImpl.ipp index 955b782a3238ed..9b36f341042aa9 100644 --- a/src/include/platform/internal/GenericConfigurationManagerImpl.ipp +++ b/src/include/platform/internal/GenericConfigurationManagerImpl.ipp @@ -27,7 +27,7 @@ #define GENERIC_CONFIGURATION_MANAGER_IMPL_CPP #include -#include +#include #include #include #include diff --git a/src/include/platform/internal/GenericConnectivityManagerImpl.h b/src/include/platform/internal/GenericConnectivityManagerImpl.h index a56e92d17d0d8d..c2aa896bf06411 100644 --- a/src/include/platform/internal/GenericConnectivityManagerImpl.h +++ b/src/include/platform/internal/GenericConnectivityManagerImpl.h @@ -46,6 +46,7 @@ class GenericConnectivityManagerImpl void _SetUserSelectedMode(bool val); uint16_t _GetUserSelectedModeTimeout(); void _SetUserSelectedModeTimeout(uint16_t val); + CHIP_ERROR _DisconnectNetwork(); private: ImplClass * Impl() { return static_cast(this); } @@ -71,6 +72,12 @@ template inline void GenericConnectivityManagerImpl::_SetUserSelectedModeTimeout(uint16_t val) {} +template +inline CHIP_ERROR GenericConnectivityManagerImpl::_DisconnectNetwork() +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + } // namespace Internal } // namespace DeviceLayer } // namespace chip diff --git a/src/lib/address_resolve/tests/BUILD.gn b/src/lib/address_resolve/tests/BUILD.gn index e82e6db2a946b2..994833f21a0020 100644 --- a/src/lib/address_resolve/tests/BUILD.gn +++ b/src/lib/address_resolve/tests/BUILD.gn @@ -14,13 +14,12 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/src/lib/address_resolve/address_resolve.gni") import("${chip_root}/build/chip/chip_test_suite.gni") -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libAddressResolveTests" if (chip_address_resolve_strategy == "default") { @@ -29,8 +28,6 @@ chip_test_suite_using_nltest("tests") { public_deps = [ "${chip_root}/src/lib/address_resolve", - "${chip_root}/src/lib/support:testing_nlunit", "${chip_root}/src/protocols", - "${nlunit_test_root}:nlunit-test", ] } diff --git a/src/lib/address_resolve/tests/TestAddressResolve_DefaultImpl.cpp b/src/lib/address_resolve/tests/TestAddressResolve_DefaultImpl.cpp index f926fc227ea294..74dc3bd81b29d2 100644 --- a/src/lib/address_resolve/tests/TestAddressResolve_DefaultImpl.cpp +++ b/src/lib/address_resolve/tests/TestAddressResolve_DefaultImpl.cpp @@ -13,11 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include - -#include +#include -#include +#include using namespace chip; using namespace chip::AddressResolve; @@ -66,7 +64,7 @@ Transport::PeerAddress GetAddressWithHighScore(uint16_t port = CHIP_PORT, Inet:: return Transport::PeerAddress::UDP(ipAddress, port, interfaceId); } -void TestLookupResult(nlTestSuite * inSuite, void * inContext) +TEST(TestAddressResolveDefaultImpl, TestLookupResult) { ResolveResult lowResult; lowResult.address = GetAddressWithLowScore(); @@ -83,8 +81,8 @@ void TestLookupResult(nlTestSuite * inSuite, void * inContext) IpScore mediumScore = ScoreIpAddress(mediumResult.address.GetIPAddress(), Inet::InterfaceId::Null()); IpScore highScore = ScoreIpAddress(highResult.address.GetIPAddress(), Inet::InterfaceId::Null()); - NL_TEST_ASSERT(inSuite, to_underlying(lowScore) < to_underlying(mediumScore)); - NL_TEST_ASSERT(inSuite, to_underlying(mediumScore) < to_underlying(highScore)); + EXPECT_LT(to_underlying(lowScore), to_underlying(mediumScore)); + EXPECT_LT(to_underlying(mediumScore), to_underlying(highScore)); ResolveResult outResult; @@ -95,20 +93,20 @@ void TestLookupResult(nlTestSuite * inSuite, void * inContext) handle.ResetForLookup(now, request); // Check that no result exists. - NL_TEST_ASSERT(inSuite, !handle.HasLookupResult()); + EXPECT_FALSE(handle.HasLookupResult()); // Fill a single slot. handle.LookupResult(lowResult); // Check that a result exists. - NL_TEST_ASSERT(inSuite, handle.HasLookupResult()); + EXPECT_TRUE(handle.HasLookupResult()); // Check that the result match what has been inserted. outResult = handle.TakeLookupResult(); - NL_TEST_ASSERT(inSuite, lowResult.address == outResult.address); + EXPECT_EQ(lowResult.address, outResult.address); // Check that the result has been consumed properly - NL_TEST_ASSERT(inSuite, !handle.HasLookupResult()); + EXPECT_FALSE(handle.HasLookupResult()); handle.ResetForLookup(now, request); @@ -121,13 +119,13 @@ void TestLookupResult(nlTestSuite * inSuite, void * inContext) // Read back all results and validate that they match the input. for (auto i = 0; i < kNumberOfAvailableSlots; i++) { - NL_TEST_ASSERT(inSuite, handle.HasLookupResult()); + EXPECT_TRUE(handle.HasLookupResult()); outResult = handle.TakeLookupResult(); - NL_TEST_ASSERT(inSuite, lowResult.address == outResult.address); + EXPECT_EQ(lowResult.address, outResult.address); } // Check that the results has been consumed properly. - NL_TEST_ASSERT(inSuite, !handle.HasLookupResult()); + EXPECT_FALSE(handle.HasLookupResult()); handle.ResetForLookup(now, request); @@ -140,13 +138,13 @@ void TestLookupResult(nlTestSuite * inSuite, void * inContext) // Read back all results and validate that they match the input. for (auto i = 0; i < kNumberOfAvailableSlots; i++) { - NL_TEST_ASSERT(inSuite, handle.HasLookupResult()); + EXPECT_TRUE(handle.HasLookupResult()); outResult = handle.TakeLookupResult(); - NL_TEST_ASSERT(inSuite, lowResult.address == outResult.address); + EXPECT_EQ(lowResult.address, outResult.address); } // Check that the results has been consumed properly. - NL_TEST_ASSERT(inSuite, !handle.HasLookupResult()); + EXPECT_FALSE(handle.HasLookupResult()); handle.ResetForLookup(now, request); @@ -158,9 +156,9 @@ void TestLookupResult(nlTestSuite * inSuite, void * inContext) // Add a result with a medium score and ensure it sits at the top. handle.LookupResult(mediumResult); - NL_TEST_ASSERT(inSuite, handle.HasLookupResult()); + EXPECT_TRUE(handle.HasLookupResult()); outResult = handle.TakeLookupResult(); - NL_TEST_ASSERT(inSuite, mediumResult.address == outResult.address); + EXPECT_EQ(mediumResult.address, outResult.address); handle.ResetForLookup(now, request); @@ -173,16 +171,16 @@ void TestLookupResult(nlTestSuite * inSuite, void * inContext) // Add a result with a medium score and a result with a high score and ensure the result with the high score comes first. handle.LookupResult(mediumResult); handle.LookupResult(highResult); - NL_TEST_ASSERT(inSuite, handle.HasLookupResult()); + EXPECT_TRUE(handle.HasLookupResult()); outResult = handle.TakeLookupResult(); - NL_TEST_ASSERT(inSuite, highResult.address == outResult.address); + EXPECT_EQ(highResult.address, outResult.address); if (kNumberOfAvailableSlots > 1) { // Ensure the second result is the medium result. - NL_TEST_ASSERT(inSuite, handle.HasLookupResult()); + EXPECT_TRUE(handle.HasLookupResult()); outResult = handle.TakeLookupResult(); - NL_TEST_ASSERT(inSuite, mediumResult.address == outResult.address); + EXPECT_EQ(mediumResult.address, outResult.address); } if (kNumberOfAvailableSlots > 2) @@ -190,28 +188,13 @@ void TestLookupResult(nlTestSuite * inSuite, void * inContext) // Ensure that all the other results are low results. for (auto i = 2; i < kNumberOfAvailableSlots; i++) { - NL_TEST_ASSERT(inSuite, handle.HasLookupResult()); + EXPECT_TRUE(handle.HasLookupResult()); outResult = handle.TakeLookupResult(); - NL_TEST_ASSERT(inSuite, lowResult.address == outResult.address); + EXPECT_EQ(lowResult.address, outResult.address); } } // Check that the results has been consumed properly. - NL_TEST_ASSERT(inSuite, !handle.HasLookupResult()); + EXPECT_FALSE(handle.HasLookupResult()); } - -const nlTest sTests[] = { - NL_TEST_DEF("TestLookupResult", TestLookupResult), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestAddressResolve_DefaultImpl() -{ - nlTestSuite theSuite = { "AddressResolve_DefaultImpl", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestAddressResolve_DefaultImpl) diff --git a/src/lib/asn1/tests/BUILD.gn b/src/lib/asn1/tests/BUILD.gn index 3439eedde3a759..83c3ec8d3d9e43 100644 --- a/src/lib/asn1/tests/BUILD.gn +++ b/src/lib/asn1/tests/BUILD.gn @@ -14,11 +14,10 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libASN1Tests" test_sources = [ "TestASN1.cpp" ] @@ -26,9 +25,7 @@ chip_test_suite_using_nltest("tests") { public_deps = [ "${chip_root}/src/lib/asn1", "${chip_root}/src/lib/core", - "${chip_root}/src/lib/support:testing_nlunit", "${chip_root}/src/platform", - "${nlunit_test_root}:nlunit-test", ] cflags = [ "-Wconversion" ] diff --git a/src/lib/asn1/tests/TestASN1.cpp b/src/lib/asn1/tests/TestASN1.cpp index 56899892abcc61..db8b1ae8ccf595 100644 --- a/src/lib/asn1/tests/TestASN1.cpp +++ b/src/lib/asn1/tests/TestASN1.cpp @@ -24,7 +24,7 @@ * decode interfaces. * */ -#include +#include #include #include @@ -33,7 +33,6 @@ #include #include #include -#include using namespace chip; using namespace chip::ASN1; @@ -159,7 +158,7 @@ static CHIP_ERROR EncodeASN1TestData(ASN1Writer & writer) return err; } -static void TestASN1_Encode(nlTestSuite * inSuite, void * inContext) +TEST(TestASN1, Encode) { CHIP_ERROR err; static uint8_t buf[2048]; @@ -169,11 +168,11 @@ static void TestASN1_Encode(nlTestSuite * inSuite, void * inContext) writer.Init(buf); err = EncodeASN1TestData(writer); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); encodedLen = writer.GetLengthWritten(); - NL_TEST_ASSERT(inSuite, encodedLen == sizeof(TestASN1_EncodedData)); - NL_TEST_ASSERT(inSuite, memcmp(buf, TestASN1_EncodedData, sizeof(TestASN1_EncodedData)) == 0); + EXPECT_EQ(encodedLen, sizeof(TestASN1_EncodedData)); + EXPECT_EQ(memcmp(buf, TestASN1_EncodedData, sizeof(TestASN1_EncodedData)), 0); #define DUMP_HEX 0 #if DUMP_HEX @@ -187,7 +186,7 @@ static void TestASN1_Encode(nlTestSuite * inSuite, void * inContext) #endif } -static void TestASN1_Decode(nlTestSuite * inSuite, void * inContext) +TEST(TestASN1, Decode) { CHIP_ERROR err = CHIP_NO_ERROR; ASN1Reader reader; @@ -201,17 +200,17 @@ static void TestASN1_Decode(nlTestSuite * inSuite, void * inContext) ASN1_PARSE_ENTER_SEQUENCE { ASN1_PARSE_BOOLEAN(boolVal); - NL_TEST_ASSERT(inSuite, boolVal == kTestVal_01_Bool); + EXPECT_EQ(boolVal, kTestVal_01_Bool); ASN1_PARSE_BOOLEAN(boolVal); - NL_TEST_ASSERT(inSuite, boolVal == kTestVal_02_Bool); + EXPECT_EQ(boolVal, kTestVal_02_Bool); ASN1_PARSE_ENTER_SET {} ASN1_EXIT_SET; ASN1_PARSE_BIT_STRING(bitStringVal); - NL_TEST_ASSERT(inSuite, bitStringVal == kTestVal_03_BitString); + EXPECT_EQ(bitStringVal, kTestVal_03_BitString); ASN1_PARSE_BIT_STRING(bitStringVal); - NL_TEST_ASSERT(inSuite, bitStringVal == kTestVal_04_BitString); + EXPECT_EQ(bitStringVal, kTestVal_04_BitString); ASN1_PARSE_BIT_STRING(bitStringVal); - NL_TEST_ASSERT(inSuite, bitStringVal == kTestVal_05_BitString); + EXPECT_EQ(bitStringVal, kTestVal_05_BitString); ASN1_PARSE_ENTER_SEQUENCE { ASN1_PARSE_ENTER_SEQUENCE @@ -219,65 +218,65 @@ static void TestASN1_Decode(nlTestSuite * inSuite, void * inContext) ASN1_PARSE_ENTER_SEQUENCE { ASN1_PARSE_BIT_STRING(bitStringVal); - NL_TEST_ASSERT(inSuite, bitStringVal == kTestVal_06_BitString); + EXPECT_EQ(bitStringVal, kTestVal_06_BitString); ASN1_PARSE_BIT_STRING(bitStringVal); - NL_TEST_ASSERT(inSuite, bitStringVal == kTestVal_07_BitString); + EXPECT_EQ(bitStringVal, kTestVal_07_BitString); } ASN1_EXIT_SEQUENCE; ASN1_PARSE_BIT_STRING(bitStringVal); - NL_TEST_ASSERT(inSuite, bitStringVal == kTestVal_08_BitString); + EXPECT_EQ(bitStringVal, kTestVal_08_BitString); } ASN1_EXIT_SEQUENCE; ASN1_PARSE_BIT_STRING(bitStringVal); - NL_TEST_ASSERT(inSuite, bitStringVal == kTestVal_09_BitString); + EXPECT_EQ(bitStringVal, kTestVal_09_BitString); } ASN1_EXIT_SEQUENCE; ASN1_PARSE_INTEGER(intVal); - NL_TEST_ASSERT(inSuite, intVal == kTestVal_10_Int); + EXPECT_EQ(intVal, kTestVal_10_Int); ASN1_PARSE_INTEGER(intVal); - NL_TEST_ASSERT(inSuite, intVal == kTestVal_11_Int); + EXPECT_EQ(intVal, kTestVal_11_Int); ASN1_PARSE_INTEGER(intVal); - NL_TEST_ASSERT(inSuite, intVal == kTestVal_12_Int); + EXPECT_EQ(intVal, kTestVal_12_Int); ASN1_PARSE_INTEGER(intVal); - NL_TEST_ASSERT(inSuite, intVal == kTestVal_13_Int); + EXPECT_EQ(intVal, kTestVal_13_Int); ASN1_PARSE_INTEGER(intVal); - NL_TEST_ASSERT(inSuite, intVal == kTestVal_14_Int); + EXPECT_EQ(intVal, kTestVal_14_Int); ASN1_PARSE_INTEGER(intVal); - NL_TEST_ASSERT(inSuite, intVal == kTestVal_15_Int); + EXPECT_EQ(intVal, kTestVal_15_Int); ASN1_PARSE_INTEGER(intVal); - NL_TEST_ASSERT(inSuite, intVal == kTestVal_16_Int); + EXPECT_EQ(intVal, kTestVal_16_Int); ASN1_PARSE_INTEGER(intVal); - NL_TEST_ASSERT(inSuite, intVal == kTestVal_17_Int); + EXPECT_EQ(intVal, kTestVal_17_Int); ASN1_PARSE_INTEGER(intVal); - NL_TEST_ASSERT(inSuite, intVal == kTestVal_18_Int); + EXPECT_EQ(intVal, kTestVal_18_Int); ASN1_PARSE_OBJECT_ID(oidVal); - NL_TEST_ASSERT(inSuite, oidVal == kTestVal_19_OID); + EXPECT_EQ(oidVal, kTestVal_19_OID); ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_OctetString); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == sizeof(kTestVal_20_OctetString)); - NL_TEST_ASSERT(inSuite, memcmp(reader.GetValue(), kTestVal_20_OctetString, sizeof(kTestVal_20_OctetString)) == 0); + EXPECT_EQ(reader.GetValueLen(), sizeof(kTestVal_20_OctetString)); + EXPECT_EQ(memcmp(reader.GetValue(), kTestVal_20_OctetString, sizeof(kTestVal_20_OctetString)), 0); ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_OctetString); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == 1); - NL_TEST_ASSERT(inSuite, reader.GetValue()[0] == kTestVal_20_OctetString[0]); + EXPECT_EQ(reader.GetValueLen(), 1u); + EXPECT_EQ(reader.GetValue()[0], kTestVal_20_OctetString[0]); ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_OctetString); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == 0); + EXPECT_EQ(reader.GetValueLen(), 0u); ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_GeneralString); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == 0); + EXPECT_EQ(reader.GetValueLen(), 0u); ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_PrintableString); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == strlen(kTestVal_21_PrintableString)); - NL_TEST_ASSERT(inSuite, memcmp(reader.GetValue(), kTestVal_21_PrintableString, strlen(kTestVal_21_PrintableString)) == 0); + EXPECT_EQ(reader.GetValueLen(), strlen(kTestVal_21_PrintableString)); + EXPECT_EQ(memcmp(reader.GetValue(), kTestVal_21_PrintableString, strlen(kTestVal_21_PrintableString)), 0); ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_UTF8String); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == strlen(kTestVal_22_UTFString)); - NL_TEST_ASSERT(inSuite, memcmp(reader.GetValue(), kTestVal_22_UTFString, strlen(kTestVal_22_UTFString)) == 0); + EXPECT_EQ(reader.GetValueLen(), strlen(kTestVal_22_UTFString)); + EXPECT_EQ(memcmp(reader.GetValue(), kTestVal_22_UTFString, strlen(kTestVal_22_UTFString)), 0); ASN1_PARSE_ENTER_ENCAPSULATED(kASN1TagClass_Universal, kASN1UniversalTag_OctetString) { ASN1_PARSE_ENTER_SEQUENCE { ASN1_PARSE_OBJECT_ID(oidVal); - NL_TEST_ASSERT(inSuite, oidVal == kTestVal_23_OID); + EXPECT_EQ(oidVal, kTestVal_23_OID); ASN1_PARSE_ENTER_ENCAPSULATED(kASN1TagClass_Universal, kASN1UniversalTag_BitString) { ASN1_PARSE_INTEGER(intVal); - NL_TEST_ASSERT(inSuite, intVal == kTestVal_24_Int); + EXPECT_EQ(intVal, kTestVal_24_Int); } ASN1_EXIT_ENCAPSULATED; } @@ -288,10 +287,10 @@ static void TestASN1_Decode(nlTestSuite * inSuite, void * inContext) ASN1_EXIT_SEQUENCE; exit: - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -static void TestASN1_NullWriter(nlTestSuite * inSuite, void * inContext) +TEST(TestASN1, NullWriter) { CHIP_ERROR err; ASN1Writer writer; @@ -300,24 +299,24 @@ static void TestASN1_NullWriter(nlTestSuite * inSuite, void * inContext) writer.InitNullWriter(); err = EncodeASN1TestData(writer); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); encodedLen = writer.GetLengthWritten(); - NL_TEST_ASSERT(inSuite, encodedLen == 0); + EXPECT_EQ(encodedLen, 0u); // Methods that take a reader should still read from it, // even if the output is suppressed by the null writer. TLVReader emptyTlvReader; emptyTlvReader.Init(ByteSpan()); err = writer.PutBitString(0, emptyTlvReader); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); emptyTlvReader.Init(ByteSpan()); err = writer.PutOctetString(kASN1TagClass_ContextSpecific, 123, emptyTlvReader); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); } -static void TestASN1_ASN1UniversalTime(nlTestSuite * inSuite, void * inContext) +TEST(TestASN1, ASN1UniversalTime) { struct ASN1TimeTestCase { @@ -369,16 +368,19 @@ static void TestASN1_ASN1UniversalTime(nlTestSuite * inSuite, void * inContext) CharSpan testStr = CharSpan(testCase.asn1TimeStr, strlen(testCase.asn1TimeStr)); ASN1UniversalTime result; - NL_TEST_ASSERT(inSuite, result.ImportFrom_ASN1_TIME_string(testStr) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - result.Year == testCase.asn1Time.Year && result.Month == testCase.asn1Time.Month && - result.Day == testCase.asn1Time.Day && result.Hour == testCase.asn1Time.Hour && - result.Minute == testCase.asn1Time.Minute && result.Second == testCase.asn1Time.Second); + EXPECT_EQ(result.ImportFrom_ASN1_TIME_string(testStr), CHIP_NO_ERROR); + + EXPECT_EQ(result.Year, testCase.asn1Time.Year); + EXPECT_EQ(result.Month, testCase.asn1Time.Month); + EXPECT_EQ(result.Day, testCase.asn1Time.Day); + EXPECT_EQ(result.Hour, testCase.asn1Time.Hour); + EXPECT_EQ(result.Minute, testCase.asn1Time.Minute); + EXPECT_EQ(result.Second, testCase.asn1Time.Second); char buf[ASN1UniversalTime::kASN1TimeStringMaxLength]; MutableCharSpan resultTimeStr(buf); - NL_TEST_ASSERT(inSuite, result.ExportTo_ASN1_TIME_string(resultTimeStr) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, resultTimeStr.data_equal(testStr)); + EXPECT_EQ(result.ExportTo_ASN1_TIME_string(resultTimeStr), CHIP_NO_ERROR); + EXPECT_TRUE(resultTimeStr.data_equal(testStr)); } for (auto & testCase : sASN1TimeErrorTestCases) @@ -386,11 +388,11 @@ static void TestASN1_ASN1UniversalTime(nlTestSuite * inSuite, void * inContext) CharSpan testStr = CharSpan(testCase.asn1TimeStr, strlen(testCase.asn1TimeStr)); ASN1UniversalTime result; - NL_TEST_ASSERT(inSuite, result.ImportFrom_ASN1_TIME_string(testStr) == testCase.mExpectedResult); + EXPECT_EQ(result.ImportFrom_ASN1_TIME_string(testStr), testCase.mExpectedResult); } } -static void TestASN1_ObjectID(nlTestSuite * inSuite, void * inContext) +TEST(TestASN1, ObjectID) { CHIP_ERROR err; static uint8_t buf[2048]; @@ -412,7 +414,7 @@ static void TestASN1_ObjectID(nlTestSuite * inSuite, void * inContext) ASN1_END_SEQUENCE; encodedLen = writer.GetLengthWritten(); - NL_TEST_ASSERT(inSuite, encodedLen > 0); + EXPECT_GT(encodedLen, 0u); reader.Init(buf, encodedLen); @@ -420,41 +422,37 @@ static void TestASN1_ObjectID(nlTestSuite * inSuite, void * inContext) ASN1_PARSE_ENTER_SEQUENCE { ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_ObjectId); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == sizeof(sOID_AttributeType_ChipNodeId)); - NL_TEST_ASSERT(inSuite, - memcmp(reader.GetValue(), sOID_AttributeType_ChipNodeId, sizeof(sOID_AttributeType_ChipNodeId)) == 0); + EXPECT_EQ(reader.GetValueLen(), sizeof(sOID_AttributeType_ChipNodeId)); + EXPECT_EQ(memcmp(reader.GetValue(), sOID_AttributeType_ChipNodeId, sizeof(sOID_AttributeType_ChipNodeId)), 0); ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_ObjectId); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == sizeof(sOID_SigAlgo_ECDSAWithSHA256)); - NL_TEST_ASSERT(inSuite, memcmp(reader.GetValue(), sOID_SigAlgo_ECDSAWithSHA256, sizeof(sOID_SigAlgo_ECDSAWithSHA256)) == 0); + EXPECT_EQ(reader.GetValueLen(), sizeof(sOID_SigAlgo_ECDSAWithSHA256)); + EXPECT_EQ(memcmp(reader.GetValue(), sOID_SigAlgo_ECDSAWithSHA256, sizeof(sOID_SigAlgo_ECDSAWithSHA256)), 0); ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_ObjectId); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == sizeof(sOID_EllipticCurve_prime256v1)); - NL_TEST_ASSERT(inSuite, - memcmp(reader.GetValue(), sOID_EllipticCurve_prime256v1, sizeof(sOID_EllipticCurve_prime256v1)) == 0); + EXPECT_EQ(reader.GetValueLen(), sizeof(sOID_EllipticCurve_prime256v1)); + EXPECT_EQ(memcmp(reader.GetValue(), sOID_EllipticCurve_prime256v1, sizeof(sOID_EllipticCurve_prime256v1)), 0); ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_ObjectId); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == sizeof(sOID_Extension_AuthorityKeyIdentifier)); - NL_TEST_ASSERT( - inSuite, - memcmp(reader.GetValue(), sOID_Extension_AuthorityKeyIdentifier, sizeof(sOID_Extension_AuthorityKeyIdentifier)) == 0); + EXPECT_EQ(reader.GetValueLen(), sizeof(sOID_Extension_AuthorityKeyIdentifier)); + EXPECT_EQ(memcmp(reader.GetValue(), sOID_Extension_AuthorityKeyIdentifier, sizeof(sOID_Extension_AuthorityKeyIdentifier)), + 0); ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_ObjectId); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == sizeof(sOID_Extension_BasicConstraints)); - NL_TEST_ASSERT(inSuite, - memcmp(reader.GetValue(), sOID_Extension_BasicConstraints, sizeof(sOID_Extension_BasicConstraints)) == 0); + EXPECT_EQ(reader.GetValueLen(), sizeof(sOID_Extension_BasicConstraints)); + EXPECT_EQ(memcmp(reader.GetValue(), sOID_Extension_BasicConstraints, sizeof(sOID_Extension_BasicConstraints)), 0); ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_ObjectId); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == sizeof(sOID_KeyPurpose_ServerAuth)); - NL_TEST_ASSERT(inSuite, memcmp(reader.GetValue(), sOID_KeyPurpose_ServerAuth, sizeof(sOID_KeyPurpose_ServerAuth)) == 0); + EXPECT_EQ(reader.GetValueLen(), sizeof(sOID_KeyPurpose_ServerAuth)); + EXPECT_EQ(memcmp(reader.GetValue(), sOID_KeyPurpose_ServerAuth, sizeof(sOID_KeyPurpose_ServerAuth)), 0); } ASN1_EXIT_SEQUENCE; exit: - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -static void TestASN1_FromTLVReader(nlTestSuite * inSuite, void * inContext) +TEST(TestASN1, FromTLVReader) { CHIP_ERROR err; static uint8_t tlvBuf[128]; @@ -474,23 +472,23 @@ static void TestASN1_FromTLVReader(nlTestSuite * inSuite, void * inContext) tlvWriter.Init(tlvEncodedData); err = tlvWriter.StartContainer(AnonymousTag(), kTLVType_Structure, outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = tlvWriter.PutBytes(TLV::ContextTag(1), kTestVal_20_OctetString, sizeof(kTestVal_20_OctetString)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = tlvWriter.PutBytes(TLV::ContextTag(2), kTestVal_09_BitString_AsOctetString, sizeof(kTestVal_09_BitString_AsOctetString)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = tlvWriter.PutString(TLV::ContextTag(3), kTestVal_21_PrintableString); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = tlvWriter.EndContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = tlvWriter.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } // Construct first ASN1 SEQUESNCE using values. @@ -504,7 +502,7 @@ static void TestASN1_FromTLVReader(nlTestSuite * inSuite, void * inContext) err = writer.PutValue(kASN1TagClass_Universal, kASN1UniversalTag_PrintableString, false, reinterpret_cast(kTestVal_21_PrintableString), static_cast(strlen(kTestVal_21_PrintableString))); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } ASN1_END_SEQUENCE; asn1EncodedData1.reduce_size(writer.GetLengthWritten()); @@ -515,84 +513,58 @@ static void TestASN1_FromTLVReader(nlTestSuite * inSuite, void * inContext) ASN1_START_SEQUENCE { err = tlvReader.Next(kTLVType_Structure, AnonymousTag()); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = tlvReader.EnterContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = tlvReader.Next(kTLVType_ByteString, ContextTag(1)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.PutOctetString(kASN1TagClass_Universal, kASN1UniversalTag_OctetString, tlvReader); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = tlvReader.Next(kTLVType_ByteString, ContextTag(2)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.PutBitString(6, tlvReader); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = tlvReader.Next(kTLVType_UTF8String, ContextTag(3)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.PutValue(kASN1TagClass_Universal, kASN1UniversalTag_PrintableString, false, tlvReader); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = tlvReader.ExitContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } ASN1_END_SEQUENCE; asn1EncodedData2.reduce_size(writer.GetLengthWritten()); // Compare two ASN1 SEQUENCEs. - NL_TEST_ASSERT(inSuite, asn1EncodedData2.data_equal(asn1EncodedData1)); + EXPECT_TRUE(asn1EncodedData2.data_equal(asn1EncodedData1)); // Initialize ASN1Reader and test data. reader.Init(asn1EncodedData2); ASN1_PARSE_ENTER_SEQUENCE { ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_OctetString); - NL_TEST_ASSERT(inSuite, reader.GetValue() != nullptr); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == sizeof(kTestVal_20_OctetString)); - NL_TEST_ASSERT(inSuite, memcmp(reader.GetValue(), kTestVal_20_OctetString, sizeof(kTestVal_20_OctetString)) == 0); + ASSERT_NE(reader.GetValue(), nullptr); + EXPECT_EQ(reader.GetValueLen(), sizeof(kTestVal_20_OctetString)); + EXPECT_EQ(memcmp(reader.GetValue(), kTestVal_20_OctetString, sizeof(kTestVal_20_OctetString)), 0); uint32_t val; ASN1_PARSE_BIT_STRING(val); - NL_TEST_ASSERT(inSuite, val == kTestVal_09_BitString); + EXPECT_EQ(val, kTestVal_09_BitString); ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_PrintableString); - NL_TEST_ASSERT(inSuite, reader.GetValue() != nullptr); - NL_TEST_ASSERT(inSuite, reader.GetValueLen() == strlen(kTestVal_21_PrintableString)); - NL_TEST_ASSERT(inSuite, memcmp(reader.GetValue(), kTestVal_21_PrintableString, strlen(kTestVal_21_PrintableString)) == 0); + ASSERT_NE(reader.GetValue(), nullptr); + EXPECT_EQ(reader.GetValueLen(), strlen(kTestVal_21_PrintableString)); + EXPECT_EQ(memcmp(reader.GetValue(), kTestVal_21_PrintableString, strlen(kTestVal_21_PrintableString)), 0); } ASN1_EXIT_SEQUENCE; exit: - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } - -/** - * Test Suite. It lists all the test functions. - */ - -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("Test ASN1 encoding macros", TestASN1_Encode), - NL_TEST_DEF("Test ASN1 decoding macros", TestASN1_Decode), - NL_TEST_DEF("Test ASN1 NULL writer", TestASN1_NullWriter), - NL_TEST_DEF("Test ASN1 universal time", TestASN1_ASN1UniversalTime), - NL_TEST_DEF("Test ASN1 Object IDs", TestASN1_ObjectID), - NL_TEST_DEF("Test ASN1 Init with ByteSpan", TestASN1_FromTLVReader), - NL_TEST_SENTINEL() -}; -// clang-format on - -int TestASN1() -{ - nlTestSuite theSuite = { "Support-ASN1", &sTests[0], nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestASN1); diff --git a/src/lib/core/CHIPCore.h b/src/lib/core/CHIPCore.h index bac6e473f39d43..6d223b2040057b 100644 --- a/src/lib/core/CHIPCore.h +++ b/src/lib/core/CHIPCore.h @@ -29,10 +29,8 @@ #include -#include - #if CONFIG_NETWORK_LAYER_BLE -#include +#include #endif // CONFIG_NETWORK_LAYER_BLE #define CHIP_CORE_IDENTITY "chip-core" diff --git a/src/lib/core/Optional.h b/src/lib/core/Optional.h index 3d509f544c97cd..a8f544ce1d9819 100644 --- a/src/lib/core/Optional.h +++ b/src/lib/core/Optional.h @@ -24,6 +24,7 @@ #pragma once #include +#include #include #include @@ -161,6 +162,18 @@ class Optional new (&mValue.mData) T(value); } + constexpr void SetValue(std::optional & value) + { + if (value.has_value()) + { + SetValue(*value); + } + else + { + ClearValue(); + } + } + /** Make the optional contain a specific value */ constexpr void SetValue(T && value) { @@ -211,6 +224,12 @@ class Optional bool operator==(const T & other) const { return HasValue() && Value() == other; } bool operator!=(const T & other) const { return !(*this == other); } + std::optional std_optional() const + { + VerifyOrReturnValue(HasValue(), std::nullopt); + return std::make_optional(Value()); + } + /** Convenience method to create an optional without a valid value. */ static Optional Missing() { return Optional(); } @@ -237,6 +256,13 @@ constexpr Optional> MakeOptional(T && value) return Optional>(InPlace, std::forward(value)); } +template +constexpr Optional FromStdOptional(const std::optional & value) +{ + VerifyOrReturnValue(value.has_value(), NullOptional); + return MakeOptional(*value); +} + template constexpr Optional MakeOptional(Args &&... args) { diff --git a/src/lib/core/tests/BUILD.gn b/src/lib/core/tests/BUILD.gn index f04aa91c9baa5e..4c65db115ac399 100644 --- a/src/lib/core/tests/BUILD.gn +++ b/src/lib/core/tests/BUILD.gn @@ -14,12 +14,11 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") import("${chip_root}/build/chip/fuzz_test.gni") -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libCoreTests" test_sources = [ @@ -40,9 +39,7 @@ chip_test_suite_using_nltest("tests") { "${chip_root}/src/lib/core", "${chip_root}/src/lib/core:vectortlv", "${chip_root}/src/lib/support:test_utils", - "${chip_root}/src/lib/support:testing_nlunit", "${chip_root}/src/platform", - "${nlunit_test_root}:nlunit-test", ] } diff --git a/src/lib/core/tests/TestCATValues.cpp b/src/lib/core/tests/TestCATValues.cpp index 86551d03130c58..a8563905ecb648 100644 --- a/src/lib/core/tests/TestCATValues.cpp +++ b/src/lib/core/tests/TestCATValues.cpp @@ -16,14 +16,13 @@ * limitations under the License. */ -#include -#include +#include #include using namespace chip; -void TestEqualityOperator(nlTestSuite * inSuite, void * inContext) +TEST(TestCATValues, TestEqualityOperator) { { auto a = CATValues{ { 0x1111'0001, 0x2222'0002, 0x3333'0003 } }; @@ -37,7 +36,7 @@ void TestEqualityOperator(nlTestSuite * inSuite, void * inContext) { for (auto & inner : candidates) { - NL_TEST_ASSERT(inSuite, inner == outer); + EXPECT_EQ(inner, outer); } } } @@ -49,7 +48,7 @@ void TestEqualityOperator(nlTestSuite * inSuite, void * inContext) { for (auto & inner : candidates) { - NL_TEST_ASSERT(inSuite, inner == outer); + EXPECT_EQ(inner, outer); } } } @@ -65,13 +64,13 @@ void TestEqualityOperator(nlTestSuite * inSuite, void * inContext) { for (auto & inner : candidates) { - NL_TEST_ASSERT(inSuite, inner == outer); + EXPECT_EQ(inner, outer); } } } } -void TestInequalityOperator(nlTestSuite * inSuite, void * inContext) +TEST(TestCATValues, TestInequalityOperator) { auto a = CATValues{ { 0x1111'0001 } }; auto b = CATValues{ { 0x1111'0001, 0x2222'0002 } }; @@ -103,12 +102,12 @@ void TestInequalityOperator(nlTestSuite * inSuite, void * inContext) { continue; } - NL_TEST_ASSERT(inSuite, inner != outer); + EXPECT_NE(inner, outer); } } } -void TestValidity(nlTestSuite * inSuite, void * inContext) +TEST(TestCATValues, TestValidity) { { auto a = CATValues{ { 0x1111'0001, 0x2222'0002, 0x3333'0003 } }; @@ -119,7 +118,7 @@ void TestValidity(nlTestSuite * inSuite, void * inContext) CATValues validCandidates[] = { a, b, c, d, e }; for (auto & candidate : validCandidates) { - NL_TEST_ASSERT(inSuite, candidate.AreValid()); + EXPECT_TRUE(candidate.AreValid()); } } @@ -130,117 +129,69 @@ void TestValidity(nlTestSuite * inSuite, void * inContext) CATValues invalidCandidates[] = { versionZero1, versionZero2, collidingId }; for (auto & candidate : invalidCandidates) { - NL_TEST_ASSERT(inSuite, !candidate.AreValid()); + EXPECT_FALSE(candidate.AreValid()); } } } -void TestMembership(nlTestSuite * inSuite, void * inContext) +TEST(TestCATValues, TestMembership) { auto a = CATValues{ { 0x1111'0001 } }; auto b = CATValues{ { 0x1111'0001, 0x2222'0002 } }; auto c = CATValues{ { 0x1111'0001, 0x2222'0002, 0x3333'0003 } }; - NL_TEST_ASSERT(inSuite, a.Contains(0x1111'0001)); - NL_TEST_ASSERT(inSuite, a.GetNumTagsPresent() == 1); - NL_TEST_ASSERT(inSuite, !a.Contains(0x1111'0002)); - NL_TEST_ASSERT(inSuite, !a.Contains(0x2222'0002)); - NL_TEST_ASSERT(inSuite, a.ContainsIdentifier(0x1111)); - NL_TEST_ASSERT(inSuite, !a.ContainsIdentifier(0x2222)); - NL_TEST_ASSERT(inSuite, a.AreValid()); - - NL_TEST_ASSERT(inSuite, b.Contains(0x1111'0001)); - NL_TEST_ASSERT(inSuite, b.Contains(0x2222'0002)); - NL_TEST_ASSERT(inSuite, b.GetNumTagsPresent() == 2); - NL_TEST_ASSERT(inSuite, b.ContainsIdentifier(0x1111)); - NL_TEST_ASSERT(inSuite, b.ContainsIdentifier(0x2222)); - NL_TEST_ASSERT(inSuite, b.AreValid()); - - NL_TEST_ASSERT(inSuite, c.Contains(0x1111'0001)); - NL_TEST_ASSERT(inSuite, c.Contains(0x2222'0002)); - NL_TEST_ASSERT(inSuite, c.Contains(0x3333'0003)); - NL_TEST_ASSERT(inSuite, c.GetNumTagsPresent() == 3); - NL_TEST_ASSERT(inSuite, c.ContainsIdentifier(0x1111)); - NL_TEST_ASSERT(inSuite, c.ContainsIdentifier(0x2222)); - NL_TEST_ASSERT(inSuite, c.ContainsIdentifier(0x3333)); - NL_TEST_ASSERT(inSuite, c.AreValid()); + EXPECT_TRUE(a.Contains(0x1111'0001)); + EXPECT_EQ(a.GetNumTagsPresent(), 1u); + EXPECT_FALSE(a.Contains(0x1111'0002)); + EXPECT_FALSE(a.Contains(0x2222'0002)); + EXPECT_TRUE(a.ContainsIdentifier(0x1111)); + EXPECT_FALSE(a.ContainsIdentifier(0x2222)); + EXPECT_TRUE(a.AreValid()); + + EXPECT_TRUE(b.Contains(0x1111'0001)); + EXPECT_TRUE(b.Contains(0x2222'0002)); + EXPECT_EQ(b.GetNumTagsPresent(), 2u); + EXPECT_TRUE(b.ContainsIdentifier(0x1111)); + EXPECT_TRUE(b.ContainsIdentifier(0x2222)); + EXPECT_TRUE(b.AreValid()); + + EXPECT_TRUE(c.Contains(0x1111'0001)); + EXPECT_TRUE(c.Contains(0x2222'0002)); + EXPECT_TRUE(c.Contains(0x3333'0003)); + EXPECT_EQ(c.GetNumTagsPresent(), 3u); + EXPECT_TRUE(c.ContainsIdentifier(0x1111)); + EXPECT_TRUE(c.ContainsIdentifier(0x2222)); + EXPECT_TRUE(c.ContainsIdentifier(0x3333)); + EXPECT_TRUE(c.AreValid()); } -void TestSubjectMatching(nlTestSuite * inSuite, void * inContext) +TEST(TestCATValues, TestSubjectMatching) { // Check operational node IDs don't match auto a = CATValues{ { 0x2222'0002 } }; - NL_TEST_ASSERT(inSuite, !a.CheckSubjectAgainstCATs(static_cast(0x0001'0002'0003'0004ull))); - NL_TEST_ASSERT(inSuite, !a.CheckSubjectAgainstCATs(static_cast(0x0001'0002'2222'0002ull))); + EXPECT_FALSE(a.CheckSubjectAgainstCATs(static_cast(0x0001'0002'0003'0004ull))); + EXPECT_FALSE(a.CheckSubjectAgainstCATs(static_cast(0x0001'0002'2222'0002ull))); auto b = CATValues{ { 0x1111'0001 } }; - NL_TEST_ASSERT(inSuite, b.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'1111'0001ull))); - NL_TEST_ASSERT(inSuite, !b.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'1111'0002ull))); + EXPECT_TRUE(b.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'1111'0001ull))); + EXPECT_FALSE(b.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'1111'0002ull))); auto c = CATValues{ { 0x1111'0001, 0x2222'0002 } }; - NL_TEST_ASSERT(inSuite, c.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'2222'0001ull))); - NL_TEST_ASSERT(inSuite, c.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'2222'0002ull))); - NL_TEST_ASSERT(inSuite, !c.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'2222'0003ull))); + EXPECT_TRUE(c.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'2222'0001ull))); + EXPECT_TRUE(c.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'2222'0002ull))); + EXPECT_FALSE(c.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'2222'0003ull))); auto d = CATValues{ { 0x1111'0001, 0x2222'0002, 0x3333'0003 } }; - NL_TEST_ASSERT(inSuite, d.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0001ull))); - NL_TEST_ASSERT(inSuite, d.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0002ull))); - NL_TEST_ASSERT(inSuite, d.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0003ull))); - NL_TEST_ASSERT(inSuite, !d.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0004ull))); - NL_TEST_ASSERT(inSuite, !d.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'ffffull))); + EXPECT_TRUE(d.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0001ull))); + EXPECT_TRUE(d.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0002ull))); + EXPECT_TRUE(d.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0003ull))); + EXPECT_FALSE(d.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0004ull))); + EXPECT_FALSE(d.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'ffffull))); auto e = CATValues{ { 0x1111'0001, 0x2222'0002, 0x3333'ffff } }; - NL_TEST_ASSERT(inSuite, e.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0001ull))); - NL_TEST_ASSERT(inSuite, e.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0002ull))); - NL_TEST_ASSERT(inSuite, e.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0003ull))); - NL_TEST_ASSERT(inSuite, e.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0004ull))); - NL_TEST_ASSERT(inSuite, e.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'ffffull))); + EXPECT_TRUE(e.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0001ull))); + EXPECT_TRUE(e.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0002ull))); + EXPECT_TRUE(e.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0003ull))); + EXPECT_TRUE(e.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'0004ull))); + EXPECT_TRUE(e.CheckSubjectAgainstCATs(static_cast(0xFFFF'FFFD'3333'ffffull))); } -// Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("Equality operator", TestEqualityOperator), - NL_TEST_DEF("Inequality operator", TestInequalityOperator), - NL_TEST_DEF("Validity checks", TestValidity), - NL_TEST_DEF("Set operations", TestMembership), - NL_TEST_DEF("Subject matching for ACL", TestSubjectMatching), - NL_TEST_SENTINEL() -}; -// clang-format on - -int TestCATValues_Setup(void * inContext) -{ - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int TestCATValues_Teardown(void * inContext) -{ - return SUCCESS; -} - -int TestCATValues() -{ - // clang-format off - nlTestSuite theSuite = - { - "CATValues", - &sTests[0], - TestCATValues_Setup, - TestCATValues_Teardown, - }; - // clang-format on - - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestCATValues) diff --git a/src/lib/core/tests/TestCHIPCallback.cpp b/src/lib/core/tests/TestCHIPCallback.cpp index fe12cfd57303b7..111a8a73671802 100644 --- a/src/lib/core/tests/TestCHIPCallback.cpp +++ b/src/lib/core/tests/TestCHIPCallback.cpp @@ -21,11 +21,11 @@ * This file implements a test for CHIP Callback * */ +#include + #include #include -#include - -#include +#include using namespace chip::Callback; @@ -87,7 +87,14 @@ static void canceler(Cancelable * ca) ca->Cancel(); } -static void ResumerTest(nlTestSuite * inSuite, void * inContext) +class TestCHIPCallback : public ::testing::Test +{ +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestCHIPCallback, ResumerTest) { int n = 1; Callback<> cb(reinterpret_cast(increment), &n); @@ -99,21 +106,21 @@ static void ResumerTest(nlTestSuite * inSuite, void * inContext) resumer.Dispatch(); resumer.Resume(&cb); resumer.Dispatch(); - NL_TEST_ASSERT(inSuite, n == 3); + EXPECT_EQ(n, 3); n = 1; // test cb->Cancel() cancels resumer.Resume(&cb); cb.Cancel(); resumer.Dispatch(); - NL_TEST_ASSERT(inSuite, n == 1); + EXPECT_EQ(n, 1); n = 1; // Cancel cb before Dispatch() gets around to us (tests FIFO *and* cancel() from readylist) resumer.Resume(&cancelcb); resumer.Resume(&cb); resumer.Dispatch(); - NL_TEST_ASSERT(inSuite, n == 1); + EXPECT_EQ(n, 1); n = 1; // 2nd Resume() cancels first registration @@ -121,7 +128,7 @@ static void ResumerTest(nlTestSuite * inSuite, void * inContext) resumer.Resume(&cb); // cancels previous registration resumer.Dispatch(); // runs the list resumer.Dispatch(); // runs an empty list - NL_TEST_ASSERT(inSuite, n == 2); + EXPECT_EQ(n, 2); n = 1; // Resume() during Dispatch() runs only once, but enqueues for next dispatch @@ -130,9 +137,9 @@ static void ResumerTest(nlTestSuite * inSuite, void * inContext) resumer.Resume(&cb); resumer.Resume(&resumecb); resumer.Dispatch(); - NL_TEST_ASSERT(inSuite, n == 2); + EXPECT_EQ(n, 2); resumer.Dispatch(); - NL_TEST_ASSERT(inSuite, n == 3); + EXPECT_EQ(n, 3); Callback<> * pcb = chip::Platform::New>(reinterpret_cast(increment), &n); @@ -140,12 +147,12 @@ static void ResumerTest(nlTestSuite * inSuite, void * inContext) // cancel on destruct resumer.Resume(pcb); resumer.Dispatch(); - NL_TEST_ASSERT(inSuite, n == 2); + EXPECT_EQ(n, 2); resumer.Resume(pcb); chip::Platform::Delete(pcb); resumer.Dispatch(); - NL_TEST_ASSERT(inSuite, n == 2); + EXPECT_EQ(n, 2); } /** @@ -190,7 +197,7 @@ static void increment_by(int * n, int by) *n += by; } -static void NotifierTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCHIPCallback, NotifierTest) { int n = 1; Callback cb(reinterpret_cast(increment_by), &n); @@ -205,68 +212,15 @@ static void NotifierTest(nlTestSuite * inSuite, void * inContext) notifier.Register(&cb); notifier.Notify(1); notifier.Notify(8); - NL_TEST_ASSERT(inSuite, n == 10); + EXPECT_EQ(n, 10); n = 1; // Cancel cb before Dispatch() gets around to us (tests FIFO *and* cancel() from readylist) notifier.Register(&cancelcb); notifier.Register(&cb); notifier.Notify(8); - NL_TEST_ASSERT(inSuite, n == 1); + EXPECT_EQ(n, 1); cb.Cancel(); cancelcb.Cancel(); } - -/** - * Set up the test suite. - */ -int TestCHIPCallback_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int TestCHIPCallback_Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -/** - * Test Suite. It lists all the test functions. - */ - -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("ResumerTest", ResumerTest), - NL_TEST_DEF("NotifierTest", NotifierTest), - - NL_TEST_SENTINEL() -}; -// clang-format on - -int TestCHIPCallback() -{ - // clang-format off - nlTestSuite theSuite = - { - "CHIPCallback", - &sTests[0], - TestCHIPCallback_Setup, - TestCHIPCallback_Teardown - }; - // clang-format on - - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestCHIPCallback) diff --git a/src/lib/core/tests/TestCHIPErrorStr.cpp b/src/lib/core/tests/TestCHIPErrorStr.cpp index 8f21a2e9ec3397..730a4843e14a45 100644 --- a/src/lib/core/tests/TestCHIPErrorStr.cpp +++ b/src/lib/core/tests/TestCHIPErrorStr.cpp @@ -28,12 +28,10 @@ #include #include +#include + #include #include -#include -#include - -#include using namespace chip; @@ -169,7 +167,7 @@ static const CHIP_ERROR kTestElements[] = }; // clang-format on -static void CheckCoreErrorStr(nlTestSuite * inSuite, void * inContext) +TEST(TestCHIPErrorStr, CheckCoreErrorStr) { // Register the layer error formatter @@ -183,52 +181,19 @@ static void CheckCoreErrorStr(nlTestSuite * inSuite, void * inContext) // Assert that the error string contains the error number in hex. snprintf(expectedText, sizeof(expectedText), "%08" PRIX32, static_cast(err.AsInteger())); - NL_TEST_ASSERT(inSuite, (strstr(errStr, expectedText) != nullptr)); + EXPECT_TRUE((strstr(errStr, expectedText) != nullptr)); #if !CHIP_CONFIG_SHORT_ERROR_STR // Assert that the error string contains a description, which is signaled // by a presence of a colon proceeding the description. - NL_TEST_ASSERT(inSuite, (strchr(errStr, ':') != nullptr)); + EXPECT_TRUE((strchr(errStr, ':') != nullptr)); #endif // !CHIP_CONFIG_SHORT_ERROR_STR #if CHIP_CONFIG_ERROR_SOURCE // GetFile() should be relative to ${chip_root} char const * const file = err.GetFile(); - NL_TEST_EXIT_ON_FAILED_ASSERT(inSuite, file != nullptr); - NL_TEST_ASSERT(inSuite, strstr(file, "src/lib/core/") == file); + ASSERT_NE(file, nullptr); + EXPECT_EQ(strstr(file, "src/lib/core/"), file); #endif // CHIP_CONFIG_ERROR_SOURCE } } - -/** - * Test Suite. It lists all the test functions. - */ - -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("CoreErrorStr", CheckCoreErrorStr), - - NL_TEST_SENTINEL() -}; -// clang-format on - -int TestCHIPErrorStr() -{ - // clang-format off - nlTestSuite theSuite = - { - "Test CHIP_ERROR string conversions", - &sTests[0], - nullptr, - nullptr - }; - // clang-format on - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr); - - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestCHIPErrorStr) diff --git a/src/lib/core/tests/TestOTAImageHeader.cpp b/src/lib/core/tests/TestOTAImageHeader.cpp index 0a05799c74ca35..8413dbdce36f0e 100644 --- a/src/lib/core/tests/TestOTAImageHeader.cpp +++ b/src/lib/core/tests/TestOTAImageHeader.cpp @@ -17,9 +17,8 @@ */ #include -#include -#include +#include using namespace chip; @@ -70,42 +69,49 @@ const uint8_t kMinOtaImageWithoutVendor[] = { 0x1e, 0xf1, 0xee, 0x1b, 0x44, 0x00 0x42, 0x36, 0x67, 0xdb, 0xb7, 0x3b, 0x6e, 0x15, 0x45, 0x4f, 0x0e, 0xb1, 0xab, 0xd4, 0x59, 0x7f, 0x9a, 0x1b, 0x07, 0x8e, 0x3f, 0x5b, 0x5a, 0x6b, 0xc7, 0x18 }; -void TestHappyPath(nlTestSuite * inSuite, void * inContext) +class TestOTAImageHeader : public ::testing::Test +{ +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestOTAImageHeader, TestHappyPath) { ByteSpan buffer(kOtaImage); OTAImageHeader header; OTAImageHeaderParser parser; parser.Init(); - NL_TEST_ASSERT(inSuite, parser.AccumulateAndDecode(buffer, header) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, parser.IsInitialized()); - NL_TEST_ASSERT(inSuite, buffer.size() == strlen("test payload")); - NL_TEST_ASSERT(inSuite, header.mVendorId == 0xDEAD); - NL_TEST_ASSERT(inSuite, header.mProductId == 0xBEEF); - NL_TEST_ASSERT(inSuite, header.mSoftwareVersion == 0xFFFFFFFF); - NL_TEST_ASSERT(inSuite, header.mSoftwareVersionString.data_equal("1.0"_span)); - NL_TEST_ASSERT(inSuite, header.mPayloadSize == strlen("test payload")); - NL_TEST_ASSERT(inSuite, header.mMinApplicableVersion.HasValue()); - NL_TEST_ASSERT(inSuite, header.mMinApplicableVersion.Value() == 1); - NL_TEST_ASSERT(inSuite, header.mMaxApplicableVersion.HasValue()); - NL_TEST_ASSERT(inSuite, header.mMaxApplicableVersion.Value() == 2); - NL_TEST_ASSERT(inSuite, header.mReleaseNotesURL.data_equal("https://rn"_span)); - NL_TEST_ASSERT(inSuite, header.mImageDigestType == OTAImageDigestType::kSha256); - NL_TEST_ASSERT(inSuite, header.mImageDigest.size() == 256 / 8); + EXPECT_EQ(parser.AccumulateAndDecode(buffer, header), CHIP_NO_ERROR); + EXPECT_TRUE(parser.IsInitialized()); + EXPECT_EQ(buffer.size(), strlen("test payload")); + EXPECT_EQ(header.mVendorId, 0xDEAD); + EXPECT_EQ(header.mProductId, 0xBEEF); + EXPECT_EQ(header.mSoftwareVersion, 0xFFFFFFFF); + EXPECT_TRUE(header.mSoftwareVersionString.data_equal("1.0"_span)); + EXPECT_EQ(header.mPayloadSize, strlen("test payload")); + EXPECT_TRUE(header.mMinApplicableVersion.HasValue()); + EXPECT_EQ(header.mMinApplicableVersion.Value(), 1u); + EXPECT_TRUE(header.mMaxApplicableVersion.HasValue()); + EXPECT_EQ(header.mMaxApplicableVersion.Value(), 2u); + EXPECT_TRUE(header.mReleaseNotesURL.data_equal("https://rn"_span)); + EXPECT_EQ(header.mImageDigestType, OTAImageDigestType::kSha256); + EXPECT_EQ(header.mImageDigest.size(), 256u / 8); } -void TestEmptyBuffer(nlTestSuite * inSuite, void * inContext) +TEST_F(TestOTAImageHeader, TestEmptyBuffer) { ByteSpan buffer{}; OTAImageHeader header; OTAImageHeaderParser parser; parser.Init(); - NL_TEST_ASSERT(inSuite, parser.AccumulateAndDecode(buffer, header) == CHIP_ERROR_BUFFER_TOO_SMALL); - NL_TEST_ASSERT(inSuite, parser.IsInitialized()); + EXPECT_EQ(parser.AccumulateAndDecode(buffer, header), CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_TRUE(parser.IsInitialized()); } -void TestInvalidFileIdentifier(nlTestSuite * inSuite, void * inContext) +TEST_F(TestOTAImageHeader, TestInvalidFileIdentifier) { static const uint8_t otaImage[] = { 0x1e, 0xf1, 0xee, 0x1c, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; @@ -115,37 +121,37 @@ void TestInvalidFileIdentifier(nlTestSuite * inSuite, void * inContext) OTAImageHeaderParser parser; parser.Init(); - NL_TEST_ASSERT(inSuite, parser.AccumulateAndDecode(buffer, header) == CHIP_ERROR_INVALID_FILE_IDENTIFIER); - NL_TEST_ASSERT(inSuite, !parser.IsInitialized()); + EXPECT_EQ(parser.AccumulateAndDecode(buffer, header), CHIP_ERROR_INVALID_FILE_IDENTIFIER); + EXPECT_FALSE(parser.IsInitialized()); } -void TestTooSmallHeader(nlTestSuite * inSuite, void * inContext) +TEST_F(TestOTAImageHeader, TestTooSmallHeader) { ByteSpan buffer(kMinOtaImage); OTAImageHeader header; OTAImageHeaderParser parser; parser.Init(); - NL_TEST_ASSERT(inSuite, parser.AccumulateAndDecode(buffer, header) == CHIP_NO_ERROR); + EXPECT_EQ(parser.AccumulateAndDecode(buffer, header), CHIP_NO_ERROR); buffer = ByteSpan(kMinOtaImage, sizeof(kMinOtaImage) - 1); parser.Init(); - NL_TEST_ASSERT(inSuite, parser.AccumulateAndDecode(buffer, header) == CHIP_ERROR_BUFFER_TOO_SMALL); - NL_TEST_ASSERT(inSuite, parser.IsInitialized()); + EXPECT_EQ(parser.AccumulateAndDecode(buffer, header), CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_TRUE(parser.IsInitialized()); } -void TestMissingMandatoryField(nlTestSuite * inSuite, void * inContext) +TEST_F(TestOTAImageHeader, TestMissingMandatoryField) { ByteSpan buffer(kMinOtaImageWithoutVendor); OTAImageHeader header; OTAImageHeaderParser parser; parser.Init(); - NL_TEST_ASSERT(inSuite, parser.AccumulateAndDecode(buffer, header) == CHIP_ERROR_UNEXPECTED_TLV_ELEMENT); - NL_TEST_ASSERT(inSuite, !parser.IsInitialized()); + EXPECT_EQ(parser.AccumulateAndDecode(buffer, header), CHIP_ERROR_UNEXPECTED_TLV_ELEMENT); + EXPECT_FALSE(parser.IsInitialized()); } -void TestSmallBlocks(nlTestSuite * inSuite, void * inContext) +TEST_F(TestOTAImageHeader, TestSmallBlocks) { constexpr size_t kImageSize = sizeof(kOtaImage); @@ -164,55 +170,20 @@ void TestSmallBlocks(nlTestSuite * inSuite, void * inContext) error = parser.AccumulateAndDecode(block, header); } - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, parser.IsInitialized()); - NL_TEST_ASSERT(inSuite, header.mVendorId == 0xDEAD); - NL_TEST_ASSERT(inSuite, header.mProductId == 0xBEEF); - NL_TEST_ASSERT(inSuite, header.mSoftwareVersion == 0xFFFFFFFF); - NL_TEST_ASSERT(inSuite, header.mSoftwareVersionString.data_equal("1.0"_span)); - NL_TEST_ASSERT(inSuite, header.mPayloadSize == strlen("test payload")); - NL_TEST_ASSERT(inSuite, header.mMinApplicableVersion.HasValue()); - NL_TEST_ASSERT(inSuite, header.mMinApplicableVersion.Value() == 1); - NL_TEST_ASSERT(inSuite, header.mMaxApplicableVersion.HasValue()); - NL_TEST_ASSERT(inSuite, header.mMaxApplicableVersion.Value() == 2); - NL_TEST_ASSERT(inSuite, header.mReleaseNotesURL.data_equal("https://rn"_span)); - NL_TEST_ASSERT(inSuite, header.mImageDigestType == OTAImageDigestType::kSha256); - NL_TEST_ASSERT(inSuite, header.mImageDigest.size() == 256 / 8); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_TRUE(parser.IsInitialized()); + EXPECT_EQ(header.mVendorId, 0xDEAD); + EXPECT_EQ(header.mProductId, 0xBEEF); + EXPECT_EQ(header.mSoftwareVersion, 0xFFFFFFFF); + EXPECT_TRUE(header.mSoftwareVersionString.data_equal("1.0"_span)); + EXPECT_EQ(header.mPayloadSize, strlen("test payload")); + EXPECT_TRUE(header.mMinApplicableVersion.HasValue()); + EXPECT_EQ(header.mMinApplicableVersion.Value(), 1u); + EXPECT_TRUE(header.mMaxApplicableVersion.HasValue()); + EXPECT_EQ(header.mMaxApplicableVersion.Value(), 2u); + EXPECT_TRUE(header.mReleaseNotesURL.data_equal("https://rn"_span)); + EXPECT_EQ(header.mImageDigestType, OTAImageDigestType::kSha256); + EXPECT_EQ(header.mImageDigest.size(), 256u / 8); } } - -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("Test happy path", TestHappyPath), - NL_TEST_DEF("Test empty buffer", TestEmptyBuffer), - NL_TEST_DEF("Test invalid File Identifier", TestInvalidFileIdentifier), - NL_TEST_DEF("Test too small header", TestTooSmallHeader), - NL_TEST_DEF("Test missing mandatory field", TestMissingMandatoryField), - NL_TEST_DEF("Test small blocks", TestSmallBlocks), - NL_TEST_SENTINEL() -}; -// clang-format on - -int SetupSuite(void * inContext) -{ - return Platform::MemoryInit() == CHIP_NO_ERROR ? SUCCESS : FAILURE; -} - -int TearDownSuite(void * inContext) -{ - Platform::MemoryShutdown(); - return SUCCESS; -} - } // namespace - -int TestOTAImageHeader() -{ - nlTestSuite theSuite = { "OTA Image header test", &sTests[0], SetupSuite, TearDownSuite }; - nlTestRunner(&theSuite, nullptr); - - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestOTAImageHeader) diff --git a/src/lib/core/tests/TestOptional.cpp b/src/lib/core/tests/TestOptional.cpp index b54d8de1120a4c..9a0e95f1db8da2 100644 --- a/src/lib/core/tests/TestOptional.cpp +++ b/src/lib/core/tests/TestOptional.cpp @@ -30,9 +30,8 @@ #include #include -#include -#include +#include using namespace chip; @@ -76,7 +75,7 @@ struct CountMovable : public Count int Count::created; int Count::destroyed; -static void TestBasic(nlTestSuite * inSuite, void * inContext) +TEST(TestOptional, TestBasic) { // Set up our test Count objects, which will mess with counts, before we reset the // counts. @@ -86,107 +85,107 @@ static void TestBasic(nlTestSuite * inSuite, void * inContext) { auto testOptional = Optional::Value(100); - NL_TEST_ASSERT(inSuite, Count::created == 1 && Count::destroyed == 0); - NL_TEST_ASSERT(inSuite, testOptional.HasValue() && testOptional.Value().m == 100); - NL_TEST_ASSERT(inSuite, testOptional == c100); - NL_TEST_ASSERT(inSuite, testOptional != c101); - NL_TEST_ASSERT(inSuite, testOptional != c102); + EXPECT_TRUE(Count::created == 1 && Count::destroyed == 0); + EXPECT_TRUE(testOptional.HasValue() && testOptional.Value().m == 100); + EXPECT_EQ(testOptional, c100); + EXPECT_NE(testOptional, c101); + EXPECT_NE(testOptional, c102); testOptional.ClearValue(); - NL_TEST_ASSERT(inSuite, Count::created == 1 && Count::destroyed == 1); - NL_TEST_ASSERT(inSuite, !testOptional.HasValue()); - NL_TEST_ASSERT(inSuite, testOptional != c100); - NL_TEST_ASSERT(inSuite, testOptional != c101); - NL_TEST_ASSERT(inSuite, testOptional != c102); + EXPECT_TRUE(Count::created == 1 && Count::destroyed == 1); + EXPECT_FALSE(testOptional.HasValue()); + EXPECT_NE(testOptional, c100); + EXPECT_NE(testOptional, c101); + EXPECT_NE(testOptional, c102); testOptional.SetValue(Count(101)); - NL_TEST_ASSERT(inSuite, Count::created == 3 && Count::destroyed == 2); - NL_TEST_ASSERT(inSuite, testOptional.HasValue() && testOptional.Value().m == 101); - NL_TEST_ASSERT(inSuite, testOptional != c100); - NL_TEST_ASSERT(inSuite, testOptional == c101); - NL_TEST_ASSERT(inSuite, testOptional != c102); + EXPECT_TRUE(Count::created == 3 && Count::destroyed == 2); + EXPECT_TRUE(testOptional.HasValue() && testOptional.Value().m == 101); + EXPECT_NE(testOptional, c100); + EXPECT_EQ(testOptional, c101); + EXPECT_NE(testOptional, c102); testOptional.Emplace(102); - NL_TEST_ASSERT(inSuite, Count::created == 4 && Count::destroyed == 3); - NL_TEST_ASSERT(inSuite, testOptional.HasValue() && testOptional.Value().m == 102); - NL_TEST_ASSERT(inSuite, testOptional != c100); - NL_TEST_ASSERT(inSuite, testOptional != c101); - NL_TEST_ASSERT(inSuite, testOptional == c102); + EXPECT_TRUE(Count::created == 4 && Count::destroyed == 3); + EXPECT_TRUE(testOptional.HasValue() && testOptional.Value().m == 102); + EXPECT_NE(testOptional, c100); + EXPECT_NE(testOptional, c101); + EXPECT_EQ(testOptional, c102); } // Our test Count objects are still in scope here. - NL_TEST_ASSERT(inSuite, Count::created == 4 && Count::destroyed == 4); + EXPECT_TRUE(Count::created == 4 && Count::destroyed == 4); } -static void TestMake(nlTestSuite * inSuite, void * inContext) +TEST(TestOptional, TestMake) { Count::ResetCounter(); { auto testOptional = MakeOptional(200); - NL_TEST_ASSERT(inSuite, Count::created == 1 && Count::destroyed == 0); - NL_TEST_ASSERT(inSuite, testOptional.HasValue() && testOptional.Value().m == 200); + EXPECT_TRUE(Count::created == 1 && Count::destroyed == 0); + EXPECT_TRUE(testOptional.HasValue() && testOptional.Value().m == 200); } - NL_TEST_ASSERT(inSuite, Count::created == 1 && Count::destroyed == 1); + EXPECT_TRUE(Count::created == 1 && Count::destroyed == 1); } -static void TestCopy(nlTestSuite * inSuite, void * inContext) +TEST(TestOptional, TestCopy) { Count::ResetCounter(); { auto testSrc = Optional::Value(300); - NL_TEST_ASSERT(inSuite, Count::created == 1 && Count::destroyed == 0); - NL_TEST_ASSERT(inSuite, testSrc.HasValue() && testSrc.Value().m == 300); + EXPECT_TRUE(Count::created == 1 && Count::destroyed == 0); + EXPECT_TRUE(testSrc.HasValue() && testSrc.Value().m == 300); { Optional testDst(testSrc); - NL_TEST_ASSERT(inSuite, Count::created == 2 && Count::destroyed == 0); - NL_TEST_ASSERT(inSuite, testDst.HasValue() && testDst.Value().m == 300); + EXPECT_TRUE(Count::created == 2 && Count::destroyed == 0); + EXPECT_TRUE(testDst.HasValue() && testDst.Value().m == 300); } - NL_TEST_ASSERT(inSuite, Count::created == 2 && Count::destroyed == 1); + EXPECT_TRUE(Count::created == 2 && Count::destroyed == 1); { Optional testDst; - NL_TEST_ASSERT(inSuite, Count::created == 2 && Count::destroyed == 1); - NL_TEST_ASSERT(inSuite, !testDst.HasValue()); + EXPECT_TRUE(Count::created == 2 && Count::destroyed == 1); + EXPECT_FALSE(testDst.HasValue()); testDst = testSrc; - NL_TEST_ASSERT(inSuite, Count::created == 3 && Count::destroyed == 1); - NL_TEST_ASSERT(inSuite, testDst.HasValue() && testDst.Value().m == 300); + EXPECT_TRUE(Count::created == 3 && Count::destroyed == 1); + EXPECT_TRUE(testDst.HasValue() && testDst.Value().m == 300); } - NL_TEST_ASSERT(inSuite, Count::created == 3 && Count::destroyed == 2); + EXPECT_TRUE(Count::created == 3 && Count::destroyed == 2); } - NL_TEST_ASSERT(inSuite, Count::created == 3 && Count::destroyed == 3); + EXPECT_TRUE(Count::created == 3 && Count::destroyed == 3); } -static void TestMove(nlTestSuite * inSuite, void * inContext) +TEST(TestOptional, TestMove) { Count::ResetCounter(); { auto testSrc = MakeOptional(400); Optional testDst(std::move(testSrc)); - NL_TEST_ASSERT(inSuite, Count::created == 2 && Count::destroyed == 1); - NL_TEST_ASSERT(inSuite, testDst.HasValue() && testDst.Value().m == 400); + EXPECT_TRUE(Count::created == 2 && Count::destroyed == 1); + EXPECT_TRUE(testDst.HasValue() && testDst.Value().m == 400); } - NL_TEST_ASSERT(inSuite, Count::created == 2 && Count::destroyed == 2); + EXPECT_TRUE(Count::created == 2 && Count::destroyed == 2); { Optional testDst; - NL_TEST_ASSERT(inSuite, Count::created == 2 && Count::destroyed == 2); - NL_TEST_ASSERT(inSuite, !testDst.HasValue()); + EXPECT_TRUE(Count::created == 2 && Count::destroyed == 2); + EXPECT_FALSE(testDst.HasValue()); auto testSrc = MakeOptional(401); testDst = std::move(testSrc); - NL_TEST_ASSERT(inSuite, Count::created == 4 && Count::destroyed == 3); - NL_TEST_ASSERT(inSuite, testDst.HasValue() && testDst.Value().m == 401); + EXPECT_TRUE(Count::created == 4 && Count::destroyed == 3); + EXPECT_TRUE(testDst.HasValue() && testDst.Value().m == 401); } - NL_TEST_ASSERT(inSuite, Count::created == 4 && Count::destroyed == 4); + EXPECT_TRUE(Count::created == 4 && Count::destroyed == 4); } -static void TestConversion(nlTestSuite * inSuite, void * inContext) +TEST(TestOptional, TestConversion) { // FixedSpan is implicitly convertible from std::array using WidgetView = FixedSpan; @@ -197,17 +196,17 @@ static void TestConversion(nlTestSuite * inSuite, void * inContext) auto optOtherStorage = MakeOptional(); auto const & constOptOtherStorage = optOtherStorage; - NL_TEST_ASSERT(inSuite, optStorage.HasValue()); - NL_TEST_ASSERT(inSuite, optOtherStorage.HasValue()); + EXPECT_TRUE(optStorage.HasValue()); + EXPECT_TRUE(optOtherStorage.HasValue()); Optional optView(constOptStorage); - NL_TEST_ASSERT(inSuite, optView.HasValue()); - NL_TEST_ASSERT(inSuite, &optView.Value()[0] == &optStorage.Value()[0]); + EXPECT_TRUE(optView.HasValue()); + EXPECT_EQ(&optView.Value()[0], &optStorage.Value()[0]); optView = optOtherStorage; optView = constOptOtherStorage; - NL_TEST_ASSERT(inSuite, optView.HasValue()); - NL_TEST_ASSERT(inSuite, &optView.Value()[0] == &optOtherStorage.Value()[0]); + EXPECT_TRUE(optView.HasValue()); + EXPECT_EQ(&optView.Value()[0], &optOtherStorage.Value()[0]); struct ExplicitBool { @@ -218,48 +217,3 @@ static void TestConversion(nlTestSuite * inSuite, void * inContext) // The following should not compile // e = Optional(false); // relies on implicit conversion } - -/** - * Test Suite. It lists all the test functions. - */ - -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("OptionalBasic", TestBasic), - NL_TEST_DEF("OptionalMake", TestMake), - NL_TEST_DEF("OptionalCopy", TestCopy), - NL_TEST_DEF("OptionalMove", TestMove), - NL_TEST_DEF("OptionalConversion", TestConversion), - NL_TEST_SENTINEL() -}; -// clang-format on - -int TestOptional_Setup(void * inContext) -{ - return SUCCESS; -} - -int TestOptional_Teardown(void * inContext) -{ - return SUCCESS; -} - -int TestOptional() -{ - // clang-format off - nlTestSuite theSuite = - { - "Optional", - &sTests[0], - TestOptional_Setup, - TestOptional_Teardown - }; - // clang-format on - - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestOptional) diff --git a/src/lib/core/tests/TestReferenceCounted.cpp b/src/lib/core/tests/TestReferenceCounted.cpp index 9c292c4a057fe1..4f3c3cd4182a3c 100644 --- a/src/lib/core/tests/TestReferenceCounted.cpp +++ b/src/lib/core/tests/TestReferenceCounted.cpp @@ -28,24 +28,30 @@ #include #include -#include -#include +#include using namespace chip; +class TestReferenceCounted : public ::testing::Test +{ +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + class TestClass : public ReferenceCounted { }; -static void TestRetainRelease(nlTestSuite * inSuite, void * inContext) +TEST_F(TestReferenceCounted, TestRetainRelease) { TestClass * testObj = chip::Platform::New(); - NL_TEST_ASSERT(inSuite, testObj->GetReferenceCount() == 1); + EXPECT_EQ(testObj->GetReferenceCount(), 1u); testObj->Retain(); - NL_TEST_ASSERT(inSuite, testObj->GetReferenceCount() == 2); + EXPECT_EQ(testObj->GetReferenceCount(), 2u); testObj->Release(); - NL_TEST_ASSERT(inSuite, testObj->GetReferenceCount() == 1); + EXPECT_EQ(testObj->GetReferenceCount(), 1u); testObj->Release(); } @@ -67,66 +73,19 @@ void Deletor::Release(TestClassNonHeap * obj) obj->deleted = true; } -static void TestRetainReleaseNonHeap(nlTestSuite * inSuite, void * inContext) +TEST_F(TestReferenceCounted, TestRetainReleaseNonHeap) { TestClassNonHeap testObj; testObj.deleted = false; - NL_TEST_ASSERT(inSuite, testObj.GetReferenceCount() == 1); - NL_TEST_ASSERT(inSuite, testObj.deleted == false); + EXPECT_EQ(testObj.GetReferenceCount(), 1u); + EXPECT_EQ(testObj.deleted, false); testObj.Retain(); - NL_TEST_ASSERT(inSuite, testObj.GetReferenceCount() == 2); - NL_TEST_ASSERT(inSuite, testObj.deleted == false); + EXPECT_EQ(testObj.GetReferenceCount(), 2u); + EXPECT_EQ(testObj.deleted, false); testObj.Release(); - NL_TEST_ASSERT(inSuite, testObj.GetReferenceCount() == 1); - NL_TEST_ASSERT(inSuite, testObj.deleted == false); + EXPECT_EQ(testObj.GetReferenceCount(), 1u); + EXPECT_EQ(testObj.deleted, false); testObj.Release(); - NL_TEST_ASSERT(inSuite, testObj.GetReferenceCount() == 0); - NL_TEST_ASSERT(inSuite, testObj.deleted == true); + EXPECT_EQ(testObj.GetReferenceCount(), 0u); + EXPECT_EQ(testObj.deleted, true); } - -/** - * Test Suite. It lists all the test functions. - */ - -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("ReferenceCountedRetain", TestRetainRelease), - NL_TEST_DEF("ReferenceCountedRetainNonHeap", TestRetainReleaseNonHeap), - - NL_TEST_SENTINEL() -}; -// clang-format on - -int TestReferenceCounted_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -int TestReferenceCounted_Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -int TestReferenceCounted() -{ - // clang-format off - nlTestSuite theSuite = - { - "Reference-Counted", - &sTests[0], - TestReferenceCounted_Setup, - TestReferenceCounted_Teardown - }; - // clang-format on - - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestReferenceCounted) diff --git a/src/lib/core/tests/TestTLV.cpp b/src/lib/core/tests/TestTLV.cpp index f71bce13fbd70b..4b391c4983f701 100644 --- a/src/lib/core/tests/TestTLV.cpp +++ b/src/lib/core/tests/TestTLV.cpp @@ -23,8 +23,8 @@ * */ +#include #include -#include #include #include @@ -37,9 +37,7 @@ #include #include #include -#include -#include -#include + #include #include @@ -66,105 +64,104 @@ static const char sLargeString [] = "...END"; // clang-format on -void TestAndOpenContainer(nlTestSuite * inSuite, TLVReader & reader, TLVType type, Tag tag, TLVReader & containerReader) +void TestAndOpenContainer(TLVReader & reader, TLVType type, Tag tag, TLVReader & containerReader) { - NL_TEST_ASSERT(inSuite, reader.GetType() == type); - NL_TEST_ASSERT(inSuite, reader.GetTag() == tag); - NL_TEST_ASSERT(inSuite, reader.GetLength() == 0); + EXPECT_EQ(reader.GetType(), type); + EXPECT_EQ(reader.GetTag(), tag); + EXPECT_EQ(reader.GetLength(), 0u); CHIP_ERROR err = reader.OpenContainer(containerReader); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, containerReader.GetContainerType() == type); + EXPECT_EQ(containerReader.GetContainerType(), type); } template -void TestAndEnterContainer(nlTestSuite * inSuite, T & t, TLVType type, Tag tag, TLVType & outerContainerType) +void TestAndEnterContainer(T & t, TLVType type, Tag tag, TLVType & outerContainerType) { - NL_TEST_ASSERT(inSuite, t.GetType() == type); - NL_TEST_ASSERT(inSuite, t.GetTag() == tag); - NL_TEST_ASSERT(inSuite, t.GetLength() == 0); + EXPECT_EQ(t.GetType(), type); + EXPECT_EQ(t.GetTag(), tag); + EXPECT_EQ(t.GetLength(), 0u); TLVType expectedContainerType = t.GetContainerType(); CHIP_ERROR err = t.EnterContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, outerContainerType == expectedContainerType); - NL_TEST_ASSERT(inSuite, t.GetContainerType() == type); + EXPECT_EQ(outerContainerType, expectedContainerType); + EXPECT_EQ(t.GetContainerType(), type); } template -void TestNext(nlTestSuite * inSuite, T & t) +void TestNext(T & t) { CHIP_ERROR err = t.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void TestSkip(nlTestSuite * inSuite, TLVReader & reader) +void TestSkip(TLVReader & reader) { CHIP_ERROR err = reader.Skip(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void TestMove(nlTestSuite * inSuite, TLVUpdater & updater) +void TestMove(TLVUpdater & updater) { CHIP_ERROR err = updater.Move(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } template -void TestEnd(nlTestSuite * inSuite, T & t) +void TestEnd(T & t) { CHIP_ERROR err; err = t.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_END_OF_TLV); + EXPECT_EQ(err, CHIP_END_OF_TLV); } -void TestEndAndCloseContainer(nlTestSuite * inSuite, TLVReader & reader, TLVReader & containerReader) +void TestEndAndCloseContainer(TLVReader & reader, TLVReader & containerReader) { CHIP_ERROR err; - TestEnd(inSuite, containerReader); + TestEnd(containerReader); err = reader.CloseContainer(containerReader); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } template -void TestEndAndExitContainer(nlTestSuite * inSuite, T & t, TLVType outerContainerType) +void TestEndAndExitContainer(T & t, TLVType outerContainerType) { CHIP_ERROR err; - TestEnd(inSuite, t); + TestEnd(t); err = t.ExitContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, t.GetContainerType() == outerContainerType); + EXPECT_EQ(t.GetContainerType(), outerContainerType); } -#define TEST_GET(inSuite, s, type, tag, expectedVal, expectedErr) \ +#define TEST_GET(s, type, tag, expectedVal, expectedErr) \ do \ { \ - NL_TEST_ASSERT(inSuite, s.GetType() == type); \ - NL_TEST_ASSERT(inSuite, s.GetTag() == tag); \ - NL_TEST_ASSERT(inSuite, s.GetLength() == 0); \ + EXPECT_EQ(s.GetType(), type); \ + EXPECT_EQ(s.GetTag(), tag); \ + EXPECT_EQ(s.GetLength(), 0u); \ \ decltype(expectedVal) __val; \ CHIP_ERROR __err = s.Get(__val); \ - NL_TEST_ASSERT(inSuite, __err == expectedErr); \ + EXPECT_EQ(__err, expectedErr); \ if (__err == CHIP_NO_ERROR) \ { \ - NL_TEST_ASSERT(inSuite, __val == expectedVal); \ + EXPECT_EQ(__val, expectedVal); \ } \ } while (false) -#define TEST_GET_NOERROR(inSuite, s, type, tag, expectedVal) TEST_GET(inSuite, s, type, tag, expectedVal, CHIP_NO_ERROR) +#define TEST_GET_NOERROR(s, type, tag, expectedVal) TEST_GET(s, type, tag, expectedVal, CHIP_NO_ERROR) -void ForEachElement(nlTestSuite * inSuite, TLVReader & reader, void * context, - void (*cb)(nlTestSuite * inSuite, TLVReader & reader, void * context)) +void ForEachElement(TLVReader & reader, void * context, void (*cb)(TLVReader & reader, void * context)) { CHIP_ERROR err; @@ -175,11 +172,11 @@ void ForEachElement(nlTestSuite * inSuite, TLVReader & reader, void * context, { return; } - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); if (cb != nullptr) { - cb(inSuite, reader, context); + cb(reader, context); } if (TLVTypeIsContainer(reader.GetType())) @@ -187,12 +184,12 @@ void ForEachElement(nlTestSuite * inSuite, TLVReader & reader, void * context, TLVType outerContainerType; err = reader.EnterContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ForEachElement(inSuite, reader, context, cb); + ForEachElement(reader, context, cb); err = reader.ExitContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } } } @@ -203,84 +200,84 @@ void ForEachElement(nlTestSuite * inSuite, TLVReader & reader, void * context, struct TestTLVContext { - nlTestSuite * mSuite = nullptr; int mEvictionCount = 0; uint32_t mEvictedBytes = 0; +}; - TestTLVContext(nlTestSuite * suite) : mSuite(suite) {} +class TestTLV : public ::testing::Test +{ +public: + static TestTLVContext ctx; + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } }; -void TestNull(nlTestSuite * inSuite, TLVReader & reader, Tag tag) +TestTLVContext TestTLV::ctx; + +void TestNull(TLVReader & reader, Tag tag) { - NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_Null); - NL_TEST_ASSERT(inSuite, reader.GetTag() == tag); - NL_TEST_ASSERT(inSuite, reader.GetLength() == 0); + EXPECT_EQ(reader.GetType(), kTLVType_Null); + EXPECT_EQ(reader.GetTag(), tag); + EXPECT_EQ(reader.GetLength(), 0u); } -void TestString(nlTestSuite * inSuite, TLVReader & reader, Tag tag, const char * expectedVal) +void TestString(TLVReader & reader, Tag tag, const char * expectedVal) { - NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_UTF8String); - NL_TEST_ASSERT(inSuite, reader.GetTag() == tag); + EXPECT_EQ(reader.GetType(), kTLVType_UTF8String); + EXPECT_EQ(reader.GetTag(), tag); size_t expectedLen = strlen(expectedVal); - NL_TEST_ASSERT(inSuite, reader.GetLength() == expectedLen); + EXPECT_EQ(reader.GetLength(), expectedLen); chip::Platform::ScopedMemoryBuffer valBuffer; char * val = static_cast(valBuffer.Alloc(expectedLen + 1).Get()); CHIP_ERROR err = reader.GetString(val, static_cast(expectedLen) + 1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(val, expectedVal, expectedLen + 1) == 0); + EXPECT_EQ(memcmp(val, expectedVal, expectedLen + 1), 0); } -void TestDupString(nlTestSuite * inSuite, TLVReader & reader, Tag tag, const char * expectedVal) +void TestDupString(TLVReader & reader, Tag tag, const char * expectedVal) { - NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_UTF8String); - NL_TEST_ASSERT(inSuite, reader.GetTag() == tag); + EXPECT_EQ(reader.GetType(), kTLVType_UTF8String); + EXPECT_EQ(reader.GetTag(), tag); size_t expectedLen = strlen(expectedVal); - NL_TEST_ASSERT(inSuite, reader.GetLength() == expectedLen); + EXPECT_EQ(reader.GetLength(), expectedLen); char * val = nullptr; CHIP_ERROR err = reader.DupString(val); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, val != nullptr); - if (val != nullptr) - { - NL_TEST_ASSERT(inSuite, memcmp(val, expectedVal, expectedLen + 1) == 0); - } + EXPECT_EQ(err, CHIP_NO_ERROR); + ASSERT_NE(val, nullptr); + EXPECT_EQ(memcmp(val, expectedVal, expectedLen + 1), 0); chip::Platform::MemoryFree(val); } -void TestDupBytes(nlTestSuite * inSuite, TLVReader & reader, Tag tag, const uint8_t * expectedVal, uint32_t expectedLen) +void TestDupBytes(TLVReader & reader, Tag tag, const uint8_t * expectedVal, uint32_t expectedLen) { - NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_UTF8String); - NL_TEST_ASSERT(inSuite, reader.GetTag() == tag); + EXPECT_EQ(reader.GetType(), kTLVType_UTF8String); + EXPECT_EQ(reader.GetTag(), tag); - NL_TEST_ASSERT(inSuite, reader.GetLength() == expectedLen); + EXPECT_EQ(reader.GetLength(), expectedLen); uint8_t * val = nullptr; CHIP_ERROR err = reader.DupBytes(val, expectedLen); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, val != nullptr); - if (val != nullptr) - { - NL_TEST_ASSERT(inSuite, memcmp(val, expectedVal, expectedLen) == 0); - } + EXPECT_EQ(err, CHIP_NO_ERROR); + ASSERT_NE(val, nullptr); + EXPECT_EQ(memcmp(val, expectedVal, expectedLen), 0); chip::Platform::MemoryFree(val); } -void TestBufferContents(nlTestSuite * inSuite, const System::PacketBufferHandle & buffer, const uint8_t * expectedVal, - uint32_t expectedLen) +void TestBufferContents(const System::PacketBufferHandle & buffer, const uint8_t * expectedVal, uint32_t expectedLen) { System::PacketBufferHandle buf = buffer.Retain(); while (!buf.IsNull()) { uint16_t len = buf->DataLength(); - NL_TEST_ASSERT(inSuite, len <= expectedLen); + EXPECT_LE(len, expectedLen); - NL_TEST_ASSERT(inSuite, memcmp(buf->Start(), expectedVal, len) == 0); + EXPECT_EQ(memcmp(buf->Start(), expectedVal, len), 0); expectedVal += len; expectedLen -= len; @@ -288,7 +285,7 @@ void TestBufferContents(nlTestSuite * inSuite, const System::PacketBufferHandle buf.Advance(); } - NL_TEST_ASSERT(inSuite, expectedLen == 0); + EXPECT_EQ(expectedLen, 0u); } // clang-format off @@ -371,455 +368,450 @@ static const uint8_t Encoding1_DataMacro [] = }; // clang-format on -static CHIP_ERROR WriteIntMinMax(nlTestSuite * inSuite, TLVWriter & writer) +static CHIP_ERROR WriteIntMinMax(TLVWriter & writer) { CHIP_ERROR err; err = writer.Put(AnonymousTag(), static_cast(INT8_MIN)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Put(AnonymousTag(), static_cast(INT8_MAX)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Put(AnonymousTag(), static_cast(INT16_MIN)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Put(AnonymousTag(), static_cast(INT16_MAX)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Put(AnonymousTag(), static_cast(INT32_MIN)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Put(AnonymousTag(), static_cast(INT32_MAX)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Put(AnonymousTag(), static_cast(INT64_MIN)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Put(AnonymousTag(), static_cast(INT64_MAX)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Put(AnonymousTag(), static_cast(UINT8_MAX)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Put(AnonymousTag(), static_cast(UINT16_MAX)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Put(AnonymousTag(), static_cast(UINT32_MAX)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Put(AnonymousTag(), static_cast(UINT64_MAX)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); return err; } -static void CheckIntMinMax(nlTestSuite * inSuite, TLVReader & reader) +static void CheckIntMinMax(TLVReader & reader) { // Writer did Put(AnonymousTag(), static_cast(INT8_MIN)) - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MIN)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MIN)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MIN)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MIN)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MIN)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MIN)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MIN)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MIN)); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TestNext(inSuite, reader); + TestNext(reader); // Writer did Put(AnonymousTag(), static_cast(INT8_MAX)) - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MAX)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MAX)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MAX)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MAX)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MAX)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MAX)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MAX)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT8_MAX)); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TestNext(inSuite, reader); + TestNext(reader); // Writer did Put(AnonymousTag(), static_cast(INT16_MIN)) - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT16_MIN)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT16_MIN)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT16_MIN)); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT16_MIN)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT16_MIN)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT16_MIN)); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TestNext(inSuite, reader); + TestNext(reader); // Writer did Put(AnonymousTag(), static_cast(INT16_MAX)) - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT16_MAX)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT16_MAX)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT16_MAX)); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT16_MAX)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT16_MAX)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT16_MAX)); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TestNext(inSuite, reader); + TestNext(reader); // Writer did Put(AnonymousTag(), static_cast(INT32_MIN)) - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT32_MIN)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT32_MIN)); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT32_MIN)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT32_MIN)); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TestNext(inSuite, reader); + TestNext(reader); // Writer did Put(AnonymousTag(), static_cast(INT32_MAX)) - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT32_MAX)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT32_MAX)); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT32_MAX)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT32_MAX)); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TestNext(inSuite, reader); + TestNext(reader); // Writer did Put(AnonymousTag(), static_cast(INT64_MIN)) - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT64_MIN)); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT64_MIN)); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TestNext(inSuite, reader); + TestNext(reader); // Writer did Put(AnonymousTag(), static_cast(INT64_MAX)) - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT64_MAX)); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(INT64_MAX)); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_SignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TestNext(inSuite, reader); + TestNext(reader); // Writer did Put(AnonymousTag(), static_cast(UINT8_MAX)) - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET_NOERROR(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT8_MAX)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT8_MAX)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT8_MAX)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT8_MAX)); + TEST_GET_NOERROR(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT8_MAX)); + TEST_GET_NOERROR(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT8_MAX)); + TEST_GET_NOERROR(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT8_MAX)); + TEST_GET_NOERROR(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT8_MAX)); - TestNext(inSuite, reader); + TestNext(reader); // Writer did Put(AnonymousTag(), static_cast(UINT16_MAX)) - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET_NOERROR(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT16_MAX)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT16_MAX)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT16_MAX)); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET_NOERROR(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT16_MAX)); + TEST_GET_NOERROR(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT16_MAX)); + TEST_GET_NOERROR(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT16_MAX)); - TestNext(inSuite, reader); + TestNext(reader); // Writer did Put(AnonymousTag(), static_cast(UINT32_MAX)) - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET_NOERROR(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT32_MAX)); - TEST_GET_NOERROR(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT32_MAX)); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET_NOERROR(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT32_MAX)); + TEST_GET_NOERROR(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT32_MAX)); - TestNext(inSuite, reader); + TestNext(reader); // Writer did Put(AnonymousTag(), static_cast(UINT64_MAX)) - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); - - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); - TEST_GET_NOERROR(inSuite, reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT64_MAX)); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_WRONG_TLV_TYPE); + + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(0), CHIP_ERROR_INVALID_INTEGER_VALUE); + TEST_GET_NOERROR(reader, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(UINT64_MAX)); } -void WriteEncoding1(nlTestSuite * inSuite, TLVWriter & writer) +void WriteEncoding1(TLVWriter & writer) { CHIP_ERROR err; TLVWriter writer2; err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); { TLVWriter writer3; err = writer2.OpenContainer(ContextTag(0), kTLVType_Array, writer3); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // TODO(#1306): expand coverage of inttype encoding tests. err = writer3.Put(AnonymousTag(), static_cast(42)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.Put(AnonymousTag(), static_cast(-17)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.Put(AnonymousTag(), static_cast(-170000)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.Put(AnonymousTag(), static_cast(40000000000ULL)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); { TLVWriter writer4; err = writer3.OpenContainer(AnonymousTag(), kTLVType_Structure, writer4); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.CloseContainer(writer4); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } { TLVWriter writer5; err = writer3.OpenContainer(AnonymousTag(), kTLVType_List, writer5); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer5.PutNull(ProfileTag(TestProfile_1, 17)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer5.PutNull(ProfileTag(TestProfile_2, 900000)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer5.PutNull(AnonymousTag()); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); { TLVType outerContainerType; err = writer5.StartContainer(ProfileTag(TestProfile_2, 4000000000ULL), kTLVType_Structure, outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer5.PutString(CommonTag(70000), sLargeString); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer5.EndContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = writer3.CloseContainer(writer5); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = writer2.CloseContainer(writer3); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = writer2.PutString(ProfileTag(TestProfile_1, 5), "This is a test"); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(ProfileTag(TestProfile_2, 65535), static_cast(17.9)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(ProfileTag(TestProfile_2, 65536), 17.9); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.CloseContainer(writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void WriteEmptyEncoding(nlTestSuite * inSuite, TLVWriter & writer) +void WriteEmptyEncoding(TLVWriter & writer) { CHIP_ERROR err; TLVWriter writer2; err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); { TLVWriter writer3; err = writer2.OpenContainer(ProfileTag(TestProfile_1, 256), kTLVType_Array, writer3); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.CloseContainer(writer3); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = writer.CloseContainer(writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void ReadEncoding1(nlTestSuite * inSuite, TLVReader & reader) +void ReadEncoding1(TLVReader & reader) { - TestNext(inSuite, reader); + TestNext(reader); { TLVReader reader2; - TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader2); + TestAndOpenContainer(reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader2); - TestNext(inSuite, reader2); + TestNext(reader2); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); + TEST_GET_NOERROR(reader2, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); - TestNext(inSuite, reader2); + TestNext(reader2); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); + TEST_GET_NOERROR(reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); - TestNext(inSuite, reader2); + TestNext(reader2); { TLVReader reader3; - TestAndOpenContainer(inSuite, reader2, kTLVType_Array, ContextTag(0), reader3); + TestAndOpenContainer(reader2, kTLVType_Array, ContextTag(0), reader3); - TestNext(inSuite, reader3); + TestNext(reader3); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); - TEST_GET(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42), - CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42), - CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42), - CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); + TEST_GET(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42), CHIP_ERROR_WRONG_TLV_TYPE); - TestNext(inSuite, reader3); + TestNext(reader3); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); - TEST_GET(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17), - CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); + TEST_GET(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17), CHIP_ERROR_WRONG_TLV_TYPE); - TestNext(inSuite, reader3); + TestNext(reader3); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-170000)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-170000)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-170000)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-170000)); - TestNext(inSuite, reader3); + TestNext(reader3); - TEST_GET(inSuite, reader3, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(40000000000ULL), + TEST_GET(reader3, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(40000000000ULL), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(40000000000ULL)); + TEST_GET_NOERROR(reader3, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(40000000000ULL)); - TestNext(inSuite, reader3); + TestNext(reader3); { TLVReader reader4; - TestAndOpenContainer(inSuite, reader3, kTLVType_Structure, AnonymousTag(), reader4); + TestAndOpenContainer(reader3, kTLVType_Structure, AnonymousTag(), reader4); - TestEndAndCloseContainer(inSuite, reader3, reader4); + TestEndAndCloseContainer(reader3, reader4); } - TestNext(inSuite, reader3); + TestNext(reader3); { TLVReader reader5; - TestAndOpenContainer(inSuite, reader3, kTLVType_List, AnonymousTag(), reader5); + TestAndOpenContainer(reader3, kTLVType_List, AnonymousTag(), reader5); - TestNext(inSuite, reader5); + TestNext(reader5); - TestNull(inSuite, reader5, ProfileTag(TestProfile_1, 17)); + TestNull(reader5, ProfileTag(TestProfile_1, 17)); - TestNext(inSuite, reader5); + TestNext(reader5); - TestNull(inSuite, reader5, ProfileTag(TestProfile_2, 900000)); + TestNull(reader5, ProfileTag(TestProfile_2, 900000)); - TestNext(inSuite, reader5); + TestNext(reader5); - TestNull(inSuite, reader5, AnonymousTag()); + TestNull(reader5, AnonymousTag()); - TestNext(inSuite, reader5); + TestNext(reader5); { TLVType outerContainerType; - TestAndEnterContainer(inSuite, reader5, kTLVType_Structure, ProfileTag(TestProfile_2, 4000000000ULL), + TestAndEnterContainer(reader5, kTLVType_Structure, ProfileTag(TestProfile_2, 4000000000ULL), outerContainerType); - TestNext(inSuite, reader5); + TestNext(reader5); - TestString(inSuite, reader5, CommonTag(70000), sLargeString); + TestString(reader5, CommonTag(70000), sLargeString); - TestEndAndExitContainer(inSuite, reader5, outerContainerType); + TestEndAndExitContainer(reader5, outerContainerType); } - TestEndAndCloseContainer(inSuite, reader3, reader5); + TestEndAndCloseContainer(reader3, reader5); } - TestEndAndCloseContainer(inSuite, reader2, reader3); + TestEndAndCloseContainer(reader2, reader3); } - TestNext(inSuite, reader2); + TestNext(reader2); - TestString(inSuite, reader2, ProfileTag(TestProfile_1, 5), "This is a test"); + TestString(reader2, ProfileTag(TestProfile_1, 5), "This is a test"); - TestNext(inSuite, reader2); + TestNext(reader2); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65535), 17.9f); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65535), - static_cast(17.9f)); + TEST_GET_NOERROR(reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65535), 17.9f); + TEST_GET_NOERROR(reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65535), static_cast(17.9f)); - TestNext(inSuite, reader2); + TestNext(reader2); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65536), 17.9); + TEST_GET_NOERROR(reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65536), 17.9); - TestEndAndCloseContainer(inSuite, reader, reader2); + TestEndAndCloseContainer(reader, reader2); } - TestEnd(inSuite, reader); + TestEnd(reader); } -void WriteEncoding2(nlTestSuite * inSuite, TLVWriter & writer) +void WriteEncoding2(TLVWriter & writer) { CHIP_ERROR err; @@ -827,39 +819,39 @@ void WriteEncoding2(nlTestSuite * inSuite, TLVWriter & writer) TLVWriter writer1; err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.CloseContainer(writer1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } { // Container 2 TLVWriter writer1; err = writer.OpenContainer(ProfileTag(TestProfile_2, 1), kTLVType_Structure, writer1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.CloseContainer(writer1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void WriteEncoding3(nlTestSuite * inSuite, TLVWriter & writer) +void WriteEncoding3(TLVWriter & writer) { CHIP_ERROR err; @@ -868,30 +860,30 @@ void WriteEncoding3(nlTestSuite * inSuite, TLVWriter & writer) err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer1); if (err != CHIP_NO_ERROR) - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.CloseContainer(writer1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void ReadEncoding3(nlTestSuite * inSuite, TLVReader & reader) +void ReadEncoding3(TLVReader & reader) { TLVReader reader2; - TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader2); + TestAndOpenContainer(reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader2); - TestNext(inSuite, reader2); + TestNext(reader2); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); + TEST_GET_NOERROR(reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); - TestEndAndCloseContainer(inSuite, reader, reader2); + TestEndAndCloseContainer(reader, reader2); } // clang-format off static const uint8_t Encoding5_DataMacro [] = @@ -920,7 +912,7 @@ static const uint8_t Encoding5_DataMacro [] = }; // clang-format on -void WriteEncoding5(nlTestSuite * inSuite, TLVWriter & writer) +void WriteEncoding5(TLVWriter & writer) { CHIP_ERROR err; @@ -928,74 +920,74 @@ void WriteEncoding5(nlTestSuite * inSuite, TLVWriter & writer) TLVWriter writer1; err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_1, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); { // Inner Container 1 TLVWriter writer2; err = writer1.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.CloseContainer(writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } { // Inner Container 2 TLVWriter writer2; err = writer1.OpenContainer(ProfileTag(TestProfile_2, 1), kTLVType_Structure, writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.CloseContainer(writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = writer.CloseContainer(writer1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } { // Container 2 TLVWriter writer1; err = writer.OpenContainer(ProfileTag(TestProfile_2, 1), kTLVType_Structure, writer1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.CloseContainer(writer1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } /** @@ -1012,66 +1004,66 @@ void WriteEncoding5(nlTestSuite * inSuite, TLVWriter & writer) * >, * > */ -void AppendEncoding2(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen) +void AppendEncoding2(uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen) { CHIP_ERROR err; TLVUpdater updater; err = updater.Init(buf, dataLen, maxLen); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); updater.SetImplicitProfileId(TestProfile_2); - TestNext(inSuite, updater); + TestNext(updater); { TLVType outerContainerType; - TestAndEnterContainer(inSuite, updater, kTLVType_Structure, ProfileTag(TestProfile_1, 1), outerContainerType); + TestAndEnterContainer(updater, kTLVType_Structure, ProfileTag(TestProfile_1, 1), outerContainerType); - TestNext(inSuite, updater); + TestNext(updater); // Move the element without modification - TestMove(inSuite, updater); + TestMove(updater); - TestNext(inSuite, updater); + TestNext(updater); // Read and copy the element with/without modification - TEST_GET_NOERROR(inSuite, updater, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); + TEST_GET_NOERROR(updater, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // TestEnd and add data at the end of the container - TestEnd(inSuite, updater); + TestEnd(updater); // Put new values in the encoding using the updater // Add err = updater.PutBoolean(ProfileTag(TestProfile_1, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Add err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Add a new container { TLVType outerContainerType1; err = updater.StartContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, outerContainerType1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Add err = updater.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Add err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Close the container err = updater.EndContainer(outerContainerType1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } // Add another new container @@ -1079,33 +1071,33 @@ void AppendEncoding2(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uin TLVType outerContainerType1; err = updater.StartContainer(ProfileTag(TestProfile_2, 1), kTLVType_Structure, outerContainerType1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Add err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Add err = updater.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Close the container err = updater.EndContainer(outerContainerType1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } - TestEndAndExitContainer(inSuite, updater, outerContainerType); + TestEndAndExitContainer(updater, outerContainerType); } - TestNext(inSuite, updater); + TestNext(updater); // Move the container unmodified - TestMove(inSuite, updater); + TestMove(updater); - TestEnd(inSuite, updater); + TestEnd(updater); err = updater.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); updatedLen = updater.GetLengthWritten(); } @@ -1126,8 +1118,7 @@ void AppendEncoding2(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uin * >, * > */ -void FindAppendEncoding2(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen, - bool findContainer) +void FindAppendEncoding2(uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen, bool findContainer) { CHIP_ERROR err; @@ -1144,76 +1135,76 @@ void FindAppendEncoding2(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, TLVReader tagReader; TLVType outerContainerType; err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_1, 1), tagReader); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = tagReader.EnterContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); do { err = tagReader.Next(); } while (err != CHIP_END_OF_TLV); - TestEnd(inSuite, tagReader); + TestEnd(tagReader); // Init a TLVUpdater using the TLVReader err = updater.Init(tagReader, maxLen - dataLen); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } else { // Find TLVReader tagReader; err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_2, 2), tagReader); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Test Find(recurse = true) TLVReader tagReader2; err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_2, 2), tagReader2, true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // // Test Find(recurse = false) TLVReader tagReader3; err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_2, 2), tagReader3, false); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_TLV_TAG_NOT_FOUND); + EXPECT_EQ(err, CHIP_ERROR_TLV_TAG_NOT_FOUND); // Init a TLVUpdater using the TLVReader err = updater.Init(tagReader, maxLen - dataLen); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - TestNext(inSuite, updater); + TestNext(updater); // Move the element without modification - TestMove(inSuite, updater); + TestMove(updater); } // Put new values in the encoding using the updater // Add err = updater.PutBoolean(ProfileTag(TestProfile_1, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Add err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Add a new container { TLVType outerContainerType1; err = updater.StartContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, outerContainerType1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Add err = updater.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Add err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Close the container err = updater.EndContainer(outerContainerType1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } // Add another new container @@ -1221,79 +1212,79 @@ void FindAppendEncoding2(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, TLVType outerContainerType1; err = updater.StartContainer(ProfileTag(TestProfile_2, 1), kTLVType_Structure, outerContainerType1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Add err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Add err = updater.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Close the container err = updater.EndContainer(outerContainerType1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } // Move everything else unmodified updater.MoveUntilEnd(); - TestEnd(inSuite, updater); + TestEnd(updater); err = updater.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); updatedLen = updater.GetLengthWritten(); } -void AppendEncoding3(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen) +void AppendEncoding3(uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen) { CHIP_ERROR err; TLVUpdater updater; err = updater.Init(buf, dataLen, maxLen); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); updater.SetImplicitProfileId(TestProfile_2); - TestNext(inSuite, updater); + TestNext(updater); { TLVType outerContainerType; - TestAndEnterContainer(inSuite, updater, kTLVType_Structure, ProfileTag(TestProfile_1, 1), outerContainerType); + TestAndEnterContainer(updater, kTLVType_Structure, ProfileTag(TestProfile_1, 1), outerContainerType); - TestNext(inSuite, updater); + TestNext(updater); // Move the element without modification - TestMove(inSuite, updater); + TestMove(updater); // Put new value in the encoding using the updater // Add err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - TestEndAndExitContainer(inSuite, updater, outerContainerType); + TestEndAndExitContainer(updater, outerContainerType); } - TestEnd(inSuite, updater); + TestEnd(updater); err = updater.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); updatedLen = updater.GetLengthWritten(); } -void AppendEncoding4(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen) +void AppendEncoding4(uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen) { CHIP_ERROR err; TLVUpdater updater; err = updater.Init(buf, dataLen, maxLen); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); updater.SetImplicitProfileId(TestProfile_2); @@ -1302,59 +1293,59 @@ void AppendEncoding4(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uin TLVType outerContainerType; err = updater.StartContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Add err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Close the container err = updater.EndContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = updater.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); updatedLen = updater.GetLengthWritten(); } -void DeleteEncoding5(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen) +void DeleteEncoding5(uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen) { CHIP_ERROR err; TLVUpdater updater; err = updater.Init(buf, dataLen, maxLen); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); updater.SetImplicitProfileId(TestProfile_2); - TestNext(inSuite, updater); + TestNext(updater); { TLVType outerContainerType; - TestAndEnterContainer(inSuite, updater, kTLVType_Structure, ProfileTag(TestProfile_1, 1), outerContainerType); + TestAndEnterContainer(updater, kTLVType_Structure, ProfileTag(TestProfile_1, 1), outerContainerType); - TestNext(inSuite, updater); + TestNext(updater); - TestMove(inSuite, updater); + TestMove(updater); - TestNext(inSuite, updater); + TestNext(updater); - TestMove(inSuite, updater); + TestMove(updater); - TestNext(inSuite, updater); + TestNext(updater); // Get the value to inspect and skip writing it - TEST_GET_NOERROR(inSuite, updater, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); + TEST_GET_NOERROR(updater, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); - TestNext(inSuite, updater); + TestNext(updater); // Skip the next boolean type and don't copy by doing nothing - TestNext(inSuite, updater); + TestNext(updater); // Read ahead into the next container and decide whether to skip or // not based on elements in the container @@ -1364,206 +1355,206 @@ void DeleteEncoding5(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uin updater.GetReader(reader); - TestAndEnterContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), containerType); + TestAndEnterContainer(reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), containerType); - TestNext(inSuite, reader); + TestNext(reader); // If the container's first element has the tag // skip the whole container, and if NOT copy the container if (reader.GetTag() != ProfileTag(TestProfile_1, 2)) - TestMove(inSuite, updater); + TestMove(updater); } - TestNext(inSuite, updater); + TestNext(updater); // Skip the next container and don't copy by doing nothing - TestEndAndExitContainer(inSuite, updater, outerContainerType); + TestEndAndExitContainer(updater, outerContainerType); } // Move everything else unmodified updater.MoveUntilEnd(); - TestEnd(inSuite, updater); + TestEnd(updater); err = updater.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); updatedLen = updater.GetLengthWritten(); } -void ReadAppendedEncoding2(nlTestSuite * inSuite, TLVReader & reader) +void ReadAppendedEncoding2(TLVReader & reader) { - TestNext(inSuite, reader); + TestNext(reader); { // Container 1 TLVReader reader1; - TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader1); + TestAndOpenContainer(reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader1); - TestNext(inSuite, reader1); + TestNext(reader1); - TEST_GET_NOERROR(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); + TEST_GET_NOERROR(reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); - TestNext(inSuite, reader1); + TestNext(reader1); - TEST_GET_NOERROR(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); + TEST_GET_NOERROR(reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); - TestNext(inSuite, reader1); + TestNext(reader1); - TEST_GET_NOERROR(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); + TEST_GET_NOERROR(reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); - TestNext(inSuite, reader1); + TestNext(reader1); - TEST_GET_NOERROR(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), true); + TEST_GET_NOERROR(reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), true); - TestNext(inSuite, reader1); + TestNext(reader1); { TLVReader reader2; - TestAndOpenContainer(inSuite, reader1, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader2); + TestAndOpenContainer(reader1, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader2); - TestNext(inSuite, reader2); + TestNext(reader2); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); + TEST_GET_NOERROR(reader2, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); - TestNext(inSuite, reader2); + TestNext(reader2); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); + TEST_GET_NOERROR(reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); - TestEndAndCloseContainer(inSuite, reader1, reader2); + TestEndAndCloseContainer(reader1, reader2); } - TestNext(inSuite, reader1); + TestNext(reader1); { TLVReader reader2; - TestAndOpenContainer(inSuite, reader1, kTLVType_Structure, ProfileTag(TestProfile_2, 1), reader2); + TestAndOpenContainer(reader1, kTLVType_Structure, ProfileTag(TestProfile_2, 1), reader2); - TestNext(inSuite, reader2); + TestNext(reader2); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); + TEST_GET_NOERROR(reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); - TestNext(inSuite, reader2); + TestNext(reader2); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); + TEST_GET_NOERROR(reader2, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); - TestEndAndCloseContainer(inSuite, reader1, reader2); + TestEndAndCloseContainer(reader1, reader2); } - TestEndAndCloseContainer(inSuite, reader, reader1); + TestEndAndCloseContainer(reader, reader1); } - TestNext(inSuite, reader); + TestNext(reader); { // Container 2 TLVReader reader1; - TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_2, 1), reader1); + TestAndOpenContainer(reader, kTLVType_Structure, ProfileTag(TestProfile_2, 1), reader1); - TestNext(inSuite, reader1); + TestNext(reader1); - TEST_GET_NOERROR(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); + TEST_GET_NOERROR(reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); - TestNext(inSuite, reader1); + TestNext(reader1); - TEST_GET_NOERROR(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); + TEST_GET_NOERROR(reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); - TestEndAndCloseContainer(inSuite, reader, reader1); + TestEndAndCloseContainer(reader, reader1); } - TestEnd(inSuite, reader); + TestEnd(reader); } -void ReadAppendedEncoding3(nlTestSuite * inSuite, TLVReader & reader) +void ReadAppendedEncoding3(TLVReader & reader) { - TestNext(inSuite, reader); + TestNext(reader); { // Container 1 TLVReader reader1; - TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader1); + TestAndOpenContainer(reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader1); - TestNext(inSuite, reader1); + TestNext(reader1); - TEST_GET_NOERROR(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); + TEST_GET_NOERROR(reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); - TestNext(inSuite, reader1); + TestNext(reader1); - TEST_GET_NOERROR(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), true); + TEST_GET_NOERROR(reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), true); - TestEndAndCloseContainer(inSuite, reader, reader1); + TestEndAndCloseContainer(reader, reader1); } - TestEnd(inSuite, reader); + TestEnd(reader); } -void ReadAppendedEncoding4(nlTestSuite * inSuite, TLVReader & reader) +void ReadAppendedEncoding4(TLVReader & reader) { - TestNext(inSuite, reader); + TestNext(reader); { // Container 1 TLVReader reader1; - TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader1); + TestAndOpenContainer(reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader1); - TestNext(inSuite, reader1); + TestNext(reader1); - TEST_GET_NOERROR(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); + TEST_GET_NOERROR(reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); - TestEndAndCloseContainer(inSuite, reader, reader1); + TestEndAndCloseContainer(reader, reader1); } - TestEnd(inSuite, reader); + TestEnd(reader); } -void ReadDeletedEncoding5(nlTestSuite * inSuite, TLVReader & reader) +void ReadDeletedEncoding5(TLVReader & reader) { - TestNext(inSuite, reader); + TestNext(reader); { // Container 1 TLVReader reader1; - TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader1); + TestAndOpenContainer(reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader1); - TestNext(inSuite, reader1); + TestNext(reader1); - TEST_GET_NOERROR(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); + TEST_GET_NOERROR(reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); - TestNext(inSuite, reader1); + TestNext(reader1); - TEST_GET_NOERROR(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); + TEST_GET_NOERROR(reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); - TestEndAndCloseContainer(inSuite, reader, reader1); + TestEndAndCloseContainer(reader, reader1); } - TestNext(inSuite, reader); + TestNext(reader); { // Container 2 TLVReader reader1; - TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_2, 1), reader1); + TestAndOpenContainer(reader, kTLVType_Structure, ProfileTag(TestProfile_2, 1), reader1); - TestNext(inSuite, reader1); + TestNext(reader1); - TEST_GET_NOERROR(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); + TEST_GET_NOERROR(reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); - TestNext(inSuite, reader1); + TestNext(reader1); - TEST_GET_NOERROR(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); + TEST_GET_NOERROR(reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); - TestEndAndCloseContainer(inSuite, reader, reader1); + TestEndAndCloseContainer(reader, reader1); } - TestEnd(inSuite, reader); + TestEnd(reader); } /** * Test Simple Write and Reader */ -void CheckSimpleWriteRead(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckSimpleWriteRead) { uint8_t buf[2048]; TLVWriter writer; @@ -1574,9 +1565,9 @@ void CheckSimpleWriteRead(nlTestSuite * inSuite, void * inContext) writer.ImplicitProfileId = TestProfile_2; remainingFreedLen = writer.GetRemainingFreeLength(); - NL_TEST_ASSERT(inSuite, sizeof(buf) == remainingFreedLen); + EXPECT_EQ(sizeof(buf), remainingFreedLen); - WriteEncoding1(inSuite, writer); + WriteEncoding1(writer); uint32_t encodedLen = writer.GetLengthWritten(); @@ -1590,16 +1581,16 @@ void CheckSimpleWriteRead(nlTestSuite * inSuite, void * inContext) printf("\n"); #endif - NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding1)); - NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding1, encodedLen) == 0); + EXPECT_EQ(encodedLen, sizeof(Encoding1)); + EXPECT_EQ(memcmp(buf, Encoding1, encodedLen), 0); reader.Init(buf, encodedLen); reader.ImplicitProfileId = TestProfile_2; - ReadEncoding1(inSuite, reader); + ReadEncoding1(reader); } -static void TestIntMinMax(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, TestIntMinMax) { CHIP_ERROR err; @@ -1611,25 +1602,25 @@ static void TestIntMinMax(nlTestSuite * inSuite, void * inContext) writer.ImplicitProfileId = TestProfile_3; err = writer.OpenContainer(ProfileTag(TestProfile_3, 1), kTLVType_Array, writer1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - WriteIntMinMax(inSuite, writer1); + WriteIntMinMax(writer1); err = writer.CloseContainer(writer1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(buf, sizeof(buf)); reader.ImplicitProfileId = TestProfile_3; - TestNext(inSuite, reader); + TestNext(reader); - TestAndOpenContainer(inSuite, reader, kTLVType_Array, ProfileTag(TestProfile_3, 1), reader1); + TestAndOpenContainer(reader, kTLVType_Array, ProfileTag(TestProfile_3, 1), reader1); - TestNext(inSuite, reader1); + TestNext(reader1); - CheckIntMinMax(inSuite, reader1); + CheckIntMinMax(reader1); - TestEndAndCloseContainer(inSuite, reader, reader1); + TestEndAndCloseContainer(reader, reader1); } /** @@ -1657,7 +1648,7 @@ void ENFORCE_FORMAT(1, 2) SimpleDumpWriter(const char * aFormat, ...) /** * Test Pretty Printer */ -void CheckPrettyPrinter(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckPrettyPrinter) { uint8_t buf[2048]; TLVWriter writer; @@ -1666,12 +1657,12 @@ void CheckPrettyPrinter(nlTestSuite * inSuite, void * inContext) writer.Init(buf); writer.ImplicitProfileId = TestProfile_2; - WriteEncoding1(inSuite, writer); + WriteEncoding1(writer); uint32_t encodedLen = writer.GetLengthWritten(); - NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding1)); - NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding1, encodedLen) == 0); + EXPECT_EQ(encodedLen, sizeof(Encoding1)); + EXPECT_EQ(memcmp(buf, Encoding1, encodedLen), 0); reader.Init(buf, encodedLen); reader.ImplicitProfileId = TestProfile_2; @@ -1707,7 +1698,7 @@ void ENFORCE_FORMAT(1, 2) StringDumpWriter(const char * aFormat, ...) /** * Test Octet String Pretty Printer */ -void CheckOctetStringPrettyPrinter(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckOctetStringPrettyPrinter) { const uint8_t testOctetString[] = { 0x62, 0xFA, 0x82, 0x33, 0x59, 0xAC, 0xFA, 0xA9 }; const char expectedPrint[] = @@ -1716,35 +1707,34 @@ void CheckOctetStringPrettyPrinter(nlTestSuite * inSuite, void * inContext) TLVWriter writer; writer.Init(encodedBuf); - NL_TEST_ASSERT_SUCCESS(inSuite, writer.PutBytes(CommonTag(0), testOctetString, sizeof(testOctetString))); - NL_TEST_ASSERT_SUCCESS(inSuite, writer.Finalize()); + EXPECT_EQ(CHIP_NO_ERROR, writer.PutBytes(CommonTag(0), testOctetString, sizeof(testOctetString))); + EXPECT_EQ(CHIP_NO_ERROR, writer.Finalize()); TLVReader reader; reader.Init(encodedBuf, writer.GetLengthWritten()); chip::TLV::Debug::Dump(reader, StringDumpWriter); - NL_TEST_ASSERT(inSuite, strlen(expectedPrint) == strlen(gStringDumpWriterBuf)); - NL_TEST_ASSERT(inSuite, strcmp(expectedPrint, gStringDumpWriterBuf) == 0); + EXPECT_STREQ(expectedPrint, gStringDumpWriterBuf); } /** * Test Data Macros */ -void CheckDataMacro(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckDataMacro) { - NL_TEST_ASSERT(inSuite, sizeof(Encoding1_DataMacro) == sizeof(Encoding1)); - NL_TEST_ASSERT(inSuite, memcmp(Encoding1, Encoding1_DataMacro, sizeof(Encoding1)) == 0); + EXPECT_EQ(sizeof(Encoding1_DataMacro), sizeof(Encoding1)); + EXPECT_EQ(memcmp(Encoding1, Encoding1_DataMacro, sizeof(Encoding1)), 0); uint8_t buf[2048]; TLVWriter writer; writer.Init(buf); writer.ImplicitProfileId = TestProfile_2; - WriteEncoding5(inSuite, writer); + WriteEncoding5(writer); uint32_t encodedLen = writer.GetLengthWritten(); - NL_TEST_ASSERT(inSuite, sizeof(Encoding5_DataMacro) == encodedLen); - NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding5_DataMacro, encodedLen) == 0); + EXPECT_EQ(sizeof(Encoding5_DataMacro), encodedLen); + EXPECT_EQ(memcmp(buf, Encoding5_DataMacro, encodedLen), 0); } static CHIP_ERROR NullIterateHandler(const TLVReader & aReader, size_t aDepth, void * aContext) @@ -1789,7 +1779,7 @@ static CHIP_ERROR FindContainerWithElement(const TLVReader & aReader, size_t aDe /** * Test CHIP TLV Utilities */ -void CheckTLVUtilities(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckTLVUtilities) { uint8_t buf[2048]; TLVWriter writer; @@ -1799,32 +1789,32 @@ void CheckTLVUtilities(nlTestSuite * inSuite, void * inContext) writer.Init(buf); writer.ImplicitProfileId = TestProfile_2; - WriteEncoding1(inSuite, writer); + WriteEncoding1(writer); uint32_t encodedLen = writer.GetLengthWritten(); - NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding1)); - NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding1, encodedLen) == 0); + EXPECT_EQ(encodedLen, sizeof(Encoding1)); + EXPECT_EQ(memcmp(buf, Encoding1, encodedLen), 0); reader.Init(buf, encodedLen); reader.ImplicitProfileId = TestProfile_2; reader1.Init(reader); err = reader1.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Find a tag TLVReader tagReader; err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_2, 65536), tagReader); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Find with reader positioned "on" the element of interest err = chip::TLV::Utilities::Find(reader1, ProfileTag(TestProfile_1, 1), tagReader); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Find a tag that's not present err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_2, 1024), tagReader); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_TLV_TAG_NOT_FOUND); + EXPECT_EQ(err, CHIP_ERROR_TLV_TAG_NOT_FOUND); // Find with a predicate { @@ -1833,7 +1823,7 @@ void CheckTLVUtilities(nlTestSuite * inSuite, void * inContext) writer.Init(buf1); writer.ImplicitProfileId = TestProfile_2; - WriteEncoding2(inSuite, writer); + WriteEncoding2(writer); // Initialize a reader reader1.Init(buf1, writer.GetLengthWritten()); @@ -1843,20 +1833,20 @@ void CheckTLVUtilities(nlTestSuite * inSuite, void * inContext) reader1.Next(); Tag tag = ProfileTag(TestProfile_1, 1); err = chip::TLV::Utilities::Find(reader1, FindContainerWithElement, &tag, tagReader, false); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_TLV_TAG_NOT_FOUND); + EXPECT_EQ(err, CHIP_ERROR_TLV_TAG_NOT_FOUND); tag = ProfileTag(TestProfile_2, 2); err = chip::TLV::Utilities::Find(reader1, FindContainerWithElement, &tag, tagReader, false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, tagReader.GetType() == kTLVType_Structure); - NL_TEST_ASSERT(inSuite, tagReader.GetTag() == ProfileTag(TestProfile_1, 1)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(tagReader.GetType(), kTLVType_Structure); + EXPECT_EQ(tagReader.GetTag(), ProfileTag(TestProfile_1, 1)); // Position the reader on the second element reader1.Next(); err = chip::TLV::Utilities::Find(reader1, FindContainerWithElement, &tag, tagReader, false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, tagReader.GetType() == kTLVType_Structure); - NL_TEST_ASSERT(inSuite, tagReader.GetTag() == ProfileTag(TestProfile_2, 1)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(tagReader.GetType(), kTLVType_Structure); + EXPECT_EQ(tagReader.GetTag(), ProfileTag(TestProfile_2, 1)); } // Count @@ -1866,23 +1856,23 @@ void CheckTLVUtilities(nlTestSuite * inSuite, void * inContext) reader1.Next(); err = chip::TLV::Utilities::Count(reader, count); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, count == expectedCount); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(count, expectedCount); // Count with reader already positioned "on" the first element in the encoding err = chip::TLV::Utilities::Count(reader1, count); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, count == expectedCount); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(count, expectedCount); // Iterate err = chip::TLV::Utilities::Iterate(reader, NullIterateHandler, nullptr); - NL_TEST_ASSERT(inSuite, err == CHIP_END_OF_TLV); + EXPECT_EQ(err, CHIP_END_OF_TLV); } /** * Test CHIP TLV Empty Find */ -void CheckTLVEmptyFind(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckTLVEmptyFind) { uint8_t buf[30]; TLVWriter writer; @@ -1892,7 +1882,7 @@ void CheckTLVEmptyFind(nlTestSuite * inSuite, void * inContext) writer.Init(buf); writer.ImplicitProfileId = TestProfile_2; - WriteEmptyEncoding(inSuite, writer); + WriteEmptyEncoding(writer); uint32_t encodedLen = writer.GetLengthWritten(); @@ -1902,7 +1892,7 @@ void CheckTLVEmptyFind(nlTestSuite * inSuite, void * inContext) // Find the empty container TLVReader tagReader; err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_1, 256), tagReader); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } // clang-format off @@ -1945,7 +1935,7 @@ uint8_t AppendedEncoding2[] = }; // clang-format on -void WriteAppendReadTest0(nlTestSuite * inSuite) +void WriteAppendReadTest0() { uint8_t buf[74]; uint32_t updatedLen; @@ -1956,7 +1946,7 @@ void WriteAppendReadTest0(nlTestSuite * inSuite) writer.Init(buf); writer.ImplicitProfileId = TestProfile_2; - WriteEncoding2(inSuite, writer); + WriteEncoding2(writer); uint32_t encodedLen = writer.GetLengthWritten(); @@ -1971,11 +1961,11 @@ void WriteAppendReadTest0(nlTestSuite * inSuite) printf("\n"); #endif - NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding2)); - NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding2, encodedLen) == 0); + EXPECT_EQ(encodedLen, sizeof(Encoding2)); + EXPECT_EQ(memcmp(buf, Encoding2, encodedLen), 0); // Append new data into encoding - AppendEncoding2(inSuite, buf, encodedLen, sizeof(buf), updatedLen); + AppendEncoding2(buf, encodedLen, sizeof(buf), updatedLen); #ifdef DUMP_ENCODING printf("Updated encoding:\n"); @@ -1988,16 +1978,16 @@ void WriteAppendReadTest0(nlTestSuite * inSuite) printf("\n"); #endif - NL_TEST_ASSERT(inSuite, updatedLen == sizeof(AppendedEncoding2)); - NL_TEST_ASSERT(inSuite, memcmp(buf, AppendedEncoding2, updatedLen) == 0); + EXPECT_EQ(updatedLen, sizeof(AppendedEncoding2)); + EXPECT_EQ(memcmp(buf, AppendedEncoding2, updatedLen), 0); reader.Init(buf, updatedLen); reader.ImplicitProfileId = TestProfile_2; - ReadAppendedEncoding2(inSuite, reader); + ReadAppendedEncoding2(reader); } -void WriteFindAppendReadTest(nlTestSuite * inSuite, bool findContainer) +void WriteFindAppendReadTest(bool findContainer) { uint8_t buf[74]; uint32_t updatedLen; @@ -2008,7 +1998,7 @@ void WriteFindAppendReadTest(nlTestSuite * inSuite, bool findContainer) writer.Init(buf); writer.ImplicitProfileId = TestProfile_2; - WriteEncoding2(inSuite, writer); + WriteEncoding2(writer); uint32_t encodedLen = writer.GetLengthWritten(); @@ -2023,11 +2013,11 @@ void WriteFindAppendReadTest(nlTestSuite * inSuite, bool findContainer) printf("\n"); #endif - NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding2)); - NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding2, encodedLen) == 0); + EXPECT_EQ(encodedLen, sizeof(Encoding2)); + EXPECT_EQ(memcmp(buf, Encoding2, encodedLen), 0); // Append new data into encoding - FindAppendEncoding2(inSuite, buf, encodedLen, sizeof(buf), updatedLen, findContainer); + FindAppendEncoding2(buf, encodedLen, sizeof(buf), updatedLen, findContainer); #ifdef DUMP_ENCODING printf("Updated encoding:\n"); @@ -2040,13 +2030,13 @@ void WriteFindAppendReadTest(nlTestSuite * inSuite, bool findContainer) printf("\n"); #endif - NL_TEST_ASSERT(inSuite, updatedLen == sizeof(AppendedEncoding2)); - NL_TEST_ASSERT(inSuite, memcmp(buf, AppendedEncoding2, updatedLen) == 0); + EXPECT_EQ(updatedLen, sizeof(AppendedEncoding2)); + EXPECT_EQ(memcmp(buf, AppendedEncoding2, updatedLen), 0); reader.Init(buf, updatedLen); reader.ImplicitProfileId = TestProfile_2; - ReadAppendedEncoding2(inSuite, reader); + ReadAppendedEncoding2(reader); } // clang-format off @@ -2068,7 +2058,7 @@ uint8_t AppendedEncoding3[] = }; // clang-format on -void WriteAppendReadTest1(nlTestSuite * inSuite) +void WriteAppendReadTest1() { uint8_t buf[14]; uint32_t updatedLen; @@ -2079,7 +2069,7 @@ void WriteAppendReadTest1(nlTestSuite * inSuite) writer.Init(buf); writer.ImplicitProfileId = TestProfile_2; - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); uint32_t encodedLen = writer.GetLengthWritten(); @@ -2094,11 +2084,11 @@ void WriteAppendReadTest1(nlTestSuite * inSuite) printf("\n"); #endif - NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding3)); - NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding3, encodedLen) == 0); + EXPECT_EQ(encodedLen, sizeof(Encoding3)); + EXPECT_EQ(memcmp(buf, Encoding3, encodedLen), 0); // Append new data into encoding - AppendEncoding3(inSuite, buf, encodedLen, sizeof(buf), updatedLen); + AppendEncoding3(buf, encodedLen, sizeof(buf), updatedLen); #ifdef DUMP_ENCODING printf("Updated encoding:\n"); @@ -2111,13 +2101,13 @@ void WriteAppendReadTest1(nlTestSuite * inSuite) printf("\n"); #endif - NL_TEST_ASSERT(inSuite, updatedLen == sizeof(AppendedEncoding3)); - NL_TEST_ASSERT(inSuite, memcmp(buf, AppendedEncoding3, updatedLen) == 0); + EXPECT_EQ(updatedLen, sizeof(AppendedEncoding3)); + EXPECT_EQ(memcmp(buf, AppendedEncoding3, updatedLen), 0); reader.Init(buf, updatedLen); reader.ImplicitProfileId = TestProfile_2; - ReadAppendedEncoding3(inSuite, reader); + ReadAppendedEncoding3(reader); } // clang-format off @@ -2130,7 +2120,7 @@ uint8_t AppendedEncoding4[] = }; // clang-format on -void AppendReadTest(nlTestSuite * inSuite) +void AppendReadTest() { uint8_t buf[11]; uint32_t updatedLen; @@ -2149,7 +2139,7 @@ void AppendReadTest(nlTestSuite * inSuite) #endif // Append new data to encoding - AppendEncoding4(inSuite, buf, 0, sizeof(buf), updatedLen); + AppendEncoding4(buf, 0, sizeof(buf), updatedLen); #ifdef DUMP_ENCODING printf("Updated encoding:\n"); @@ -2162,14 +2152,14 @@ void AppendReadTest(nlTestSuite * inSuite) printf("\n"); #endif - NL_TEST_ASSERT(inSuite, updatedLen == sizeof(AppendedEncoding4)); - NL_TEST_ASSERT(inSuite, memcmp(buf, AppendedEncoding4, updatedLen) == 0); + EXPECT_EQ(updatedLen, sizeof(AppendedEncoding4)); + EXPECT_EQ(memcmp(buf, AppendedEncoding4, updatedLen), 0); TLVReader reader; reader.Init(buf, updatedLen); reader.ImplicitProfileId = TestProfile_2; - ReadAppendedEncoding4(inSuite, reader); + ReadAppendedEncoding4(reader); } // clang-format off @@ -2212,7 +2202,7 @@ uint8_t DeletedEncoding5[] = }; // clang-format on -void WriteDeleteReadTest(nlTestSuite * inSuite) +void WriteDeleteReadTest() { uint8_t buf[74]; uint32_t updatedLen; @@ -2223,7 +2213,7 @@ void WriteDeleteReadTest(nlTestSuite * inSuite) writer.Init(buf); writer.ImplicitProfileId = TestProfile_2; - WriteEncoding5(inSuite, writer); + WriteEncoding5(writer); uint32_t encodedLen = writer.GetLengthWritten(); @@ -2237,25 +2227,25 @@ void WriteDeleteReadTest(nlTestSuite * inSuite) printf("\n"); #endif - NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding5)); - NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding5, encodedLen) == 0); + EXPECT_EQ(encodedLen, sizeof(Encoding5)); + EXPECT_EQ(memcmp(buf, Encoding5, encodedLen), 0); // Delete some elements from the encoding - DeleteEncoding5(inSuite, buf, encodedLen, sizeof(buf), updatedLen); + DeleteEncoding5(buf, encodedLen, sizeof(buf), updatedLen); - NL_TEST_ASSERT(inSuite, updatedLen == sizeof(DeletedEncoding5)); - NL_TEST_ASSERT(inSuite, memcmp(buf, DeletedEncoding5, updatedLen) == 0); + EXPECT_EQ(updatedLen, sizeof(DeletedEncoding5)); + EXPECT_EQ(memcmp(buf, DeletedEncoding5, updatedLen), 0); reader.Init(buf, updatedLen); reader.ImplicitProfileId = TestProfile_2; - ReadDeletedEncoding5(inSuite, reader); + ReadDeletedEncoding5(reader); } /** * Test Packet Buffer */ -void CheckPacketBuffer(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckPacketBuffer) { System::PacketBufferHandle buf = System::PacketBufferHandle::New(sizeof(Encoding1), 0); System::PacketBufferTLVWriter writer; @@ -2264,19 +2254,19 @@ void CheckPacketBuffer(nlTestSuite * inSuite, void * inContext) writer.Init(buf.Retain()); writer.ImplicitProfileId = TestProfile_2; - WriteEncoding1(inSuite, writer); + WriteEncoding1(writer); - TestBufferContents(inSuite, buf, Encoding1, sizeof(Encoding1)); + TestBufferContents(buf, Encoding1, sizeof(Encoding1)); reader.Init(buf.Retain()); reader.ImplicitProfileId = TestProfile_2; - ReadEncoding1(inSuite, reader); + ReadEncoding1(reader); reader.Init(buf.Retain()); reader.ImplicitProfileId = TestProfile_2; - ReadEncoding1(inSuite, reader); + ReadEncoding1(reader); } CHIP_ERROR CountEvictedMembers(TLVCircularBuffer & inBuffer, void * inAppData, TLVReader & inReader) @@ -2286,10 +2276,10 @@ CHIP_ERROR CountEvictedMembers(TLVCircularBuffer & inBuffer, void * inAppData, T // "Process" the first element in the reader err = inReader.Next(); - NL_TEST_ASSERT(context->mSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = inReader.Skip(); - NL_TEST_ASSERT(context->mSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); context->mEvictionCount++; context->mEvictedBytes += inReader.GetLengthRead(); @@ -2297,7 +2287,7 @@ CHIP_ERROR CountEvictedMembers(TLVCircularBuffer & inBuffer, void * inAppData, T return CHIP_NO_ERROR; } -void CheckCircularTLVBufferSimple(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckCircularTLVBufferSimple) { // Write 40 bytes as 4 separate events into a 30 byte buffer. On // completion of the test, the buffer should contain 2 elements @@ -2307,7 +2297,7 @@ void CheckCircularTLVBufferSimple(nlTestSuite * inSuite, void * inContext) uint8_t backingStore[30]; CircularTLVWriter writer; CircularTLVReader reader; - TestTLVContext * context = static_cast(inContext); + TestTLVContext * context = &TestTLV::ctx; TLVCircularBuffer buffer(backingStore, 30); writer.Init(buffer); writer.ImplicitProfileId = TestProfile_2; @@ -2316,38 +2306,38 @@ void CheckCircularTLVBufferSimple(nlTestSuite * inSuite, void * inContext) context->mEvictedBytes = 0; buffer.mProcessEvictedElement = CountEvictedMembers; - buffer.mAppData = inContext; + buffer.mAppData = &TestTLV::ctx; writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); - NL_TEST_ASSERT(inSuite, context->mEvictionCount == 2); - NL_TEST_ASSERT(inSuite, context->mEvictedBytes == 18); - NL_TEST_ASSERT(inSuite, buffer.DataLength() == 22); - NL_TEST_ASSERT(inSuite, (buffer.DataLength() + context->mEvictedBytes) == writer.GetLengthWritten()); + EXPECT_EQ(context->mEvictionCount, 2); + EXPECT_EQ(context->mEvictedBytes, 18u); + EXPECT_EQ(buffer.DataLength(), 22u); + EXPECT_EQ((buffer.DataLength() + context->mEvictedBytes), writer.GetLengthWritten()); // At this point the buffer should contain 2 instances of Encoding3. reader.Init(buffer); reader.ImplicitProfileId = TestProfile_2; - TestNext(inSuite, reader); + TestNext(reader); - ReadEncoding3(inSuite, reader); + ReadEncoding3(reader); - TestNext(inSuite, reader); + TestNext(reader); - ReadEncoding3(inSuite, reader); + ReadEncoding3(reader); // Check that the reader is out of data - TestEnd(inSuite, reader); + TestEnd(reader); } -void CheckCircularTLVBufferStartMidway(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckCircularTLVBufferStartMidway) { // Write 40 bytes as 4 separate events into a 30 byte buffer. On // completion of the test, the buffer should contain 2 elements @@ -2357,7 +2347,7 @@ void CheckCircularTLVBufferStartMidway(nlTestSuite * inSuite, void * inContext) uint8_t backingStore[30]; CircularTLVWriter writer; CircularTLVReader reader; - TestTLVContext * context = static_cast(inContext); + TestTLVContext * context = &TestTLV::ctx; TLVCircularBuffer buffer(backingStore, 30, &(backingStore[15])); writer.Init(buffer); writer.ImplicitProfileId = TestProfile_2; @@ -2366,38 +2356,38 @@ void CheckCircularTLVBufferStartMidway(nlTestSuite * inSuite, void * inContext) context->mEvictedBytes = 0; buffer.mProcessEvictedElement = CountEvictedMembers; - buffer.mAppData = inContext; + buffer.mAppData = &TestTLV::ctx; writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); - NL_TEST_ASSERT(inSuite, context->mEvictionCount == 2); - NL_TEST_ASSERT(inSuite, context->mEvictedBytes == 18); - NL_TEST_ASSERT(inSuite, buffer.DataLength() == 22); - NL_TEST_ASSERT(inSuite, (buffer.DataLength() + context->mEvictedBytes) == writer.GetLengthWritten()); + EXPECT_EQ(context->mEvictionCount, 2); + EXPECT_EQ(context->mEvictedBytes, 18u); + EXPECT_EQ(buffer.DataLength(), 22u); + EXPECT_EQ((buffer.DataLength() + context->mEvictedBytes), writer.GetLengthWritten()); // At this point the buffer should contain 2 instances of Encoding3. reader.Init(buffer); reader.ImplicitProfileId = TestProfile_2; - TestNext(inSuite, reader); + TestNext(reader); - ReadEncoding3(inSuite, reader); + ReadEncoding3(reader); - TestNext(inSuite, reader); + TestNext(reader); - ReadEncoding3(inSuite, reader); + ReadEncoding3(reader); // Check that the reader is out of data - TestEnd(inSuite, reader); + TestEnd(reader); } -void CheckCircularTLVBufferEvictStraddlingEvent(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckCircularTLVBufferEvictStraddlingEvent) { // Write 95 bytes to the buffer as 9 different TLV elements: 1 // 7-byte element and 8 11-byte elements. @@ -2405,7 +2395,7 @@ void CheckCircularTLVBufferEvictStraddlingEvent(nlTestSuite * inSuite, void * in // and 7 elements should have been evicted in the last call to // WriteEncoding. - TestTLVContext * context = static_cast(inContext); + TestTLVContext * context = &TestTLV::ctx; uint8_t backingStore[30]; CircularTLVWriter writer; CircularTLVReader reader; @@ -2417,53 +2407,52 @@ void CheckCircularTLVBufferEvictStraddlingEvent(nlTestSuite * inSuite, void * in context->mEvictedBytes = 0; buffer.mProcessEvictedElement = CountEvictedMembers; - buffer.mAppData = inContext; + buffer.mAppData = &TestTLV::ctx; writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); // the write below will evict an element that straddles the buffer boundary. - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); - WriteEncoding3(inSuite, writer); + WriteEncoding3(writer); - NL_TEST_ASSERT(inSuite, - writer.GetLengthWritten() == - (8 * 11 + 7)); // 8 writes of Encoding3 (11 bytes each) and 7 bytes for the initial boolean. - NL_TEST_ASSERT(inSuite, buffer.DataLength() == 22); - NL_TEST_ASSERT(inSuite, (buffer.DataLength() + context->mEvictedBytes) == writer.GetLengthWritten()); - NL_TEST_ASSERT(inSuite, context->mEvictionCount == 7); + EXPECT_EQ(writer.GetLengthWritten(), + (8u * 11 + 7)); // 8 writes of Encoding3 (11 bytes each) and 7 bytes for the initial boolean. + EXPECT_EQ(buffer.DataLength(), 22u); + EXPECT_EQ((buffer.DataLength() + context->mEvictedBytes), writer.GetLengthWritten()); + EXPECT_EQ(context->mEvictionCount, 7); // At this point the buffer should contain 2 instances of Encoding3. reader.Init(buffer); reader.ImplicitProfileId = TestProfile_2; - TestNext(inSuite, reader); + TestNext(reader); - ReadEncoding3(inSuite, reader); + ReadEncoding3(reader); - TestNext(inSuite, reader); + TestNext(reader); - ReadEncoding3(inSuite, reader); + ReadEncoding3(reader); // Check that the reader is out of data - TestEnd(inSuite, reader); + TestEnd(reader); } -void CheckCircularTLVBufferEdge(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckCircularTLVBufferEdge) { - TestTLVContext * context = static_cast(inContext); + TestTLVContext * context = &TestTLV::ctx; CHIP_ERROR err; uint8_t backingStore[7]; uint8_t backingStore1[14]; @@ -2480,33 +2469,33 @@ void CheckCircularTLVBufferEdge(nlTestSuite * inSuite, void * inContext) context->mEvictedBytes = 0; buffer.mProcessEvictedElement = CountEvictedMembers; - buffer.mAppData = inContext; + buffer.mAppData = &TestTLV::ctx; // Test eviction for an element that fits in the underlying buffer exactly err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // At this point the buffer should contain only the boolean we just wrote reader.Init(buffer); reader.ImplicitProfileId = TestProfile_2; - TestNext(inSuite, reader); - TEST_GET_NOERROR(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); + TestNext(reader); + TEST_GET_NOERROR(reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); // Check that the reader is out of data - TestEnd(inSuite, reader); + TestEnd(reader); // verify that an element larger than the underlying buffer fails out. err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_END_OF_TLV); + EXPECT_EQ(err, CHIP_END_OF_TLV); // Verify reader correctness @@ -2520,23 +2509,23 @@ void CheckCircularTLVBufferEdge(nlTestSuite * inSuite, void * inContext) writer.ImplicitProfileId = TestProfile_2; err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(buffer1); reader.ImplicitProfileId = TestProfile_2; - TestNext(inSuite, reader); - TEST_GET_NOERROR(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); - TestEnd(inSuite, reader); + TestNext(reader); + TEST_GET_NOERROR(reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); + TestEnd(reader); buffer1.EvictHead(); reader.Init(buffer1); reader.ImplicitProfileId = TestProfile_2; - TestEnd(inSuite, reader); + TestEnd(reader); } writer.Init(buffer1); @@ -2546,14 +2535,14 @@ void CheckCircularTLVBufferEdge(nlTestSuite * inSuite, void * inContext) context->mEvictedBytes = 0; buffer1.mProcessEvictedElement = CountEvictedMembers; - buffer1.mAppData = inContext; + buffer1.mAppData = &TestTLV::ctx; // Two elements fit in the buffer exactly err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); @@ -2561,13 +2550,13 @@ void CheckCircularTLVBufferEdge(nlTestSuite * inSuite, void * inContext) reader.Init(buffer1); reader.ImplicitProfileId = TestProfile_2; - TestNext(inSuite, reader); - TEST_GET_NOERROR(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); + TestNext(reader); + TEST_GET_NOERROR(reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); - TestNext(inSuite, reader); - TEST_GET_NOERROR(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); + TestNext(reader); + TEST_GET_NOERROR(reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); - TestEnd(inSuite, reader); + TestEnd(reader); // Check that the eviction works as expected @@ -2577,11 +2566,11 @@ void CheckCircularTLVBufferEdge(nlTestSuite * inSuite, void * inContext) reader.Init(buffer1); reader.ImplicitProfileId = TestProfile_2; - TestNext(inSuite, reader); - TEST_GET_NOERROR(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); + TestNext(reader); + TEST_GET_NOERROR(reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); // Check that the reader is out of data - TestEnd(inSuite, reader); + TestEnd(reader); // Write another boolean, verify that the buffer is full and contains two booleans @@ -2589,22 +2578,22 @@ void CheckCircularTLVBufferEdge(nlTestSuite * inSuite, void * inContext) writer.ImplicitProfileId = TestProfile_2; err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Verify that we can read out two elements from the buffer reader.Init(buffer1); reader.ImplicitProfileId = TestProfile_2; - TestNext(inSuite, reader); - TEST_GET_NOERROR(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); + TestNext(reader); + TEST_GET_NOERROR(reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); - TestNext(inSuite, reader); - TEST_GET_NOERROR(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); + TestNext(reader); + TEST_GET_NOERROR(reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); - TestEnd(inSuite, reader); + TestEnd(reader); // Evict the elements from the buffer, verfiy that we have an // empty reader on our hands @@ -2615,9 +2604,9 @@ void CheckCircularTLVBufferEdge(nlTestSuite * inSuite, void * inContext) reader.Init(buffer1); reader.ImplicitProfileId = TestProfile_2; - TestEnd(inSuite, reader); + TestEnd(reader); } -void CheckTLVPutStringF(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckTLVPutStringF) { const size_t bufsize = 24; char strBuffer[bufsize]; @@ -2632,22 +2621,22 @@ void CheckTLVPutStringF(nlTestSuite * inSuite, void * inContext) snprintf(strBuffer, sizeof(strBuffer), "Sample string %u", static_cast(num)); err = writer.PutStringF(ProfileTag(TestProfile_1, 1), "Sample string %u", static_cast(num)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(backingStore, writer.GetLengthWritten()); err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.GetString(valStr, bufsize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, strncmp(valStr, strBuffer, bufsize) == 0); + EXPECT_EQ(strncmp(valStr, strBuffer, bufsize), 0); } -void CheckTLVPutStringSpan(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckTLVPutStringSpan) { const size_t bufsize = 24; char strBuffer[bufsize] = "Sample string"; @@ -2670,7 +2659,7 @@ void CheckTLVPutStringSpan(nlTestSuite * inSuite, void * inContext) strSpan = { strBuffer, static_cast(0xffffffffff) }; err = writer.PutString(ProfileTag(TestProfile_1, 1), strSpan); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); } { @@ -2680,23 +2669,23 @@ void CheckTLVPutStringSpan(nlTestSuite * inSuite, void * inContext) strSpan = { strBuffer, strlen("Sample string") }; err = writer.PutString(ProfileTag(TestProfile_1, 1), strSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(backingStore, writer.GetLengthWritten()); err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.GetString(valStr, bufsize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, strncmp(valStr, strBuffer, bufsize) == 0); + EXPECT_EQ(strncmp(valStr, strBuffer, bufsize), 0); } } -void CheckTLVPutStringFCircular(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckTLVPutStringFCircular) { const size_t bufsize = 40; char strBuffer[bufsize]; @@ -2714,30 +2703,30 @@ void CheckTLVPutStringFCircular(nlTestSuite * inSuite, void * inContext) snprintf(strBuffer, sizeof(strBuffer), "Sample string %u", static_cast(num)); err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.PutStringF(ProfileTag(TestProfile_1, 1), "Sample string %u", static_cast(num)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(buffer); // Skip over the initial element err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.GetString(valStr, bufsize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, strncmp(valStr, strBuffer, bufsize) == 0); + EXPECT_EQ(strncmp(valStr, strBuffer, bufsize), 0); // Verify that the PutStringF will handle correctly the case with the discontinuous buffer // This print will both stradle the boundary of the buffer and displace the previous two elements. @@ -2746,22 +2735,22 @@ void CheckTLVPutStringFCircular(nlTestSuite * inSuite, void * inContext) snprintf(strBuffer, sizeof(strBuffer), "Sample string %u", static_cast(num)); err = writer.PutStringF(ProfileTag(TestProfile_1, 1), "Sample string %u", static_cast(num)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(buffer); err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.GetString(valStr, bufsize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, strncmp(valStr, strBuffer, bufsize) == 0); + EXPECT_EQ(strncmp(valStr, strBuffer, bufsize), 0); } -void CheckTLVByteSpan(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckTLVByteSpan) { const size_t bufSize = 14; uint8_t bytesBuffer[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }; @@ -2774,25 +2763,25 @@ void CheckTLVByteSpan(nlTestSuite * inSuite, void * inContext) ByteSpan writerSpan(bytesBuffer); err = writer.Put(ProfileTag(TestProfile_1, 1), writerSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(backingStore, writer.GetLengthWritten()); err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); chip::ByteSpan readerSpan; err = reader.Get(readerSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(readerSpan.data(), bytesBuffer, sizeof(bytesBuffer)) == 0); + EXPECT_EQ(memcmp(readerSpan.data(), bytesBuffer, sizeof(bytesBuffer)), 0); } #define IS1_CHAR "\x1F" -void CheckTLVCharSpan(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckTLVCharSpan) { struct CharSpanTestCase { @@ -2823,25 +2812,25 @@ void CheckTLVCharSpan(nlTestSuite * inSuite, void * inContext) writer.Init(backingStore); err = writer.PutString(ProfileTag(TestProfile_1, 1), testCase.testString); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(backingStore, writer.GetLengthWritten()); err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); chip::CharSpan readerSpan; err = reader.Get(readerSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, strlen(testCase.expectedString) == readerSpan.size()); - NL_TEST_ASSERT(inSuite, memcmp(readerSpan.data(), testCase.expectedString, strlen(testCase.expectedString)) == 0); + EXPECT_EQ(strlen(testCase.expectedString), readerSpan.size()); + EXPECT_EQ(memcmp(readerSpan.data(), testCase.expectedString, strlen(testCase.expectedString)), 0); } } -void CheckTLVGetLocalizedStringIdentifier(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckTLVGetLocalizedStringIdentifier) { struct CharSpanTestCase { @@ -2881,19 +2870,19 @@ void CheckTLVGetLocalizedStringIdentifier(nlTestSuite * inSuite, void * inContex writer.Init(backingStore); err = writer.PutString(ProfileTag(TestProfile_1, 1), testCase.testString); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(backingStore, writer.GetLengthWritten()); err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); Optional readerLSID; err = reader.Get(readerLSID); - NL_TEST_ASSERT(inSuite, testCase.expectedResult == err); - NL_TEST_ASSERT(inSuite, testCase.expectedLSID == readerLSID); + EXPECT_EQ(testCase.expectedResult, err); + EXPECT_EQ(testCase.expectedLSID, readerLSID); } // Error case: A case of TLVReader buffer underrun. @@ -2907,14 +2896,14 @@ void CheckTLVGetLocalizedStringIdentifier(nlTestSuite * inSuite, void * inContex writer.Init(backingStore); err = writer.PutString(ProfileTag(TestProfile_1, 1), sCharSpanTestCases[2].testString); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(backingStore, writer.GetLengthWritten() - 1); err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_TLV_UNDERRUN); + EXPECT_EQ(err, CHIP_ERROR_TLV_UNDERRUN); } // Error case: the reader is on a bytestring, not utf-8 string. @@ -2929,23 +2918,23 @@ void CheckTLVGetLocalizedStringIdentifier(nlTestSuite * inSuite, void * inContex err = writer.PutBytes(ProfileTag(TestProfile_1, 1), reinterpret_cast(sCharSpanTestCases[2].testString), static_cast(strlen(sCharSpanTestCases[2].testString))); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(backingStore, writer.GetLengthWritten()); err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); Optional readerLSID; err = reader.Get(readerLSID); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); - NL_TEST_ASSERT(inSuite, readerLSID == Optional()); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(readerLSID, Optional()); } } -void CheckTLVSkipCircular(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckTLVSkipCircular) { const size_t bufsize = 40; // large enough s.t. 2 elements fit, 3rd causes eviction uint8_t backingStore[bufsize]; @@ -2959,33 +2948,33 @@ void CheckTLVSkipCircular(nlTestSuite * inSuite, void * inContext) writer.Init(buffer); err = writer.PutString(AnonymousTag(), testString); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.PutString(AnonymousTag(), testString); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.PutString(AnonymousTag(), testString); // This event straddles the boundary - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.PutString(AnonymousTag(), testString); // This one does not. - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(buffer); err = reader.Next(); // position the reader at the straddling element - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.Skip(); // // Test that the buf ptr is handled correctly within the ReadData() function. - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } /** * Test Buffer Overflow */ -void CheckBufferOverflow(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckBufferOverflow) { System::PacketBufferTLVReader reader; @@ -3007,10 +2996,10 @@ void CheckBufferOverflow(nlTestSuite * inSuite, void * inContext) writer.Init(buf.Retain(), /* useChainedBuffers = */ true); writer.ImplicitProfileId = TestProfile_2; - WriteEncoding1(inSuite, writer); + WriteEncoding1(writer); } - TestBufferContents(inSuite, buf, Encoding1, sizeof(Encoding1)); + TestBufferContents(buf, Encoding1, sizeof(Encoding1)); // Compact the buffer, since we don't allow reading from chained // buffers. @@ -3019,7 +3008,7 @@ void CheckBufferOverflow(nlTestSuite * inSuite, void * inContext) reader.Init(buf.Retain()); reader.ImplicitProfileId = TestProfile_2; - ReadEncoding1(inSuite, reader); + ReadEncoding1(reader); buf = System::PacketBufferHandle::New(sizeof(Encoding1), 0); } @@ -3050,7 +3039,7 @@ static const uint8_t sIdentifyResponseBuf[] = static const uint32_t kIdentifyResponseLen = 53; -void CheckStrictAliasing(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckStrictAliasing) { const uint32_t kProfile_Id = 0x0000000e; CHIP_ERROR err = CHIP_NO_ERROR; @@ -3060,15 +3049,15 @@ void CheckStrictAliasing(nlTestSuite * inSuite, void * inContext) reader.ImplicitProfileId = kProfile_Id; err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reader.GetTag() == ProfileTag(kProfile_Id, 1)); + EXPECT_EQ(reader.GetTag(), ProfileTag(kProfile_Id, 1)); } /** * Test CHIP TLV Writer Copy Container */ -void TestTLVWriterCopyContainer(nlTestSuite * inSuite) +void TestTLVWriterCopyContainer() { uint8_t buf[2048]; @@ -3079,19 +3068,19 @@ void TestTLVWriterCopyContainer(nlTestSuite * inSuite) reader.Init(Encoding1); reader.ImplicitProfileId = TestProfile_2; - TestNext(inSuite, reader); + TestNext(reader); writer.Init(buf); writer.ImplicitProfileId = TestProfile_2; CHIP_ERROR err = writer.CopyContainer(reader); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t encodedLen = writer.GetLengthWritten(); - NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding1)); + EXPECT_EQ(encodedLen, sizeof(Encoding1)); int memcmpRes = memcmp(buf, Encoding1, encodedLen); - NL_TEST_ASSERT(inSuite, memcmpRes == 0); + EXPECT_EQ(memcmpRes, 0); } { @@ -3101,20 +3090,20 @@ void TestTLVWriterCopyContainer(nlTestSuite * inSuite) writer.ImplicitProfileId = TestProfile_2; CHIP_ERROR err = writer.CopyContainer(ProfileTag(TestProfile_1, 1), Encoding1, sizeof(Encoding1)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t encodedLen = writer.GetLengthWritten(); - NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding1)); + EXPECT_EQ(encodedLen, sizeof(Encoding1)); int memcmpRes = memcmp(buf, Encoding1, encodedLen); - NL_TEST_ASSERT(inSuite, memcmpRes == 0); + EXPECT_EQ(memcmpRes, 0); } } /** * Test CHIP TLV Writer Copy Element */ -void TestTLVWriterCopyElement(nlTestSuite * inSuite) +void TestTLVWriterCopyElement() { CHIP_ERROR err; uint8_t expectedBuf[2048], testBuf[2048]; @@ -3130,18 +3119,18 @@ void TestTLVWriterCopyElement(nlTestSuite * inSuite) writer.ImplicitProfileId = TestProfile_2; err = writer.StartContainer(AnonymousTag(), kTLVType_Structure, outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); for (int i = 0; i < kRepeatCount; i++) { - WriteEncoding1(inSuite, writer); + WriteEncoding1(writer); } err = writer.EndContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); expectedLen = writer.GetLengthWritten(); @@ -3149,7 +3138,7 @@ void TestTLVWriterCopyElement(nlTestSuite * inSuite) writer.ImplicitProfileId = TestProfile_2; err = writer.StartContainer(AnonymousTag(), kTLVType_Structure, outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); for (int i = 0; i < kRepeatCount; i++) { @@ -3158,99 +3147,99 @@ void TestTLVWriterCopyElement(nlTestSuite * inSuite) reader.Init(Encoding1); reader.ImplicitProfileId = TestProfile_2; - TestNext(inSuite, reader); + TestNext(reader); err = writer.CopyElement(reader); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = writer.EndContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); testLen = writer.GetLengthWritten(); - NL_TEST_ASSERT(inSuite, testLen == expectedLen); + EXPECT_EQ(testLen, expectedLen); int memcmpRes = memcmp(testBuf, expectedBuf, testLen); - NL_TEST_ASSERT(inSuite, memcmpRes == 0); + EXPECT_EQ(memcmpRes, 0); } -void PreserveSizeWrite(nlTestSuite * inSuite, TLVWriter & writer, bool preserveSize) +void PreserveSizeWrite(TLVWriter & writer, bool preserveSize) { CHIP_ERROR err; TLVWriter writer2; // TLVTagControl::FullyQualified_8Bytes err = writer.Put(ProfileTag(TestProfile_1, 4000000000ULL), static_cast(40000000000ULL), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Put(ProfileTag(TestProfile_1, 4000000000ULL), static_cast(12345), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Put(ProfileTag(TestProfile_1, 4000000000ULL), static_cast(1.0)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); { TLVWriter writer3; err = writer2.OpenContainer(ContextTag(0), kTLVType_Array, writer3); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.Put(AnonymousTag(), static_cast(42), preserveSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.Put(AnonymousTag(), static_cast(42), preserveSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.Put(AnonymousTag(), static_cast(42), preserveSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.Put(AnonymousTag(), static_cast(40000000000ULL), preserveSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.Put(AnonymousTag(), static_cast(-17), preserveSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.Put(AnonymousTag(), static_cast(-17), preserveSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.Put(AnonymousTag(), static_cast(-170000), preserveSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.Put(AnonymousTag(), static_cast(-170000), preserveSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // the below cases are for full coverage of PUTs err = writer3.Put(AnonymousTag(), static_cast(65535), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.Put(AnonymousTag(), static_cast(32767), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer3.Put(AnonymousTag(), static_cast(40000000000ULL), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.CloseContainer(writer3); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = writer.CloseContainer(writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } /** * Test CHIP TLV Writer with Preserve Size */ -void TestTLVWriterPreserveSize(nlTestSuite * inSuite) +void TestTLVWriterPreserveSize() { uint8_t buf[2048]; TLVWriter writer; @@ -3258,16 +3247,16 @@ void TestTLVWriterPreserveSize(nlTestSuite * inSuite) writer.Init(buf); writer.ImplicitProfileId = TestProfile_2; - PreserveSizeWrite(inSuite, writer, true); + PreserveSizeWrite(writer, true); uint32_t encodedLen = writer.GetLengthWritten(); - NL_TEST_ASSERT(inSuite, encodedLen == 105); + EXPECT_EQ(encodedLen, 105u); } /** * Test error handling of CHIP TLV Writer */ -void TestTLVWriterErrorHandling(nlTestSuite * inSuite) +void TestTLVWriterErrorHandling() { CHIP_ERROR err; uint8_t buf[2048]; @@ -3278,45 +3267,45 @@ void TestTLVWriterErrorHandling(nlTestSuite * inSuite) // OpenContainer() for non-container err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Boolean, writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); // Since OpenContainer failed, writer2 remains uninitialized. writer2.Init(nullptr, 0); // CloseContainer() for non-container err = writer.CloseContainer(writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); // OpenContainer() failure err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer3); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // CloseContainer() failure err = writer.CloseContainer(writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_TLV_CONTAINER_OPEN); + EXPECT_EQ(err, CHIP_ERROR_TLV_CONTAINER_OPEN); // StartContainer() TLVType outerContainerType; err = writer.StartContainer(ProfileTag(TestProfile_2, 4000000000ULL), kTLVType_Boolean, outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); // EndContainer() outerContainerType = kTLVType_Boolean; err = writer.EndContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); // PutPreEncodedContainer() TLVReader reader; reader.Init(buf, 2048); err = writer.PutPreEncodedContainer(ProfileTag(TestProfile_2, 4000000000ULL), kTLVType_Boolean, reader.GetReadPoint(), reader.GetRemainingLength()); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(err, CHIP_ERROR_INVALID_ARGUMENT); } -void TestTLVEmptyString(nlTestSuite * inSuite) +void TestTLVEmptyString() { uint8_t buf[2]; TLVWriter writer; @@ -3326,42 +3315,42 @@ void TestTLVEmptyString(nlTestSuite * inSuite) writer.Init(buf); err = writer.PutString(AnonymousTag(), nullptr, 0); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); TLVReader reader; reader.Init(buf); err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.Get(s); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, s.data() == nullptr); - NL_TEST_ASSERT(inSuite, s.size() == 0); + EXPECT_EQ(s.data(), nullptr); + EXPECT_EQ(s.size(), 0u); } /** * Test CHIP TLV Writer */ -void CheckTLVWriter(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckTLVWriter) { - TestTLVWriterCopyContainer(inSuite); + TestTLVWriterCopyContainer(); - TestTLVWriterCopyElement(inSuite); + TestTLVWriterCopyElement(); - TestTLVWriterPreserveSize(inSuite); + TestTLVWriterPreserveSize(); - TestTLVWriterErrorHandling(inSuite); + TestTLVWriterErrorHandling(); - TestTLVEmptyString(inSuite); + TestTLVEmptyString(); } -void SkipNonContainer(nlTestSuite * inSuite) +void SkipNonContainer() { TLVReader reader; const uint8_t * readpoint1 = nullptr; @@ -3370,19 +3359,19 @@ void SkipNonContainer(nlTestSuite * inSuite) reader.Init(Encoding1); reader.ImplicitProfileId = TestProfile_2; - TestSkip(inSuite, reader); + TestSkip(reader); readpoint1 = reader.GetReadPoint(); // Skip again, to check the operation is idempotent - TestSkip(inSuite, reader); + TestSkip(reader); readpoint2 = reader.GetReadPoint(); - NL_TEST_ASSERT(inSuite, readpoint1 == readpoint2); + EXPECT_EQ(readpoint1, readpoint2); } -void SkipContainer(nlTestSuite * inSuite) +void SkipContainer() { TLVReader reader; const uint8_t * readpoint1 = nullptr; @@ -3391,179 +3380,176 @@ void SkipContainer(nlTestSuite * inSuite) reader.Init(Encoding1); reader.ImplicitProfileId = TestProfile_2; - TestNext(inSuite, reader); + TestNext(reader); - TestSkip(inSuite, reader); + TestSkip(reader); readpoint1 = reader.GetReadPoint(); // Skip again, to check the operation is idempotent - TestSkip(inSuite, reader); + TestSkip(reader); readpoint2 = reader.GetReadPoint(); - NL_TEST_ASSERT(inSuite, readpoint1 == readpoint2); + EXPECT_EQ(readpoint1, readpoint2); } -void NextContainer(nlTestSuite * inSuite) +void NextContainer() { TLVReader reader; reader.Init(Encoding1); reader.ImplicitProfileId = TestProfile_2; - TestNext(inSuite, reader); + TestNext(reader); CHIP_ERROR err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_END_OF_TLV); + EXPECT_EQ(err, CHIP_END_OF_TLV); } /** * Test CHIP TLV Reader Skip functions */ -void TestTLVReaderSkip(nlTestSuite * inSuite) +void TestTLVReaderSkip() { - SkipNonContainer(inSuite); + SkipNonContainer(); - SkipContainer(inSuite); + SkipContainer(); - NextContainer(inSuite); + NextContainer(); } /** * Test CHIP TLV Reader Dup functions */ -void TestTLVReaderDup(nlTestSuite * inSuite) +void TestTLVReaderDup() { TLVReader reader; reader.Init(Encoding1); reader.ImplicitProfileId = TestProfile_2; - TestNext(inSuite, reader); + TestNext(reader); { TLVReader reader2; - TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader2); + TestAndOpenContainer(reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader2); - TestNext(inSuite, reader2); + TestNext(reader2); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); + TEST_GET_NOERROR(reader2, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); - TestNext(inSuite, reader2); + TestNext(reader2); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); + TEST_GET_NOERROR(reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); - TestNext(inSuite, reader2); + TestNext(reader2); { TLVReader reader3; - TestAndOpenContainer(inSuite, reader2, kTLVType_Array, ContextTag(0), reader3); + TestAndOpenContainer(reader2, kTLVType_Array, ContextTag(0), reader3); - TestNext(inSuite, reader3); + TestNext(reader3); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); - TEST_GET(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42), - CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42), - CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42)); + TEST_GET(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42), CHIP_ERROR_WRONG_TLV_TYPE); + TEST_GET(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(42), CHIP_ERROR_WRONG_TLV_TYPE); - TestNext(inSuite, reader3); + TestNext(reader3); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-17)); - TestNext(inSuite, reader3); + TestNext(reader3); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-170000)); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-170000)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-170000)); + TEST_GET_NOERROR(reader3, kTLVType_SignedInteger, AnonymousTag(), static_cast(-170000)); - TestNext(inSuite, reader3); + TestNext(reader3); - TEST_GET(inSuite, reader3, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(40000000000ULL), + TEST_GET(reader3, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(40000000000ULL), CHIP_ERROR_WRONG_TLV_TYPE); - TEST_GET_NOERROR(inSuite, reader3, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(40000000000ULL)); + TEST_GET_NOERROR(reader3, kTLVType_UnsignedInteger, AnonymousTag(), static_cast(40000000000ULL)); - TestNext(inSuite, reader3); + TestNext(reader3); { TLVReader reader4; - TestAndOpenContainer(inSuite, reader3, kTLVType_Structure, AnonymousTag(), reader4); + TestAndOpenContainer(reader3, kTLVType_Structure, AnonymousTag(), reader4); - TestEndAndCloseContainer(inSuite, reader3, reader4); + TestEndAndCloseContainer(reader3, reader4); } - TestNext(inSuite, reader3); + TestNext(reader3); { TLVReader reader5; - TestAndOpenContainer(inSuite, reader3, kTLVType_List, AnonymousTag(), reader5); + TestAndOpenContainer(reader3, kTLVType_List, AnonymousTag(), reader5); - TestNext(inSuite, reader5); + TestNext(reader5); - TestNull(inSuite, reader5, ProfileTag(TestProfile_1, 17)); + TestNull(reader5, ProfileTag(TestProfile_1, 17)); - TestNext(inSuite, reader5); + TestNext(reader5); - TestNull(inSuite, reader5, ProfileTag(TestProfile_2, 900000)); + TestNull(reader5, ProfileTag(TestProfile_2, 900000)); - TestNext(inSuite, reader5); + TestNext(reader5); - TestNull(inSuite, reader5, AnonymousTag()); + TestNull(reader5, AnonymousTag()); - TestNext(inSuite, reader5); + TestNext(reader5); { TLVType outerContainerType; - TestAndEnterContainer(inSuite, reader5, kTLVType_Structure, ProfileTag(TestProfile_2, 4000000000ULL), + TestAndEnterContainer(reader5, kTLVType_Structure, ProfileTag(TestProfile_2, 4000000000ULL), outerContainerType); - TestNext(inSuite, reader5); + TestNext(reader5); - TestDupString(inSuite, reader5, CommonTag(70000), sLargeString); + TestDupString(reader5, CommonTag(70000), sLargeString); - TestEndAndExitContainer(inSuite, reader5, outerContainerType); + TestEndAndExitContainer(reader5, outerContainerType); } - TestEndAndCloseContainer(inSuite, reader3, reader5); + TestEndAndCloseContainer(reader3, reader5); } - TestEndAndCloseContainer(inSuite, reader2, reader3); + TestEndAndCloseContainer(reader2, reader3); } - TestNext(inSuite, reader2); + TestNext(reader2); - TestDupBytes(inSuite, reader2, ProfileTag(TestProfile_1, 5), reinterpret_cast("This is a test"), 14); + TestDupBytes(reader2, ProfileTag(TestProfile_1, 5), reinterpret_cast("This is a test"), 14); - TestNext(inSuite, reader2); + TestNext(reader2); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65535), 17.9f); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65535), - static_cast(17.9f)); + TEST_GET_NOERROR(reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65535), 17.9f); + TEST_GET_NOERROR(reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65535), static_cast(17.9f)); - TestNext(inSuite, reader2); + TestNext(reader2); - TEST_GET_NOERROR(inSuite, reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65536), 17.9); + TEST_GET_NOERROR(reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65536), 17.9); - TestEndAndCloseContainer(inSuite, reader, reader2); + TestEndAndCloseContainer(reader, reader2); } - TestEnd(inSuite, reader); + TestEnd(reader); } /** * Test error handling of CHIP TLV Reader */ -void TestTLVReaderErrorHandling(nlTestSuite * inSuite) +void TestTLVReaderErrorHandling() { CHIP_ERROR err; uint8_t buf[2048] = { 0 }; @@ -3575,118 +3561,118 @@ void TestTLVReaderErrorHandling(nlTestSuite * inSuite) // Get(bool&) bool val; err = reader.Get(val); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); // Get(float&) float numF; err = reader.Get(numF); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); // Get(double&) double numD; err = reader.Get(numD); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); // Get(uint64_t&) uint64_t num; err = reader.Get(num); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); // GetBytes() uint8_t bBuf[16]; err = reader.GetBytes(bBuf, sizeof(bBuf)); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); // GetString() char sBuf[16]; err = reader.GetString(sBuf, sizeof(sBuf)); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); // OpenContainer() TLVReader reader2; err = reader.OpenContainer(reader2); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); // CloseContainer() err = reader.CloseContainer(reader2); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); // EnterContainer() TLVType outerContainerType = kTLVType_Boolean; err = reader.EnterContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); // DupString() char * str = static_cast(chip::Platform::MemoryAlloc(16)); err = reader.DupString(str); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); chip::Platform::MemoryFree(str); // GetDataPtr() const uint8_t * data = static_cast(chip::Platform::MemoryAlloc(16)); err = reader.GetDataPtr(data); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); chip::Platform::MemoryFree(const_cast(data)); } -void TestTLVReaderExpect(nlTestSuite * inSuite) +void TestTLVReaderExpect() { // Prepare some test data uint8_t buffer[20]; TLVWriter writer; writer.Init(buffer, sizeof(buffer)); TLVType outerContainer; - NL_TEST_ASSERT_SUCCESS(inSuite, writer.StartContainer(AnonymousTag(), kTLVType_Structure, outerContainer)); - NL_TEST_ASSERT_SUCCESS(inSuite, writer.PutBoolean(ContextTag(23), false)); - NL_TEST_ASSERT_SUCCESS(inSuite, writer.EndContainer(outerContainer)); + EXPECT_EQ(CHIP_NO_ERROR, writer.StartContainer(AnonymousTag(), kTLVType_Structure, outerContainer)); + EXPECT_EQ(CHIP_NO_ERROR, writer.PutBoolean(ContextTag(23), false)); + EXPECT_EQ(CHIP_NO_ERROR, writer.EndContainer(outerContainer)); TLVReader reader; reader.Init(buffer, writer.GetLengthWritten()); // Positioned before the first element - NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_NotSpecified); + EXPECT_EQ(reader.GetType(), kTLVType_NotSpecified); - NL_TEST_ASSERT(inSuite, reader.Expect(AnonymousTag()) == CHIP_ERROR_WRONG_TLV_TYPE); - NL_TEST_ASSERT(inSuite, reader.Expect(ContextTag(23)) == CHIP_ERROR_WRONG_TLV_TYPE); - NL_TEST_ASSERT(inSuite, reader.Expect(kTLVType_Boolean, AnonymousTag()) == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(reader.Expect(AnonymousTag()), CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(reader.Expect(ContextTag(23)), CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(reader.Expect(kTLVType_Boolean, AnonymousTag()), CHIP_ERROR_WRONG_TLV_TYPE); // Positioned on kTLVType_Structure / AnonymousTag(), - NL_TEST_ASSERT_SUCCESS(inSuite, reader.Next()); - NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_Structure); - NL_TEST_ASSERT(inSuite, reader.GetTag() == AnonymousTag()); + EXPECT_EQ(CHIP_NO_ERROR, reader.Next()); + EXPECT_EQ(reader.GetType(), kTLVType_Structure); + EXPECT_EQ(reader.GetTag(), AnonymousTag()); - NL_TEST_ASSERT(inSuite, reader.Expect(ContextTag(23)) == CHIP_ERROR_UNEXPECTED_TLV_ELEMENT); - NL_TEST_ASSERT_SUCCESS(inSuite, reader.Expect(AnonymousTag())); + EXPECT_EQ(reader.Expect(ContextTag(23)), CHIP_ERROR_UNEXPECTED_TLV_ELEMENT); + EXPECT_EQ(CHIP_NO_ERROR, reader.Expect(AnonymousTag())); - NL_TEST_ASSERT(inSuite, reader.Expect(kTLVType_SignedInteger, AnonymousTag()) == CHIP_ERROR_WRONG_TLV_TYPE); - NL_TEST_ASSERT_SUCCESS(inSuite, reader.Expect(kTLVType_Structure, AnonymousTag())); + EXPECT_EQ(reader.Expect(kTLVType_SignedInteger, AnonymousTag()), CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(CHIP_NO_ERROR, reader.Expect(kTLVType_Structure, AnonymousTag())); // Positioned before first struct element - NL_TEST_ASSERT_SUCCESS(inSuite, reader.EnterContainer(outerContainer)); - NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_NotSpecified); + EXPECT_EQ(CHIP_NO_ERROR, reader.EnterContainer(outerContainer)); + EXPECT_EQ(reader.GetType(), kTLVType_NotSpecified); - NL_TEST_ASSERT(inSuite, reader.Expect(AnonymousTag()) == CHIP_ERROR_WRONG_TLV_TYPE); - NL_TEST_ASSERT(inSuite, reader.Expect(ContextTag(23)) == CHIP_ERROR_WRONG_TLV_TYPE); - NL_TEST_ASSERT(inSuite, reader.Expect(kTLVType_Boolean, AnonymousTag()) == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(reader.Expect(AnonymousTag()), CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(reader.Expect(ContextTag(23)), CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(reader.Expect(kTLVType_Boolean, AnonymousTag()), CHIP_ERROR_WRONG_TLV_TYPE); // Positioned on kTLVType_Boolean / ContextTag(23) - NL_TEST_ASSERT_SUCCESS(inSuite, reader.Next()); - NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_Boolean); - NL_TEST_ASSERT(inSuite, reader.GetTag() == ContextTag(23)); + EXPECT_EQ(CHIP_NO_ERROR, reader.Next()); + EXPECT_EQ(reader.GetType(), kTLVType_Boolean); + EXPECT_EQ(reader.GetTag(), ContextTag(23)); - NL_TEST_ASSERT(inSuite, reader.Expect(AnonymousTag()) == CHIP_ERROR_UNEXPECTED_TLV_ELEMENT); - NL_TEST_ASSERT(inSuite, reader.Expect(ContextTag(42)) == CHIP_ERROR_UNEXPECTED_TLV_ELEMENT); - NL_TEST_ASSERT_SUCCESS(inSuite, reader.Expect(ContextTag(23))); + EXPECT_EQ(reader.Expect(AnonymousTag()), CHIP_ERROR_UNEXPECTED_TLV_ELEMENT); + EXPECT_EQ(reader.Expect(ContextTag(42)), CHIP_ERROR_UNEXPECTED_TLV_ELEMENT); + EXPECT_EQ(CHIP_NO_ERROR, reader.Expect(ContextTag(23))); - NL_TEST_ASSERT(inSuite, reader.Expect(kTLVType_SignedInteger, ContextTag(23)) == CHIP_ERROR_WRONG_TLV_TYPE); - NL_TEST_ASSERT_SUCCESS(inSuite, reader.Expect(kTLVType_Boolean, ContextTag(23))); + EXPECT_EQ(reader.Expect(kTLVType_SignedInteger, ContextTag(23)), CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(CHIP_NO_ERROR, reader.Expect(kTLVType_Boolean, ContextTag(23))); } /** * Test that CHIP TLV reader returns an error when a read is requested that * would truncate the output. */ -void TestTLVReaderTruncatedReads(nlTestSuite * inSuite) +void TestTLVReaderTruncatedReads() { uint8_t buf[2048]; TLVWriter writer; @@ -3700,23 +3686,23 @@ void TestTLVReaderTruncatedReads(nlTestSuite * inSuite) writer.ImplicitProfileId = TestProfile_2; err = writer.Put(AnonymousTag(), double{ 12.5 }); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Test reading values from the buffer reader.Init(buf); - TestNext(inSuite, reader); + TestNext(reader); - TEST_GET_NOERROR(inSuite, reader, kTLVType_FloatingPointNumber, AnonymousTag(), 12.5); + TEST_GET_NOERROR(reader, kTLVType_FloatingPointNumber, AnonymousTag(), 12.5); err = reader.Get(outF); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); + EXPECT_EQ(err, CHIP_ERROR_WRONG_TLV_TYPE); } /** * Test CHIP TLV Reader in a use case */ -void TestTLVReaderInPractice(nlTestSuite * inSuite) +void TestTLVReaderInPractice() { uint8_t buf[2048]; TLVWriter writer; @@ -3725,27 +3711,25 @@ void TestTLVReaderInPractice(nlTestSuite * inSuite) writer.Init(buf); writer.ImplicitProfileId = TestProfile_2; - PreserveSizeWrite(inSuite, writer, true); + PreserveSizeWrite(writer, true); reader.Init(buf); - TestNext(inSuite, reader); + TestNext(reader); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, ProfileTag(TestProfile_1, 4000000000ULL), + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, ProfileTag(TestProfile_1, 4000000000ULL), static_cast(40000000000ULL)); - TestNext(inSuite, reader); + TestNext(reader); - TEST_GET_NOERROR(inSuite, reader, kTLVType_SignedInteger, ProfileTag(TestProfile_1, 4000000000ULL), - static_cast(12345)); + TEST_GET_NOERROR(reader, kTLVType_SignedInteger, ProfileTag(TestProfile_1, 4000000000ULL), static_cast(12345)); - TestNext(inSuite, reader); + TestNext(reader); - TEST_GET_NOERROR(inSuite, reader, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_1, 4000000000ULL), - static_cast(1.0)); + TEST_GET_NOERROR(reader, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_1, 4000000000ULL), static_cast(1.0)); } -void TestTLVReader_NextOverContainer_ProcessElement(nlTestSuite * inSuite, TLVReader & reader, void * context) +void TestTLVReader_NextOverContainer_ProcessElement(TLVReader & reader, void * context) { CHIP_ERROR err, nextRes1, nextRes2; TLVType outerContainerType; @@ -3759,38 +3743,38 @@ void TestTLVReader_NextOverContainer_ProcessElement(nlTestSuite * inSuite, TLVRe // Manually advance one of the readers to the element immediately after the container (if any). err = readerClone1.EnterContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - ForEachElement(inSuite, readerClone1, nullptr, nullptr); + EXPECT_EQ(err, CHIP_NO_ERROR); + ForEachElement(readerClone1, nullptr, nullptr); err = readerClone1.ExitContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); nextRes1 = readerClone1.Next(); - NL_TEST_ASSERT(inSuite, nextRes1 == CHIP_NO_ERROR || nextRes1 == CHIP_END_OF_TLV); + EXPECT_TRUE(nextRes1 == CHIP_NO_ERROR || nextRes1 == CHIP_END_OF_TLV); // For the other reader, skip over the entire container using the Next() method. nextRes2 = readerClone2.Next(); - NL_TEST_ASSERT(inSuite, nextRes2 == CHIP_NO_ERROR || nextRes2 == CHIP_END_OF_TLV); + EXPECT_TRUE(nextRes2 == CHIP_NO_ERROR || nextRes2 == CHIP_END_OF_TLV); // Verify the two readers end up in the same state/position. - NL_TEST_ASSERT(inSuite, nextRes1 == nextRes2); - NL_TEST_ASSERT(inSuite, readerClone1.GetType() == readerClone2.GetType()); - NL_TEST_ASSERT(inSuite, readerClone1.GetReadPoint() == readerClone2.GetReadPoint()); + EXPECT_EQ(nextRes1, nextRes2); + EXPECT_EQ(readerClone1.GetType(), readerClone2.GetType()); + EXPECT_EQ(readerClone1.GetReadPoint(), readerClone2.GetReadPoint()); } } /** * Test using CHIP TLV Reader Next() method to skip over containers. */ -void TestTLVReader_NextOverContainer(nlTestSuite * inSuite) +void TestTLVReader_NextOverContainer() { TLVReader reader; reader.Init(Encoding1); reader.ImplicitProfileId = TestProfile_2; - ForEachElement(inSuite, reader, nullptr, TestTLVReader_NextOverContainer_ProcessElement); + ForEachElement(reader, nullptr, TestTLVReader_NextOverContainer_ProcessElement); } -void TestTLVReader_SkipOverContainer_ProcessElement(nlTestSuite * inSuite, TLVReader & reader, void * context) +void TestTLVReader_SkipOverContainer_ProcessElement(TLVReader & reader, void * context) { CHIP_ERROR err; TLVType outerContainerType; @@ -3804,83 +3788,83 @@ void TestTLVReader_SkipOverContainer_ProcessElement(nlTestSuite * inSuite, TLVRe // Manually advance one of the readers to immediately after the container. err = readerClone1.EnterContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - ForEachElement(inSuite, readerClone1, nullptr, nullptr); + EXPECT_EQ(err, CHIP_NO_ERROR); + ForEachElement(readerClone1, nullptr, nullptr); err = readerClone1.ExitContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // For the other reader, skip over the entire container using the Skip() method. err = readerClone2.Skip(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Verify the two readers end up in the same state/position. - NL_TEST_ASSERT(inSuite, readerClone1.GetType() == readerClone2.GetType()); - NL_TEST_ASSERT(inSuite, readerClone1.GetReadPoint() == readerClone2.GetReadPoint()); + EXPECT_EQ(readerClone1.GetType(), readerClone2.GetType()); + EXPECT_EQ(readerClone1.GetReadPoint(), readerClone2.GetReadPoint()); } } /** * Test using CHIP TLV Reader Skip() method to skip over containers. */ -void TestTLVReader_SkipOverContainer(nlTestSuite * inSuite) +void TestTLVReader_SkipOverContainer() { TLVReader reader; reader.Init(Encoding1); reader.ImplicitProfileId = TestProfile_2; - ForEachElement(inSuite, reader, nullptr, TestTLVReader_SkipOverContainer_ProcessElement); + ForEachElement(reader, nullptr, TestTLVReader_SkipOverContainer_ProcessElement); } /** * Tests using an uninitialized TLVReader. */ -void TestTLVReaderUninitialized(nlTestSuite * inSuite) +void TestTLVReaderUninitialized() { TLVReader reader; - NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_NotSpecified); - NL_TEST_ASSERT(inSuite, reader.GetLength() == 0); - NL_TEST_ASSERT(inSuite, reader.GetControlByte() == kTLVControlByte_NotSpecified); - NL_TEST_ASSERT(inSuite, reader.GetContainerType() == kTLVType_NotSpecified); - NL_TEST_ASSERT(inSuite, reader.GetLengthRead() == 0); - NL_TEST_ASSERT(inSuite, reader.GetRemainingLength() == 0); - NL_TEST_ASSERT(inSuite, reader.GetTotalLength() == 0); - NL_TEST_ASSERT(inSuite, reader.GetBackingStore() == nullptr); - NL_TEST_ASSERT(inSuite, reader.IsElementDouble() == false); - NL_TEST_ASSERT(inSuite, reader.GetReadPoint() == nullptr); - NL_TEST_ASSERT(inSuite, reader.ImplicitProfileId == kProfileIdNotSpecified); - NL_TEST_ASSERT(inSuite, reader.AppData == nullptr); + EXPECT_EQ(reader.GetType(), kTLVType_NotSpecified); + EXPECT_EQ(reader.GetLength(), 0u); + EXPECT_EQ(reader.GetControlByte(), kTLVControlByte_NotSpecified); + EXPECT_EQ(reader.GetContainerType(), kTLVType_NotSpecified); + EXPECT_EQ(reader.GetLengthRead(), 0u); + EXPECT_EQ(reader.GetRemainingLength(), 0u); + EXPECT_EQ(reader.GetTotalLength(), 0u); + EXPECT_EQ(reader.GetBackingStore(), nullptr); + EXPECT_EQ(reader.IsElementDouble(), false); + EXPECT_EQ(reader.GetReadPoint(), nullptr); + EXPECT_EQ(reader.ImplicitProfileId, kProfileIdNotSpecified); + EXPECT_EQ(reader.AppData, nullptr); } /** * Test CHIP TLV Reader */ -void CheckTLVReader(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckTLVReader) { - TestTLVReaderSkip(inSuite); + TestTLVReaderSkip(); - TestTLVReaderDup(inSuite); + TestTLVReaderDup(); - TestTLVReaderErrorHandling(inSuite); + TestTLVReaderErrorHandling(); - TestTLVReaderExpect(inSuite); + TestTLVReaderExpect(); - TestTLVReaderTruncatedReads(inSuite); + TestTLVReaderTruncatedReads(); - TestTLVReaderInPractice(inSuite); + TestTLVReaderInPractice(); - TestTLVReader_NextOverContainer(inSuite); + TestTLVReader_NextOverContainer(); - TestTLVReader_SkipOverContainer(inSuite); + TestTLVReader_SkipOverContainer(); - TestTLVReaderUninitialized(inSuite); + TestTLVReaderUninitialized(); } /** * Test CHIP TLV Items */ -static void TestItems(nlTestSuite * inSuite, void * inContext) +static void TestItems() { CHIP_ERROR err = CHIP_NO_ERROR; @@ -3891,83 +3875,83 @@ static void TestItems(nlTestSuite * inSuite, void * inContext) TLVWriter writer2; err = writer.OpenContainer(AnonymousTag(), kTLVType_Array, writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); { err = writer2.PutBoolean(AnonymousTag(), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(-1)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(-2)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(-3)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(-4)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(-5.5)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(-3.14159265358979323846)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = writer.CloseContainer(writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.OpenContainer(AnonymousTag(), kTLVType_Array, writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); { err = writer2.PutBoolean(AnonymousTag(), false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(1)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(2)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(3)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(4)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(5)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(6)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(7)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(8)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(9.9)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.Put(AnonymousTag(), static_cast(3.14159265358979323846)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = writer.CloseContainer(writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } /** * Test CHIP TLV Containers */ -static void TestContainers(nlTestSuite * inSuite, void * inContext) +static void TestContainers() { CHIP_ERROR err = CHIP_NO_ERROR; TLVWriter writer; @@ -3977,52 +3961,52 @@ static void TestContainers(nlTestSuite * inSuite, void * inContext) TLVWriter writer2; err = writer.OpenContainer(AnonymousTag(), kTLVType_Array, writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); TLVType type = writer2.GetContainerType(); - NL_TEST_ASSERT(inSuite, type == kTLVType_Array); + EXPECT_EQ(type, kTLVType_Array); err = writer.CloseContainer(writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.OpenContainer(AnonymousTag(), kTLVType_Structure, writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); type = writer2.GetContainerType(); - NL_TEST_ASSERT(inSuite, type == kTLVType_Structure); + EXPECT_EQ(type, kTLVType_Structure); err = writer.CloseContainer(writer2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } /** * Test CHIP TLV Basics */ -static void CheckTLVBasics(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckTLVBasics) { - TestItems(inSuite, inContext); - TestContainers(inSuite, inContext); + TestItems(); + TestContainers(); } /** * Test CHIP TLV Updater */ -static void CheckCHIPUpdater(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckCHIPUpdater) { - WriteAppendReadTest0(inSuite); + WriteAppendReadTest0(); - WriteAppendReadTest1(inSuite); + WriteAppendReadTest1(); - WriteFindAppendReadTest(inSuite, false); // Find an element + WriteFindAppendReadTest(false); // Find an element - WriteFindAppendReadTest(inSuite, true); // Find a container + WriteFindAppendReadTest(true); // Find a container - AppendReadTest(inSuite); + AppendReadTest(); - WriteDeleteReadTest(inSuite); + WriteDeleteReadTest(); } /** @@ -4041,7 +4025,7 @@ void OptimisticTLVWriter::Init(uint8_t * buf, size_t maxLen) SetCloseContainerReserved(false); } -static void CheckCloseContainerReserve(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckCloseContainerReserve) { // We are writing the structure looking like: // @@ -4070,114 +4054,114 @@ static void CheckCloseContainerReserve(nlTestSuite * inSuite, void * inContext) writer1.Init(buf); err = writer1.OpenContainer(AnonymousTag(), kTLVType_Array, innerWriter1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = innerWriter1.OpenContainer(AnonymousTag(), kTLVType_Structure, innerWriter2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = innerWriter2.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); err = innerWriter1.CloseContainer(innerWriter2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.CloseContainer(innerWriter1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); writer2.Init(buf, sizeof(buf)); err = writer2.OpenContainer(AnonymousTag(), kTLVType_Array, innerWriter1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = innerWriter1.OpenContainer(AnonymousTag(), kTLVType_Structure, innerWriter2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = innerWriter2.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = innerWriter1.CloseContainer(innerWriter2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.CloseContainer(innerWriter1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); // test the same scheme works on the Start/End container writer1.Init(buf); err = writer1.StartContainer(AnonymousTag(), kTLVType_Array, container1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.StartContainer(AnonymousTag(), kTLVType_Structure, container2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); err = writer1.EndContainer(container2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer1.EndContainer(container1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); writer2.Init(buf, sizeof(buf)); err = writer2.StartContainer(AnonymousTag(), kTLVType_Array, container1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.StartContainer(AnonymousTag(), kTLVType_Structure, container2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_1, 2), true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.EndContainer(container2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.EndContainer(container1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); // Test that the reservations work for the empty containers writer1.Init(buf1); err = writer1.OpenContainer(ProfileTag(TestProfile_1, 2), kTLVType_Structure, innerWriter1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); err = writer1.CloseContainer(innerWriter1); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); writer2.Init(buf1, sizeof(buf1)); err = writer2.OpenContainer(ProfileTag(TestProfile_1, 2), kTLVType_Structure, innerWriter1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.CloseContainer(innerWriter1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); writer1.Init(buf1); err = writer1.StartContainer(ProfileTag(TestProfile_1, 2), kTLVType_Structure, container1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); err = writer1.EndContainer(container1); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); writer2.Init(buf1, sizeof(buf1)); err = writer2.StartContainer(ProfileTag(TestProfile_1, 2), kTLVType_Structure, container1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer2.EndContainer(container1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); // Test that the reservations work if the writer has a maxLen of 0. writer1.Init(buf1, 0); err = writer1.OpenContainer(ProfileTag(TestProfile_1, 2), kTLVType_Structure, innerWriter1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); err = writer1.StartContainer(AnonymousTag(), kTLVType_Array, container1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); // Test again all cases from 0 to the length of buf1 @@ -4201,7 +4185,7 @@ static void CheckCloseContainerReserve(nlTestSuite * inSuite, void * inContext) if (err == CHIP_NO_ERROR) err = writer1.CloseContainer(innerWriter1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); // Start/EndContainer @@ -4222,11 +4206,11 @@ static void CheckCloseContainerReserve(nlTestSuite * inSuite, void * inContext) if (err == CHIP_NO_ERROR) err = writer1.EndContainer(container1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); } } -static CHIP_ERROR ReadFuzzedEncoding1(nlTestSuite * inSuite, TLVReader & reader) +static CHIP_ERROR ReadFuzzedEncoding1(TLVReader & reader) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -4357,7 +4341,7 @@ static CHIP_ERROR ReadFuzzedEncoding1(nlTestSuite * inSuite, TLVReader & reader) static uint64_t sFuzzTestDurationMillis = 5000; static uint8_t sFixedFuzzMask = 0; -static void TLVReaderFuzzTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, TLVReaderFuzzTest) { uint64_t now, endTime; uint8_t fuzzedData[sizeof(Encoding1)]; @@ -4421,8 +4405,8 @@ static void TLVReaderFuzzTest(nlTestSuite * inSuite, void * inContext) reader.Init(fuzzedData); reader.ImplicitProfileId = TestProfile_2; - CHIP_ERROR readRes = ReadFuzzedEncoding1(inSuite, reader); - NL_TEST_ASSERT(inSuite, readRes != CHIP_NO_ERROR); + CHIP_ERROR readRes = ReadFuzzedEncoding1(reader); + EXPECT_NE(readRes, CHIP_NO_ERROR); if (readRes == CHIP_NO_ERROR) { @@ -4443,23 +4427,23 @@ static void TLVReaderFuzzTest(nlTestSuite * inSuite, void * inContext) } } -static void AssertCanReadString(nlTestSuite * inSuite, ContiguousBufferTLVReader & reader, const char * expectedString) +static void AssertCanReadString(ContiguousBufferTLVReader & reader, const char * expectedString) { Span str; CHIP_ERROR err = reader.GetStringView(str); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, str.size() == strlen(expectedString)); - NL_TEST_ASSERT(inSuite, strncmp(str.data(), expectedString, str.size()) == 0); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(str.size(), strlen(expectedString)); + EXPECT_EQ(strncmp(str.data(), expectedString, str.size()), 0); } -static void AssertCannotReadString(nlTestSuite * inSuite, ContiguousBufferTLVReader & reader) +static void AssertCannotReadString(ContiguousBufferTLVReader & reader) { Span str; CHIP_ERROR err = reader.GetStringView(str); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); } -static void CheckGetStringView(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckGetStringView) { uint8_t buf[256]; static const char testString[] = "This is a test"; @@ -4467,25 +4451,25 @@ static void CheckGetStringView(nlTestSuite * inSuite, void * inContext) TLVWriter writer; writer.Init(buf); CHIP_ERROR err = writer.PutString(CommonTag(0), testString); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // First check that basic read from entire buffer works. ContiguousBufferTLVReader reader; reader.Init(buf); reader.Next(); - AssertCanReadString(inSuite, reader, testString); + AssertCanReadString(reader, testString); // Now check that read from a buffer bounded by the number of bytes // written works. reader.Init(buf, writer.GetLengthWritten()); reader.Next(); - AssertCanReadString(inSuite, reader, testString); + AssertCanReadString(reader, testString); // Now check that read from a buffer bounded by fewer than the number of // bytes written fails. reader.Init(buf, writer.GetLengthWritten() - 1); reader.Next(); - AssertCannotReadString(inSuite, reader); + AssertCannotReadString(reader); } { @@ -4493,12 +4477,12 @@ static void CheckGetStringView(nlTestSuite * inSuite, void * inContext) TLVWriter writer; writer.Init(buf); CHIP_ERROR err = writer.Put(CommonTag(0), static_cast(5)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); ContiguousBufferTLVReader reader; reader.Init(buf); reader.Next(); - AssertCannotReadString(inSuite, reader); + AssertCannotReadString(reader); } { @@ -4507,12 +4491,12 @@ static void CheckGetStringView(nlTestSuite * inSuite, void * inContext) writer.Init(buf); CHIP_ERROR err = writer.PutBytes(CommonTag(0), reinterpret_cast(testString), static_cast(strlen(testString))); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); ContiguousBufferTLVReader reader; reader.Init(buf); reader.Next(); - AssertCannotReadString(inSuite, reader); + AssertCannotReadString(reader); } { @@ -4521,7 +4505,7 @@ static void CheckGetStringView(nlTestSuite * inSuite, void * inContext) ContiguousBufferTLVReader reader; reader.Init(shortString); reader.Next(); - AssertCanReadString(inSuite, reader, "ab"); + AssertCanReadString(reader, "ab"); } { @@ -4530,26 +4514,26 @@ static void CheckGetStringView(nlTestSuite * inSuite, void * inContext) ContiguousBufferTLVReader reader; reader.Init(shortString); reader.Next(); - AssertCannotReadString(inSuite, reader); + AssertCannotReadString(reader); } } -static void AssertCanReadBytes(nlTestSuite * inSuite, ContiguousBufferTLVReader & reader, const ByteSpan & expectedBytes) +static void AssertCanReadBytes(ContiguousBufferTLVReader & reader, const ByteSpan & expectedBytes) { ByteSpan bytes; CHIP_ERROR err = reader.GetByteView(bytes); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, bytes.data_equal(expectedBytes)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(bytes.data_equal(expectedBytes)); } -static void AssertCannotReadBytes(nlTestSuite * inSuite, ContiguousBufferTLVReader & reader) +static void AssertCannotReadBytes(ContiguousBufferTLVReader & reader) { ByteSpan bytes; CHIP_ERROR err = reader.GetByteView(bytes); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); } -static void CheckGetByteView(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckGetByteView) { uint8_t buf[256]; const uint8_t testBytes[] = { 'T', 'h', 'i', 's', 'i', 's', 'a', 't', 'e', 's', 't', '\0' }; @@ -4557,25 +4541,25 @@ static void CheckGetByteView(nlTestSuite * inSuite, void * inContext) TLVWriter writer; writer.Init(buf); CHIP_ERROR err = writer.PutBytes(CommonTag(0), testBytes, sizeof(testBytes)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // First check that basic read from entire buffer works. ContiguousBufferTLVReader reader; reader.Init(buf); reader.Next(); - AssertCanReadBytes(inSuite, reader, ByteSpan(testBytes)); + AssertCanReadBytes(reader, ByteSpan(testBytes)); // Now check that read from a buffer bounded by the number of bytes // written works. reader.Init(buf, writer.GetLengthWritten()); reader.Next(); - AssertCanReadBytes(inSuite, reader, ByteSpan(testBytes)); + AssertCanReadBytes(reader, ByteSpan(testBytes)); // Now check that read from a buffer bounded by fewer than the number of // bytes written fails. reader.Init(buf, writer.GetLengthWritten() - 1); reader.Next(); - AssertCannotReadBytes(inSuite, reader); + AssertCannotReadBytes(reader); } { @@ -4583,12 +4567,12 @@ static void CheckGetByteView(nlTestSuite * inSuite, void * inContext) TLVWriter writer; writer.Init(buf); CHIP_ERROR err = writer.Put(CommonTag(0), static_cast(5)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); ContiguousBufferTLVReader reader; reader.Init(buf); reader.Next(); - AssertCannotReadBytes(inSuite, reader); + AssertCannotReadBytes(reader); } { @@ -4596,12 +4580,12 @@ static void CheckGetByteView(nlTestSuite * inSuite, void * inContext) TLVWriter writer; writer.Init(buf); CHIP_ERROR err = writer.PutString(CommonTag(0), reinterpret_cast(testBytes)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); ContiguousBufferTLVReader reader; reader.Init(buf); reader.Next(); - AssertCannotReadBytes(inSuite, reader); + AssertCannotReadBytes(reader); } { @@ -4611,7 +4595,7 @@ static void CheckGetByteView(nlTestSuite * inSuite, void * inContext) reader.Init(shortBytes); reader.Next(); const uint8_t expectedBytes[] = { 1, 2 }; - AssertCanReadBytes(inSuite, reader, ByteSpan(expectedBytes)); + AssertCanReadBytes(reader, ByteSpan(expectedBytes)); } { @@ -4621,32 +4605,32 @@ static void CheckGetByteView(nlTestSuite * inSuite, void * inContext) ContiguousBufferTLVReader reader; reader.Init(shortBytes); reader.Next(); - AssertCannotReadBytes(inSuite, reader); + AssertCannotReadBytes(reader); } } -static void CheckTLVScopedBuffer(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, CheckTLVScopedBuffer) { Platform::ScopedMemoryBuffer buf; CHIP_ERROR err; buf.Calloc(64); - NL_TEST_ASSERT(inSuite, buf.Get() != nullptr); + ASSERT_NE(buf.Get(), nullptr); { ScopedBufferTLVWriter writer(std::move(buf), 64); - NL_TEST_ASSERT(inSuite, buf.Get() == nullptr); // // NOLINT(bugprone-use-after-move) + EXPECT_EQ(buf.Get(), nullptr); // // NOLINT(bugprone-use-after-move) err = writer.Put(TLV::AnonymousTag(), (uint8_t) 33); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writer.Finalize(buf); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, buf.Get() != nullptr); + EXPECT_EQ(err, CHIP_NO_ERROR); + ASSERT_NE(buf.Get(), nullptr); err = writer.Put(TLV::AnonymousTag(), (uint8_t) 33); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); } { @@ -4656,204 +4640,202 @@ static void CheckTLVScopedBuffer(nlTestSuite * inSuite, void * inContext) reader.Init(std::move(buf), 64); err = reader.Next(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.Get(val); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, val == 33); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(val, 33); reader.TakeBuffer(buf); - NL_TEST_ASSERT(inSuite, buf.Get() != nullptr); + ASSERT_NE(buf.Get(), nullptr); err = reader.Get(val); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); } } -static void TestUninitializedWriter(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLV, TestUninitializedWriter) { { TLVWriter writer; - NL_TEST_ASSERT(inSuite, !writer.IsInitialized()); + EXPECT_FALSE(writer.IsInitialized()); } { TLVWriter writer; - NL_TEST_ASSERT(inSuite, writer.Finalize() == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Finalize(), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; - NL_TEST_ASSERT(inSuite, writer.ReserveBuffer(123) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.ReserveBuffer(123), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; - NL_TEST_ASSERT(inSuite, writer.UnreserveBuffer(123) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.UnreserveBuffer(123), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; uint8_t v = 3; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; int8_t v = 3; bool preserveSize = true; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v, preserveSize) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v, preserveSize), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; int16_t v = 3; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; int16_t v = 3; bool preserveSize = true; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v, preserveSize) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v, preserveSize), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; int32_t v = 3; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; int32_t v = 3; bool preserveSize = true; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v, preserveSize) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v, preserveSize), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; int64_t v = 3; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; int64_t v = 3; bool preserveSize = true; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v, preserveSize) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v, preserveSize), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; uint8_t v = 3; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; uint8_t v = 3; bool preserveSize = true; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v, preserveSize) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v, preserveSize), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; uint16_t v = 3; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; uint16_t v = 3; bool preserveSize = true; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v, preserveSize) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v, preserveSize), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; uint32_t v = 3; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; uint32_t v = 3; bool preserveSize = true; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v, preserveSize) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v, preserveSize), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; uint64_t v = 3; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; uint64_t v = 3; bool preserveSize = true; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v, preserveSize) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v, preserveSize), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; double v = 1.23; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; float v = 1.23f; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; bool v = true; - NL_TEST_ASSERT(inSuite, writer.PutBoolean(ContextTag(1), v) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.PutBoolean(ContextTag(1), v), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; bool v = true; - NL_TEST_ASSERT(inSuite, writer.Put(ContextTag(1), v) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.Put(ContextTag(1), v), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; const uint8_t buf[] = { 1, 2, 3 }; - NL_TEST_ASSERT(inSuite, - writer.PutBytes(ContextTag(1), buf, static_cast(sizeof(buf))) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.PutBytes(ContextTag(1), buf, static_cast(sizeof(buf))), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; const char * buf = "abc"; - NL_TEST_ASSERT(inSuite, writer.PutString(ContextTag(1), buf) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.PutString(ContextTag(1), buf), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; const char * buf = "abc"; - NL_TEST_ASSERT(inSuite, - writer.PutString(ContextTag(1), buf, static_cast(strlen(buf))) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.PutString(ContextTag(1), buf, static_cast(strlen(buf))), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; CharSpan str = "abc"_span; - NL_TEST_ASSERT(inSuite, writer.PutString(ContextTag(1), str) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.PutString(ContextTag(1), str), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; - NL_TEST_ASSERT(inSuite, writer.PutStringF(ContextTag(1), "%d", 1) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.PutStringF(ContextTag(1), "%d", 1), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; - NL_TEST_ASSERT(inSuite, writer.PutNull(ContextTag(1)) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.PutNull(ContextTag(1)), CHIP_ERROR_INCORRECT_STATE); } { @@ -4862,7 +4844,7 @@ static void TestUninitializedWriter(nlTestSuite * inSuite, void * inContext) reader.Init(buf); TLVWriter writer; - NL_TEST_ASSERT(inSuite, writer.CopyElement(reader) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.CopyElement(reader), CHIP_ERROR_INCORRECT_STATE); } { @@ -4871,51 +4853,49 @@ static void TestUninitializedWriter(nlTestSuite * inSuite, void * inContext) reader.Init(buf); TLVWriter writer; - NL_TEST_ASSERT(inSuite, writer.CopyElement(ContextTag(1), reader) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.CopyElement(ContextTag(1), reader), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; TLVType outerContainerType; - NL_TEST_ASSERT(inSuite, - writer.StartContainer(ContextTag(1), TLVType::kTLVType_Structure, outerContainerType) == - CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.StartContainer(ContextTag(1), TLVType::kTLVType_Structure, outerContainerType), + CHIP_ERROR_INCORRECT_STATE); } { TLVWriter writer; TLVType outerContainerType = TLVType::kTLVType_Structure; - NL_TEST_ASSERT(inSuite, writer.EndContainer(outerContainerType) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.EndContainer(outerContainerType), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter innerWriter; uint8_t buf[]{ 0, 0, 0 }; innerWriter.Init(buf); - NL_TEST_ASSERT(inSuite, innerWriter.IsInitialized()); + EXPECT_TRUE(innerWriter.IsInitialized()); TLVWriter writer; - NL_TEST_ASSERT(inSuite, - writer.OpenContainer(ContextTag(1), TLVType::kTLVType_Structure, innerWriter) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.OpenContainer(ContextTag(1), TLVType::kTLVType_Structure, innerWriter), CHIP_ERROR_INCORRECT_STATE); } { TLVWriter innerWriter; uint8_t buf[]{ 0, 0, 0 }; innerWriter.Init(buf); - NL_TEST_ASSERT(inSuite, innerWriter.IsInitialized()); + EXPECT_TRUE(innerWriter.IsInitialized()); TLVWriter writer; - NL_TEST_ASSERT(inSuite, writer.CloseContainer(innerWriter) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.CloseContainer(innerWriter), CHIP_ERROR_INCORRECT_STATE); } { uint8_t buf[]{ 0, 0, 0 }; TLVWriter writer; - NL_TEST_ASSERT(inSuite, - writer.PutPreEncodedContainer(ContextTag(1), TLVType::kTLVType_Structure, buf, - static_cast(sizeof(buf))) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ( + writer.PutPreEncodedContainer(ContextTag(1), TLVType::kTLVType_Structure, buf, static_cast(sizeof(buf))), + CHIP_ERROR_INCORRECT_STATE); } { @@ -4924,7 +4904,7 @@ static void TestUninitializedWriter(nlTestSuite * inSuite, void * inContext) reader.Init(buf); TLVWriter writer; - NL_TEST_ASSERT(inSuite, writer.CopyContainer(reader) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.CopyContainer(reader), CHIP_ERROR_INCORRECT_STATE); } { @@ -4933,95 +4913,13 @@ static void TestUninitializedWriter(nlTestSuite * inSuite, void * inContext) reader.Init(buf); TLVWriter writer; - NL_TEST_ASSERT(inSuite, writer.CopyContainer(ContextTag(1), reader) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.CopyContainer(ContextTag(1), reader), CHIP_ERROR_INCORRECT_STATE); } { uint8_t buf[]{ 0, 0, 0 }; TLVWriter writer; - NL_TEST_ASSERT(inSuite, - writer.CopyContainer(ContextTag(1), buf, static_cast(sizeof(buf))) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(writer.CopyContainer(ContextTag(1), buf, static_cast(sizeof(buf))), CHIP_ERROR_INCORRECT_STATE); } } - -// Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("Simple Write Read Test", CheckSimpleWriteRead), - NL_TEST_DEF("Inet Buffer Test", CheckPacketBuffer), - NL_TEST_DEF("Buffer Overflow Test", CheckBufferOverflow), - NL_TEST_DEF("Pretty Print Test", CheckPrettyPrinter), - NL_TEST_DEF("Pretty Octet String Print Test", CheckOctetStringPrettyPrinter), - NL_TEST_DEF("Data Macro Test", CheckDataMacro), - NL_TEST_DEF("Strict Aliasing Test", CheckStrictAliasing), - NL_TEST_DEF("CHIP TLV Basics", CheckTLVBasics), - NL_TEST_DEF("CHIP TLV Writer", CheckTLVWriter), - NL_TEST_DEF("CHIP TLV Reader", CheckTLVReader), - NL_TEST_DEF("CHIP TLV Utilities", CheckTLVUtilities), - NL_TEST_DEF("CHIP TLV Updater", CheckCHIPUpdater), - NL_TEST_DEF("CHIP TLV Empty Find", CheckTLVEmptyFind), - NL_TEST_DEF("CHIP Circular TLV buffer, simple", CheckCircularTLVBufferSimple), - NL_TEST_DEF("CHIP Circular TLV buffer, mid-buffer start", CheckCircularTLVBufferStartMidway), - NL_TEST_DEF("CHIP Circular TLV buffer, straddle", CheckCircularTLVBufferEvictStraddlingEvent), - NL_TEST_DEF("CHIP Circular TLV buffer, edge", CheckCircularTLVBufferEdge), - NL_TEST_DEF("CHIP TLV Printf", CheckTLVPutStringF), - NL_TEST_DEF("CHIP TLV String Span", CheckTLVPutStringSpan), - NL_TEST_DEF("CHIP TLV Printf, Circular TLV buf", CheckTLVPutStringFCircular), - NL_TEST_DEF("CHIP TLV Skip non-contiguous", CheckTLVSkipCircular), - NL_TEST_DEF("CHIP TLV ByteSpan", CheckTLVByteSpan), - NL_TEST_DEF("CHIP TLV CharSpan", CheckTLVCharSpan), - NL_TEST_DEF("CHIP TLV Get LocalizedStringIdentifier", CheckTLVGetLocalizedStringIdentifier), - NL_TEST_DEF("CHIP TLV Scoped Buffer", CheckTLVScopedBuffer), - NL_TEST_DEF("CHIP TLV Check reserve", CheckCloseContainerReserve), - NL_TEST_DEF("CHIP TLV Reader Fuzz Test", TLVReaderFuzzTest), - NL_TEST_DEF("CHIP TLV GetStringView Test", CheckGetStringView), - NL_TEST_DEF("CHIP TLV GetByteView Test", CheckGetByteView), - NL_TEST_DEF("Int Min/Max Test", TestIntMinMax), - NL_TEST_DEF("Uninitialized Writer Test", TestUninitializedWriter), - - NL_TEST_SENTINEL() -}; -// clang-format on - -/** - * Set up the test suite. - */ -int TestTLV_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int TestTLV_Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -int TestTLV() -{ - // clang-format off - nlTestSuite theSuite = - { - "chip-tlv", - &sTests[0], - TestTLV_Setup, - TestTLV_Teardown - }; - // clang-format on - - return chip::ExecuteTestsWithContext(&theSuite, &theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestTLV) diff --git a/src/lib/core/tests/TestTLVVectorWriter.cpp b/src/lib/core/tests/TestTLVVectorWriter.cpp index c68211b02de721..d2b604fa7e876f 100644 --- a/src/lib/core/tests/TestTLVVectorWriter.cpp +++ b/src/lib/core/tests/TestTLVVectorWriter.cpp @@ -16,6 +16,8 @@ * limitations under the License. */ +#include + #include #include @@ -28,9 +30,6 @@ #include #include #include -#include -#include -#include #include using namespace chip; @@ -42,42 +41,46 @@ using namespace chip::TLV; struct TestTLVContext { - nlTestSuite * mSuite = nullptr; int mEvictionCount = 0; uint32_t mEvictedBytes = 0; +}; - TestTLVContext(nlTestSuite * suite) : mSuite(suite) {} +class TestTLVVectorWriter : public ::testing::Test +{ +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } }; -void InitAndFinalizeWithNoData(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLVVectorWriter, InitAndFinalizeWithNoData) { std::vector buffer; TlvVectorWriter writer(buffer); // Init and finalize but write not data. - NL_TEST_ASSERT(inSuite, writer.Finalize() == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, buffer.empty()); + EXPECT_EQ(writer.Finalize(), CHIP_NO_ERROR); + EXPECT_TRUE(buffer.empty()); } -void SingleSmallDataFitsInOriginalBuffer(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLVVectorWriter, SingleSmallDataFitsInOriginalBuffer) { std::vector buffer; TlvVectorWriter writer(buffer); TLVReader reader; - NL_TEST_ASSERT(inSuite, writer.Put(AnonymousTag(), true) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, writer.Finalize() == CHIP_NO_ERROR); + EXPECT_EQ(writer.Put(AnonymousTag(), true), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(), CHIP_NO_ERROR); reader.Init(buffer.data(), buffer.size()); - NL_TEST_ASSERT(inSuite, reader.Next() == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reader.GetTag() == AnonymousTag()); + EXPECT_EQ(reader.Next(), CHIP_NO_ERROR); + EXPECT_EQ(reader.GetTag(), AnonymousTag()); bool value = false; - NL_TEST_ASSERT(inSuite, reader.Get(value) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, value == true); + EXPECT_EQ(reader.Get(value), CHIP_NO_ERROR); + EXPECT_EQ(value, true); } -void SingleLargeDataRequiresNewBufferAllocation(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLVVectorWriter, SingleLargeDataRequiresNewBufferAllocation) { std::vector buffer; TlvVectorWriter writer(buffer); @@ -86,20 +89,20 @@ void SingleLargeDataRequiresNewBufferAllocation(nlTestSuite * inSuite, void * in const std::string bytes(kStringSize, 'a'); CHIP_ERROR error = writer.PutString(AnonymousTag(), bytes.data()); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, writer.Finalize() == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(), CHIP_NO_ERROR); reader.Init(buffer.data(), buffer.size()); - NL_TEST_ASSERT(inSuite, reader.Next() == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reader.GetTag() == AnonymousTag()); + EXPECT_EQ(reader.Next(), CHIP_NO_ERROR); + EXPECT_EQ(reader.GetTag(), AnonymousTag()); CharSpan span; error = reader.Get(span); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, std::string(span.data(), span.size()) == bytes); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(std::string(span.data(), span.size()), bytes); } -void ManySmallDataRequiresNewBufferAllocation(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLVVectorWriter, ManySmallDataRequiresNewBufferAllocation) { std::vector buffer; TlvVectorWriter writer(buffer); @@ -107,74 +110,21 @@ void ManySmallDataRequiresNewBufferAllocation(nlTestSuite * inSuite, void * inCo for (int i = 0; i < 10000; i++) { - NL_TEST_ASSERT(inSuite, writer.Put(AnonymousTag(), true) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Put(AnonymousTag(), true), CHIP_NO_ERROR); } - NL_TEST_ASSERT(inSuite, writer.Finalize() == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(), CHIP_NO_ERROR); reader.Init(buffer.data(), buffer.size()); for (int i = 0; i < 10000; i++) { - NL_TEST_ASSERT(inSuite, reader.Next() == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reader.GetTag() == AnonymousTag()); + EXPECT_EQ(reader.Next(), CHIP_NO_ERROR); + EXPECT_EQ(reader.GetTag(), AnonymousTag()); bool value = false; CHIP_ERROR error = reader.Get(value); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, value == true); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(value, true); } - NL_TEST_ASSERT(inSuite, reader.Next() == CHIP_END_OF_TLV); -} - -// Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("Verify behavior on init and finalize without data manipulation", InitAndFinalizeWithNoData), - NL_TEST_DEF("Ensure correct write/read operations within Inet buffer constraints", SingleSmallDataFitsInOriginalBuffer), - NL_TEST_DEF("Handle cases where a single large data input exceeds buffer capacity", SingleLargeDataRequiresNewBufferAllocation), - NL_TEST_DEF("Validate output formatting for multiple small data inputs requiring additional buffer space", ManySmallDataRequiresNewBufferAllocation), - NL_TEST_SENTINEL() -}; -// clang-format on - -/** - * Set up the test suite. - */ -int TestTLVVectorWriter_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int TestTLVVectorWriter_Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -int TestTLVVectorWriter() -{ - // clang-format off - nlTestSuite theSuite = - { - "chip-tlv", - &sTests[0], - TestTLVVectorWriter_Setup, - TestTLVVectorWriter_Teardown - }; - // clang-format on - - return chip::ExecuteTestsWithContext(&theSuite, &theSuite); + EXPECT_EQ(reader.Next(), CHIP_END_OF_TLV); } - -CHIP_REGISTER_TEST_SUITE(TestTLVVectorWriter) diff --git a/src/lib/dnssd/ActiveResolveAttempts.cpp b/src/lib/dnssd/ActiveResolveAttempts.cpp index fe0cc16ebb26aa..f49056896e0b2e 100644 --- a/src/lib/dnssd/ActiveResolveAttempts.cpp +++ b/src/lib/dnssd/ActiveResolveAttempts.cpp @@ -19,8 +19,6 @@ #include -#include - using namespace chip; namespace mdns { @@ -284,6 +282,32 @@ Optional ActiveResolveAttempts::NextSch return Optional::Missing(); } +bool ActiveResolveAttempts::ShouldResolveIpAddress(PeerId peerId) const +{ + for (auto & item : mRetryQueue) + { + if (item.attempt.IsEmpty()) + { + continue; + } + if (item.attempt.IsBrowse()) + { + return true; + } + + if (item.attempt.IsResolve()) + { + auto & data = item.attempt.ResolveData(); + if (data.peerId == peerId) + { + return true; + } + } + } + + return false; +} + bool ActiveResolveAttempts::IsWaitingForIpResolutionFor(SerializedQNameIterator hostName) const { for (auto & entry : mRetryQueue) diff --git a/src/lib/dnssd/ActiveResolveAttempts.h b/src/lib/dnssd/ActiveResolveAttempts.h index ba6d8cf7a54f6e..1d87bbbba49cbc 100644 --- a/src/lib/dnssd/ActiveResolveAttempts.h +++ b/src/lib/dnssd/ActiveResolveAttempts.h @@ -288,6 +288,12 @@ class ActiveResolveAttempts /// IP resolution. bool IsWaitingForIpResolutionFor(SerializedQNameIterator hostName) const; + /// Determines if address resolution for the given peer ID is required + /// + /// IP Addresses are required for active operational discovery of specific peers + /// or if an active browse is being performed. + bool ShouldResolveIpAddress(chip::PeerId peerId) const; + /// Check if a browse operation is active for the given discovery type bool HasBrowseFor(chip::Dnssd::DiscoveryType type) const; diff --git a/src/lib/dnssd/IncrementalResolve.h b/src/lib/dnssd/IncrementalResolve.h index 9d2386472d7eba..17790b6f9f5fe0 100644 --- a/src/lib/dnssd/IncrementalResolve.h +++ b/src/lib/dnssd/IncrementalResolve.h @@ -17,6 +17,7 @@ #pragma once #include +#include #include #include #include @@ -104,6 +105,12 @@ class IncrementalResolver ServiceNameType GetCurrentType() const { return mServiceNameType; } + PeerId OperationalParsePeerId() const + { + VerifyOrReturnValue(IsActiveOperationalParse(), PeerId()); + return mSpecificResolutionData.Get().peerId; + } + /// Start parsing a new record. SRV records are the records we are mainly /// interested on, after which TXT and A/AAAA are looked for. /// diff --git a/src/lib/dnssd/Resolver_ImplMinimalMdns.cpp b/src/lib/dnssd/Resolver_ImplMinimalMdns.cpp index a5e7117a72a005..3abc11ac659cf8 100644 --- a/src/lib/dnssd/Resolver_ImplMinimalMdns.cpp +++ b/src/lib/dnssd/Resolver_ImplMinimalMdns.cpp @@ -17,8 +17,6 @@ #include "Resolver.h" -#include - #include #include #include @@ -372,7 +370,23 @@ void MinMdnsResolver::AdvancePendingResolverStates() if (missing.Has(IncrementalResolver::RequiredInformationBitFlags::kIpAddress)) { - ScheduleIpAddressResolve(resolver->GetTargetHostName()); + if (resolver->IsActiveBrowseParse()) + { + // Browse wants IP addresses + ScheduleIpAddressResolve(resolver->GetTargetHostName()); + } + else if (mActiveResolves.ShouldResolveIpAddress(resolver->OperationalParsePeerId())) + { + // Keep searching for IP addresses if an active resolve needs these IP addresses + // otherwise ignore the data (received a SRV record without IP address, however we do not + // seem interested in it. Probably just a device that came online). + ScheduleIpAddressResolve(resolver->GetTargetHostName()); + } + else + { + // This IP address is not interesting enough to run another discovery + resolver->ResetToInactive(); + } continue; } diff --git a/src/lib/dnssd/TxtFields.cpp b/src/lib/dnssd/TxtFields.cpp index b77d991784867d..c4ec70e342d41a 100644 --- a/src/lib/dnssd/TxtFields.cpp +++ b/src/lib/dnssd/TxtFields.cpp @@ -185,7 +185,7 @@ void GetPairingInstruction(const ByteSpan & value, char * pairingInstruction) uint8_t GetCommissionerPasscode(const ByteSpan & value) { - return MakeU8FromAsciiDecimal(value); + return MakeBoolFromAsciiDecimal(value); } Optional GetRetryInterval(const ByteSpan & value) @@ -256,7 +256,7 @@ void FillNodeDataFromTxt(const ByteSpan & key, const ByteSpan & val, DnssdNodeDa nodeData.pairingHint = Internal::GetPairingHint(val); break; case TxtFieldKey::kCommissionerPasscode: - nodeData.commissionerPasscode = Internal::GetCommissionerPasscode(val); + nodeData.supportsCommissionerGeneratedPasscode = Internal::GetCommissionerPasscode(val); break; default: break; diff --git a/src/lib/dnssd/Types.h b/src/lib/dnssd/Types.h index 15dbf90670ac34..43e55bfbc65e0e 100644 --- a/src/lib/dnssd/Types.h +++ b/src/lib/dnssd/Types.h @@ -214,7 +214,7 @@ struct DnssdNodeData uint16_t productId = 0; uint16_t pairingHint = 0; uint8_t commissioningMode = 0; - uint8_t commissionerPasscode = 0; + bool supportsCommissionerGeneratedPasscode = false; uint8_t rotatingId[kMaxRotatingIdLen] = {}; char instanceName[Commission::kInstanceNameMaxLength + 1] = {}; char deviceName[kMaxDeviceNameLen + 1] = {}; @@ -272,10 +272,8 @@ struct DnssdNodeData ChipLogDetail(Discovery, "\tInstance Name: %s", instanceName); } ChipLogDetail(Discovery, "\tCommissioning Mode: %u", commissioningMode); - if (commissionerPasscode > 0) - { - ChipLogDetail(Discovery, "\tCommissioner Passcode: %u", commissionerPasscode); - } + ChipLogDetail(Discovery, "\tSupports Commissioner Generated Passcode: %s", + supportsCommissionerGeneratedPasscode ? "true" : "false"); } }; diff --git a/src/lib/dnssd/minimal_mdns/core/tests/BUILD.gn b/src/lib/dnssd/minimal_mdns/core/tests/BUILD.gn index ce985ffc651b9a..39b59bb999c9ad 100644 --- a/src/lib/dnssd/minimal_mdns/core/tests/BUILD.gn +++ b/src/lib/dnssd/minimal_mdns/core/tests/BUILD.gn @@ -14,7 +14,6 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") @@ -27,7 +26,7 @@ source_set("support") { ] } -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libMinimalMdnsCoreTests" test_sources = [ @@ -43,7 +42,5 @@ chip_test_suite_using_nltest("tests") { ":support", "${chip_root}/src/lib/core", "${chip_root}/src/lib/dnssd/minimal_mdns/core", - "${chip_root}/src/lib/support:testing_nlunit", - "${nlunit_test_root}:nlunit-test", ] } diff --git a/src/lib/dnssd/minimal_mdns/core/tests/TestFlatAllocatedQName.cpp b/src/lib/dnssd/minimal_mdns/core/tests/TestFlatAllocatedQName.cpp index db9aa23d2a7eb1..c9ab4f222ef6f0 100644 --- a/src/lib/dnssd/minimal_mdns/core/tests/TestFlatAllocatedQName.cpp +++ b/src/lib/dnssd/minimal_mdns/core/tests/TestFlatAllocatedQName.cpp @@ -14,10 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include +#include -#include +#include namespace { @@ -38,28 +37,28 @@ class AutoFreeBuffer void * mBuffer; }; -void TestFlatAllocatedQName(nlTestSuite * inSuite, void * inContext) +TEST(TestFlatAllocatedQName, TestFlatAllocatedQName) { AutoFreeBuffer buffer(128); - NL_TEST_ASSERT(inSuite, FlatAllocatedQName::RequiredStorageSize("some", "test") == (sizeof(char * [2]) + 5 + 5)); + EXPECT_EQ(FlatAllocatedQName::RequiredStorageSize("some", "test"), (sizeof(char * [2]) + 5 + 5)); { FullQName built = FlatAllocatedQName::Build(buffer.Buffer(), "some", "test"); const QNamePart expected[] = { "some", "test" }; - NL_TEST_ASSERT(inSuite, FullQName(expected) == built); + EXPECT_EQ(FullQName(expected), built); } { FullQName built = FlatAllocatedQName::Build(buffer.Buffer(), "1", "2", "3"); const QNamePart expected[] = { "1", "2", "3" }; - NL_TEST_ASSERT(inSuite, FullQName(expected) == built); + EXPECT_EQ(FullQName(expected), built); } } -void SizeCompare(nlTestSuite * inSuite, void * inContext) +TEST(TestFlatAllocatedQName, SizeCompare) { static const char kThis[] = "this"; static const char kIs[] = "is"; @@ -79,23 +78,22 @@ void SizeCompare(nlTestSuite * inSuite, void * inContext) const size_t kTestStorageSize = FlatAllocatedQName::RequiredStorageSize(kThis, kIs, kA, kTest); - NL_TEST_ASSERT(inSuite, kTestStorageSize == FlatAllocatedQName::RequiredStorageSizeFromArray(kSameArraySameSize, 4)); - NL_TEST_ASSERT(inSuite, kTestStorageSize == FlatAllocatedQName::RequiredStorageSizeFromArray(kDifferentArraySameSize, 4)); - NL_TEST_ASSERT(inSuite, kTestStorageSize < FlatAllocatedQName::RequiredStorageSizeFromArray(kDifferenArrayLongerWord, 4)); - NL_TEST_ASSERT(inSuite, kTestStorageSize > FlatAllocatedQName::RequiredStorageSizeFromArray(kDifferenArrayShorterWord, 4)); + EXPECT_EQ(kTestStorageSize, FlatAllocatedQName::RequiredStorageSizeFromArray(kSameArraySameSize, 4)); + EXPECT_EQ(kTestStorageSize, FlatAllocatedQName::RequiredStorageSizeFromArray(kDifferentArraySameSize, 4)); + EXPECT_LT(kTestStorageSize, FlatAllocatedQName::RequiredStorageSizeFromArray(kDifferenArrayLongerWord, 4)); + EXPECT_GT(kTestStorageSize, FlatAllocatedQName::RequiredStorageSizeFromArray(kDifferenArrayShorterWord, 4)); // Although the size of the array is larger, if we tell the function there are only 4 words, it should still work. - NL_TEST_ASSERT(inSuite, kTestStorageSize == FlatAllocatedQName::RequiredStorageSizeFromArray(kSameArrayExtraWord, 4)); + EXPECT_EQ(kTestStorageSize, FlatAllocatedQName::RequiredStorageSizeFromArray(kSameArrayExtraWord, 4)); // If we add the extra word, the sizes should not match - NL_TEST_ASSERT(inSuite, kTestStorageSize < FlatAllocatedQName::RequiredStorageSizeFromArray(kSameArrayExtraWord, 5)); + EXPECT_LT(kTestStorageSize, FlatAllocatedQName::RequiredStorageSizeFromArray(kSameArrayExtraWord, 5)); - NL_TEST_ASSERT(inSuite, kTestStorageSize > FlatAllocatedQName::RequiredStorageSizeFromArray(kShorterArray, 3)); - NL_TEST_ASSERT(inSuite, - FlatAllocatedQName::RequiredStorageSizeFromArray(kSameArraySameSize, 3) == - FlatAllocatedQName::RequiredStorageSizeFromArray(kShorterArray, 3)); + EXPECT_GT(kTestStorageSize, FlatAllocatedQName::RequiredStorageSizeFromArray(kShorterArray, 3)); + EXPECT_EQ(FlatAllocatedQName::RequiredStorageSizeFromArray(kSameArraySameSize, 3), + FlatAllocatedQName::RequiredStorageSizeFromArray(kShorterArray, 3)); } -void BuildCompare(nlTestSuite * inSuite, void * inContext) +TEST(TestFlatAllocatedQName, BuildCompare) { static const char kThis[] = "this"; static const char kIs[] = "is"; @@ -111,33 +109,15 @@ void BuildCompare(nlTestSuite * inSuite, void * inContext) const FullQName kTestQName = FlatAllocatedQName::Build(storage, kThis, kIs, kA, kTest); - NL_TEST_ASSERT(inSuite, kTestQName == FlatAllocatedQName::BuildFromArray(storage, kSameArraySameSize, 4)); + EXPECT_EQ(kTestQName, FlatAllocatedQName::BuildFromArray(storage, kSameArraySameSize, 4)); // Although the size of the array is larger, if we tell the function there are only 4 words, it should still work. - NL_TEST_ASSERT(inSuite, kTestQName == FlatAllocatedQName::BuildFromArray(storage, kSameArrayExtraWord, 4)); + EXPECT_EQ(kTestQName, FlatAllocatedQName::BuildFromArray(storage, kSameArrayExtraWord, 4)); // If we add the extra word, the names - NL_TEST_ASSERT(inSuite, kTestQName != FlatAllocatedQName::BuildFromArray(storage, kSameArrayExtraWord, 5)); + EXPECT_NE(kTestQName, FlatAllocatedQName::BuildFromArray(storage, kSameArrayExtraWord, 5)); - NL_TEST_ASSERT(inSuite, kTestQName != FlatAllocatedQName::BuildFromArray(storage, kShorterArray, 3)); - NL_TEST_ASSERT(inSuite, - FlatAllocatedQName::BuildFromArray(storage, kSameArraySameSize, 3) == - FlatAllocatedQName::BuildFromArray(storage, kShorterArray, 3)); + EXPECT_NE(kTestQName, FlatAllocatedQName::BuildFromArray(storage, kShorterArray, 3)); + EXPECT_EQ(FlatAllocatedQName::BuildFromArray(storage, kSameArraySameSize, 3), + FlatAllocatedQName::BuildFromArray(storage, kShorterArray, 3)); } - -const nlTest sTests[] = { - NL_TEST_DEF("TestFlatAllocatedQName", TestFlatAllocatedQName), // - NL_TEST_DEF("TestFlatAllocatedQNameRequiredSizes", SizeCompare), // - NL_TEST_DEF("TestFlatAllocatedQNameBuild", BuildCompare), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestFlatAllocatedQName() -{ - nlTestSuite theSuite = { "FlatAllocatedQName", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestFlatAllocatedQName) diff --git a/src/lib/dnssd/minimal_mdns/core/tests/TestHeapQName.cpp b/src/lib/dnssd/minimal_mdns/core/tests/TestHeapQName.cpp index 51e31ca0112205..22287751ac5f05 100644 --- a/src/lib/dnssd/minimal_mdns/core/tests/TestHeapQName.cpp +++ b/src/lib/dnssd/minimal_mdns/core/tests/TestHeapQName.cpp @@ -16,17 +16,23 @@ * limitations under the License. */ +#include + #include #include -#include - -#include namespace { using namespace mdns::Minimal; -void Construction(nlTestSuite * inSuite, void * inContext) +class TestHeapQName : public ::testing::Test +{ +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestHeapQName, Construction) { { @@ -34,9 +40,9 @@ void Construction(nlTestSuite * inSuite, void * inContext) HeapQName heapQName(kShort.Serialized()); - NL_TEST_ASSERT(inSuite, heapQName.IsOk()); - NL_TEST_ASSERT(inSuite, heapQName.Content() == kShort.Full()); - NL_TEST_ASSERT(inSuite, kShort.Serialized() == heapQName.Content()); + EXPECT_TRUE(heapQName.IsOk()); + EXPECT_EQ(heapQName.Content(), kShort.Full()); + EXPECT_EQ(kShort.Serialized(), heapQName.Content()); } { @@ -45,13 +51,13 @@ void Construction(nlTestSuite * inSuite, void * inContext) HeapQName heapQName(kLonger.Serialized()); - NL_TEST_ASSERT(inSuite, heapQName.IsOk()); - NL_TEST_ASSERT(inSuite, heapQName.Content() == kLonger.Full()); - NL_TEST_ASSERT(inSuite, kLonger.Serialized() == heapQName.Content()); + EXPECT_TRUE(heapQName.IsOk()); + EXPECT_EQ(heapQName.Content(), kLonger.Full()); + EXPECT_EQ(kLonger.Serialized(), heapQName.Content()); } } -void Copying(nlTestSuite * inSuite, void * inContext) +TEST_F(TestHeapQName, Copying) { const testing::TestQName<2> kShort({ "some", "test" }); @@ -61,50 +67,11 @@ void Copying(nlTestSuite * inSuite, void * inContext) name3 = name2; - NL_TEST_ASSERT(inSuite, name1.IsOk()); - NL_TEST_ASSERT(inSuite, name2.IsOk()); - NL_TEST_ASSERT(inSuite, name3.IsOk()); - NL_TEST_ASSERT(inSuite, name1.Content() == name2.Content()); - NL_TEST_ASSERT(inSuite, name1.Content() == name3.Content()); -} - -static const nlTest sTests[] = { // - NL_TEST_DEF("Construction", Construction), // - NL_TEST_DEF("Copying", Copying), // - NL_TEST_SENTINEL() -}; - -int Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; + EXPECT_TRUE(name1.IsOk()); + EXPECT_TRUE(name2.IsOk()); + EXPECT_TRUE(name3.IsOk()); + EXPECT_EQ(name1.Content(), name2.Content()); + EXPECT_EQ(name1.Content(), name3.Content()); } } // namespace - -int TestHeapQName() -{ - nlTestSuite theSuite = { - "HeapQName", - &sTests[0], - &Setup, - &Teardown, - }; - - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestHeapQName) diff --git a/src/lib/dnssd/minimal_mdns/core/tests/TestQName.cpp b/src/lib/dnssd/minimal_mdns/core/tests/TestQName.cpp index da2f91013b3217..5f430bd3c76a7a 100644 --- a/src/lib/dnssd/minimal_mdns/core/tests/TestQName.cpp +++ b/src/lib/dnssd/minimal_mdns/core/tests/TestQName.cpp @@ -16,10 +16,9 @@ * limitations under the License. */ -#include -#include +#include -#include +#include namespace { @@ -40,67 +39,67 @@ static SerializedQNameIterator AsSerializedQName(const uint8_t (&v)[N]) return SerializedQNameIterator(BytesRange(v, v + N - 1), v); } -void IteratorTest(nlTestSuite * inSuite, void * inContext) +TEST(TestQName, IteratorTest) { { static const uint8_t kOneItem[] = "\04test\00"; SerializedQNameIterator it = AsSerializedQName(kOneItem); - NL_TEST_ASSERT(inSuite, it.Next()); - NL_TEST_ASSERT(inSuite, strcmp(it.Value(), "test") == 0); - NL_TEST_ASSERT(inSuite, !it.Next()); - NL_TEST_ASSERT(inSuite, it.IsValid()); + EXPECT_TRUE(it.Next()); + EXPECT_STREQ(it.Value(), "test"); + EXPECT_FALSE(it.Next()); + EXPECT_TRUE(it.IsValid()); } { static const uint8_t kManyItems[] = "\04this\02is\01a\04test\00"; SerializedQNameIterator it = AsSerializedQName(kManyItems); - NL_TEST_ASSERT(inSuite, it.Next()); - NL_TEST_ASSERT(inSuite, strcmp(it.Value(), "this") == 0); + EXPECT_TRUE(it.Next()); + EXPECT_STREQ(it.Value(), "this"); - NL_TEST_ASSERT(inSuite, it.Next()); - NL_TEST_ASSERT(inSuite, strcmp(it.Value(), "is") == 0); + EXPECT_TRUE(it.Next()); + EXPECT_STREQ(it.Value(), "is"); - NL_TEST_ASSERT(inSuite, it.Next()); - NL_TEST_ASSERT(inSuite, strcmp(it.Value(), "a") == 0); + EXPECT_TRUE(it.Next()); + EXPECT_STREQ(it.Value(), "a"); - NL_TEST_ASSERT(inSuite, it.Next()); - NL_TEST_ASSERT(inSuite, strcmp(it.Value(), "test") == 0); + EXPECT_TRUE(it.Next()); + EXPECT_STREQ(it.Value(), "test"); - NL_TEST_ASSERT(inSuite, !it.Next()); - NL_TEST_ASSERT(inSuite, it.IsValid()); + EXPECT_FALSE(it.Next()); + EXPECT_TRUE(it.IsValid()); } { static const uint8_t kPtrItems[] = "abc\02is\01a\04test\00\04this\xc0\03"; SerializedQNameIterator it(BytesRange(kPtrItems, kPtrItems + sizeof(kPtrItems)), kPtrItems + 14); - NL_TEST_ASSERT(inSuite, it.Next()); - NL_TEST_ASSERT(inSuite, strcmp(it.Value(), "this") == 0); + EXPECT_TRUE(it.Next()); + EXPECT_STREQ(it.Value(), "this"); - NL_TEST_ASSERT(inSuite, it.Next()); - NL_TEST_ASSERT(inSuite, strcmp(it.Value(), "is") == 0); + EXPECT_TRUE(it.Next()); + EXPECT_STREQ(it.Value(), "is"); - NL_TEST_ASSERT(inSuite, it.Next()); - NL_TEST_ASSERT(inSuite, strcmp(it.Value(), "a") == 0); + EXPECT_TRUE(it.Next()); + EXPECT_STREQ(it.Value(), "a"); - NL_TEST_ASSERT(inSuite, it.Next()); - NL_TEST_ASSERT(inSuite, strcmp(it.Value(), "test") == 0); + EXPECT_TRUE(it.Next()); + EXPECT_STREQ(it.Value(), "test"); - NL_TEST_ASSERT(inSuite, !it.Next()); - NL_TEST_ASSERT(inSuite, it.IsValid()); + EXPECT_FALSE(it.Next()); + EXPECT_TRUE(it.IsValid()); } } -void ErrorTest(nlTestSuite * inSuite, void * inContext) +TEST(TestQName, ErrorTest) { { // Truncated before the end static const uint8_t kData[] = "\04test"; SerializedQNameIterator it = AsSerializedQName(kData); - NL_TEST_ASSERT(inSuite, !it.Next()); - NL_TEST_ASSERT(inSuite, !it.IsValid()); + EXPECT_FALSE(it.Next()); + EXPECT_FALSE(it.IsValid()); } { @@ -108,8 +107,8 @@ void ErrorTest(nlTestSuite * inSuite, void * inContext) static const uint8_t kData[] = "\02"; SerializedQNameIterator it = AsSerializedQName(kData); - NL_TEST_ASSERT(inSuite, !it.Next()); - NL_TEST_ASSERT(inSuite, !it.IsValid()); + EXPECT_FALSE(it.Next()); + EXPECT_FALSE(it.IsValid()); } { @@ -117,12 +116,12 @@ void ErrorTest(nlTestSuite * inSuite, void * inContext) static const uint8_t kData[] = "\xc0"; SerializedQNameIterator it = AsSerializedQName(kData); - NL_TEST_ASSERT(inSuite, !it.Next()); - NL_TEST_ASSERT(inSuite, !it.IsValid()); + EXPECT_FALSE(it.Next()); + EXPECT_FALSE(it.IsValid()); } } -void InvalidReferencing(nlTestSuite * inSuite, void * inContext) +TEST(TestQName, InvalidReferencing) { { // Truncated before the end (but seemingly valid in case of error) @@ -130,8 +129,8 @@ void InvalidReferencing(nlTestSuite * inSuite, void * inContext) static const uint8_t kData[] = "\00\xc0\x00"; SerializedQNameIterator it(BytesRange(kData, kData + 2), kData + 1); - NL_TEST_ASSERT(inSuite, !it.Next()); - NL_TEST_ASSERT(inSuite, !it.IsValid()); + EXPECT_FALSE(it.Next()); + EXPECT_FALSE(it.IsValid()); } { @@ -139,9 +138,9 @@ void InvalidReferencing(nlTestSuite * inSuite, void * inContext) static const uint8_t kData[] = "\03test\xc0\x00"; SerializedQNameIterator it = AsSerializedQName(kData); - NL_TEST_ASSERT(inSuite, it.Next()); - NL_TEST_ASSERT(inSuite, !it.Next()); - NL_TEST_ASSERT(inSuite, !it.IsValid()); + EXPECT_TRUE(it.Next()); + EXPECT_FALSE(it.Next()); + EXPECT_FALSE(it.IsValid()); } { @@ -149,9 +148,9 @@ void InvalidReferencing(nlTestSuite * inSuite, void * inContext) static const uint8_t kData[] = "\03test\xc0\x05"; SerializedQNameIterator it = AsSerializedQName(kData); - NL_TEST_ASSERT(inSuite, it.Next()); - NL_TEST_ASSERT(inSuite, !it.Next()); - NL_TEST_ASSERT(inSuite, !it.IsValid()); + EXPECT_TRUE(it.Next()); + EXPECT_FALSE(it.Next()); + EXPECT_FALSE(it.IsValid()); } { @@ -159,8 +158,8 @@ void InvalidReferencing(nlTestSuite * inSuite, void * inContext) static const uint8_t kData[] = "\xc0\x00"; SerializedQNameIterator it = AsSerializedQName(kData); - NL_TEST_ASSERT(inSuite, !it.Next()); - NL_TEST_ASSERT(inSuite, !it.IsValid()); + EXPECT_FALSE(it.Next()); + EXPECT_FALSE(it.IsValid()); } { @@ -168,171 +167,134 @@ void InvalidReferencing(nlTestSuite * inSuite, void * inContext) static const uint8_t kData[] = "\03test\xc0\x07"; SerializedQNameIterator it = AsSerializedQName(kData); - NL_TEST_ASSERT(inSuite, it.Next()); - NL_TEST_ASSERT(inSuite, !it.Next()); - NL_TEST_ASSERT(inSuite, !it.IsValid()); + EXPECT_TRUE(it.Next()); + EXPECT_FALSE(it.Next()); + EXPECT_FALSE(it.IsValid()); } } -void Comparison(nlTestSuite * inSuite, void * inContext) +TEST(TestQName, Comparison) { static const uint8_t kManyItems[] = "\04this\02is\01a\04test\00"; { const QNamePart kTestName[] = { "this" }; - NL_TEST_ASSERT(inSuite, AsSerializedQName(kManyItems) != FullQName(kTestName)); + EXPECT_NE(AsSerializedQName(kManyItems), FullQName(kTestName)); } { const QNamePart kTestName[] = { "this", "is" }; - NL_TEST_ASSERT(inSuite, AsSerializedQName(kManyItems) != FullQName(kTestName)); + EXPECT_NE(AsSerializedQName(kManyItems), FullQName(kTestName)); } { const QNamePart kTestName[] = { "is", "a", "test" }; - NL_TEST_ASSERT(inSuite, AsSerializedQName(kManyItems) != FullQName(kTestName)); + EXPECT_NE(AsSerializedQName(kManyItems), FullQName(kTestName)); } { const QNamePart kTestName[] = { "this", "is", "a", "test" }; - NL_TEST_ASSERT(inSuite, AsSerializedQName(kManyItems) == FullQName(kTestName)); + EXPECT_EQ(AsSerializedQName(kManyItems), FullQName(kTestName)); } { const QNamePart kTestName[] = { "this", "is", "a", "test", "suffix" }; - NL_TEST_ASSERT(inSuite, AsSerializedQName(kManyItems) != FullQName(kTestName)); + EXPECT_NE(AsSerializedQName(kManyItems), FullQName(kTestName)); } { const QNamePart kTestName[] = { "prefix", "this", "is", "a", "test" }; - NL_TEST_ASSERT(inSuite, AsSerializedQName(kManyItems) != FullQName(kTestName)); + EXPECT_NE(AsSerializedQName(kManyItems), FullQName(kTestName)); } } -void CaseInsensitiveSerializedCompare(nlTestSuite * inSuite, void * inContext) +TEST(TestQName, CaseInsensitiveSerializedCompare) { static const uint8_t kManyItems[] = "\04thIs\02iS\01a\04tEst\00"; { const QNamePart kTestName[] = { "this", "is", "a", "test" }; - NL_TEST_ASSERT(inSuite, - SerializedQNameIterator(BytesRange(kManyItems, kManyItems + sizeof(kManyItems)), kManyItems) == - FullQName(kTestName)); + EXPECT_EQ(SerializedQNameIterator(BytesRange(kManyItems, kManyItems + sizeof(kManyItems)), kManyItems), + FullQName(kTestName)); } { const QNamePart kTestName[] = { "THIS", "IS", "A", "test" }; - NL_TEST_ASSERT(inSuite, - SerializedQNameIterator(BytesRange(kManyItems, kManyItems + sizeof(kManyItems)), kManyItems) == - FullQName(kTestName)); + EXPECT_EQ(SerializedQNameIterator(BytesRange(kManyItems, kManyItems + sizeof(kManyItems)), kManyItems), + FullQName(kTestName)); } { const QNamePart kTestName[] = { "THIS", "IS", "A", "TEST" }; - NL_TEST_ASSERT(inSuite, - SerializedQNameIterator(BytesRange(kManyItems, kManyItems + sizeof(kManyItems)), kManyItems) == - FullQName(kTestName)); + EXPECT_EQ(SerializedQNameIterator(BytesRange(kManyItems, kManyItems + sizeof(kManyItems)), kManyItems), + FullQName(kTestName)); } } -void CaseInsensitiveFullQNameCompare(nlTestSuite * inSuite, void * inContext) +TEST(TestQName, CaseInsensitiveFullQNameCompare) { { const QNamePart kName1[] = { "this", "is", "a", "test" }; const QNamePart kName2[] = { "this", "IS", "a", "TEST" }; - NL_TEST_ASSERT(inSuite, FullQName(kName1) == FullQName(kName2)); + EXPECT_EQ(FullQName(kName1), FullQName(kName2)); } { const QNamePart kName1[] = { "THIS", "IS", "a", "tesT" }; const QNamePart kName2[] = { "this", "IS", "A", "TEst" }; - NL_TEST_ASSERT(inSuite, FullQName(kName1) == FullQName(kName2)); + EXPECT_EQ(FullQName(kName1), FullQName(kName2)); } { const QNamePart kName1[] = { "THIS", "IS", "a", "test" }; const QNamePart kName2[] = { "this", "IS", "A", "NEST" }; - NL_TEST_ASSERT(inSuite, FullQName(kName1) != FullQName(kName2)); + EXPECT_NE(FullQName(kName1), FullQName(kName2)); } { const QNamePart kName1[] = { "THIS", "IS", "a" }; const QNamePart kName2[] = { "this", "IS", "A", "NEST" }; - NL_TEST_ASSERT(inSuite, FullQName(kName1) != FullQName(kName2)); + EXPECT_NE(FullQName(kName1), FullQName(kName2)); } { const QNamePart kName1[] = { "THIS", "IS", "a" }; const QNamePart kName2[] = { "this", "IS" }; - NL_TEST_ASSERT(inSuite, FullQName(kName1) != FullQName(kName2)); + EXPECT_NE(FullQName(kName1), FullQName(kName2)); } { const QNamePart kName[] = { "this" }; - NL_TEST_ASSERT(inSuite, FullQName() != FullQName(kName)); - NL_TEST_ASSERT(inSuite, FullQName(kName) != FullQName()); + EXPECT_NE(FullQName(), FullQName(kName)); + EXPECT_NE(FullQName(kName), FullQName()); } } -void SerializedCompare(nlTestSuite * inSuite, void * inContext) +TEST(TestQName, SerializedCompare) { static const uint8_t kThisIsATest1[] = "\04this\02is\01a\04test\00"; static const uint8_t kThisIsATest2[] = "\04ThIs\02is\01A\04tESt\00"; static const uint8_t kThisIsDifferent[] = "\04this\02is\09different\00"; static const uint8_t kThisIs[] = "\04this\02is"; - NL_TEST_ASSERT(inSuite, AsSerializedQName(kThisIsATest1) == AsSerializedQName(kThisIsATest1)); - NL_TEST_ASSERT(inSuite, AsSerializedQName(kThisIsATest2) == AsSerializedQName(kThisIsATest2)); - NL_TEST_ASSERT(inSuite, AsSerializedQName(kThisIsATest1) == AsSerializedQName(kThisIsATest2)); - NL_TEST_ASSERT(inSuite, AsSerializedQName(kThisIsATest1) != AsSerializedQName(kThisIsDifferent)); - NL_TEST_ASSERT(inSuite, AsSerializedQName(kThisIsDifferent) != AsSerializedQName(kThisIsATest1)); - NL_TEST_ASSERT(inSuite, AsSerializedQName(kThisIsDifferent) != AsSerializedQName(kThisIs)); - NL_TEST_ASSERT(inSuite, AsSerializedQName(kThisIs) != AsSerializedQName(kThisIsDifferent)); + EXPECT_EQ(AsSerializedQName(kThisIsATest1), AsSerializedQName(kThisIsATest1)); + EXPECT_EQ(AsSerializedQName(kThisIsATest2), AsSerializedQName(kThisIsATest2)); + EXPECT_EQ(AsSerializedQName(kThisIsATest1), AsSerializedQName(kThisIsATest2)); + EXPECT_NE(AsSerializedQName(kThisIsATest1), AsSerializedQName(kThisIsDifferent)); + EXPECT_NE(AsSerializedQName(kThisIsDifferent), AsSerializedQName(kThisIsATest1)); + EXPECT_NE(AsSerializedQName(kThisIsDifferent), AsSerializedQName(kThisIs)); + EXPECT_NE(AsSerializedQName(kThisIs), AsSerializedQName(kThisIsDifferent)); // These items have back references and are "this.is.a.test" static const uint8_t kPtrItems[] = "\03abc\02is\01a\04test\00\04this\xc0\04"; SerializedQNameIterator thisIsATestPtr(BytesRange(kPtrItems, kPtrItems + sizeof(kPtrItems)), kPtrItems + 15); - NL_TEST_ASSERT(inSuite, thisIsATestPtr == AsSerializedQName(kThisIsATest1)); - NL_TEST_ASSERT(inSuite, thisIsATestPtr == AsSerializedQName(kThisIsATest2)); - NL_TEST_ASSERT(inSuite, AsSerializedQName(kThisIsATest1) == thisIsATestPtr); - NL_TEST_ASSERT(inSuite, AsSerializedQName(kThisIsATest2) == thisIsATestPtr); - NL_TEST_ASSERT(inSuite, thisIsATestPtr != AsSerializedQName(kThisIs)); - NL_TEST_ASSERT(inSuite, AsSerializedQName(kThisIs) != thisIsATestPtr); + EXPECT_EQ(thisIsATestPtr, AsSerializedQName(kThisIsATest1)); + EXPECT_EQ(thisIsATestPtr, AsSerializedQName(kThisIsATest2)); + EXPECT_EQ(AsSerializedQName(kThisIsATest1), thisIsATestPtr); + EXPECT_EQ(AsSerializedQName(kThisIsATest2), thisIsATestPtr); + EXPECT_NE(thisIsATestPtr, AsSerializedQName(kThisIs)); + EXPECT_NE(AsSerializedQName(kThisIs), thisIsATestPtr); } } // namespace - -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("IteratorTest", IteratorTest), - NL_TEST_DEF("ErrorTest", ErrorTest), - NL_TEST_DEF("Comparison", Comparison), - NL_TEST_DEF("CaseInsensitiveSerializedCompare", CaseInsensitiveSerializedCompare), - NL_TEST_DEF("CaseInsensitiveFullQNameCompare", CaseInsensitiveFullQNameCompare), - NL_TEST_DEF("SerializedCompare", SerializedCompare), - NL_TEST_DEF("InvalidReferencing", InvalidReferencing), - - NL_TEST_SENTINEL() -}; -// clang-format on - -int TestQName() -{ - // clang-format off - nlTestSuite theSuite = - { - "QName", - &sTests[0], - nullptr, - nullptr - }; - // clang-format on - - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestQName) diff --git a/src/lib/dnssd/minimal_mdns/core/tests/TestRecordWriter.cpp b/src/lib/dnssd/minimal_mdns/core/tests/TestRecordWriter.cpp index e6e2e9611f38c6..f8dbc220978c87 100644 --- a/src/lib/dnssd/minimal_mdns/core/tests/TestRecordWriter.cpp +++ b/src/lib/dnssd/minimal_mdns/core/tests/TestRecordWriter.cpp @@ -16,17 +16,16 @@ * limitations under the License. */ -#include -#include +#include -#include +#include namespace { using namespace mdns::Minimal; using namespace chip::Encoding::BigEndian; -void BasicWriteTest(nlTestSuite * inSuite, void * inContext) +TEST(TestRecordWriter, BasicWriteTest) { const QNamePart kName1[] = { "some", "name" }; const QNamePart kName2[] = { "abc", "xyz", "here" }; @@ -52,11 +51,11 @@ void BasicWriteTest(nlTestSuite * inSuite, void * inContext) }; // clang-format on - NL_TEST_ASSERT(inSuite, output.Needed() == sizeof(expectedOutput)); - NL_TEST_ASSERT(inSuite, memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)) == 0); + EXPECT_EQ(output.Needed(), sizeof(expectedOutput)); + EXPECT_EQ(memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)), 0); } -void SimpleDedup(nlTestSuite * inSuite, void * inContext) +TEST(TestRecordWriter, SimpleDedup) { const QNamePart kName1[] = { "some", "name" }; const QNamePart kName2[] = { "other", "name" }; @@ -80,11 +79,11 @@ void SimpleDedup(nlTestSuite * inSuite, void * inContext) }; // clang-format on - NL_TEST_ASSERT(inSuite, output.Needed() == sizeof(expectedOutput)); - NL_TEST_ASSERT(inSuite, memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)) == 0); + EXPECT_EQ(output.Needed(), sizeof(expectedOutput)); + EXPECT_EQ(memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)), 0); } -void ComplexDedup(nlTestSuite * inSuite, void * inContext) +TEST(TestRecordWriter, ComplexDedup) { const QNamePart kName1[] = { "some", "name" }; const QNamePart kName2[] = { "other", "name" }; @@ -125,11 +124,11 @@ void ComplexDedup(nlTestSuite * inSuite, void * inContext) }; // clang-format on - NL_TEST_ASSERT(inSuite, output.Needed() == sizeof(expectedOutput)); - NL_TEST_ASSERT(inSuite, memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)) == 0); + EXPECT_EQ(output.Needed(), sizeof(expectedOutput)); + EXPECT_EQ(memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)), 0); } -void TonsOfReferences(nlTestSuite * inSuite, void * inContext) +TEST(TestRecordWriter, TonsOfReferences) { const QNamePart kName1[] = { "some", "name" }; const QNamePart kName2[] = { "different", "name" }; @@ -159,39 +158,8 @@ void TonsOfReferences(nlTestSuite * inSuite, void * inContext) writer.WriteQName(FullQName(kName2)); } - NL_TEST_ASSERT(inSuite, output.Fit()); - NL_TEST_ASSERT(inSuite, output.Needed() == 423); + EXPECT_TRUE(output.Fit()); + EXPECT_EQ(output.Needed(), 423u); } } // namespace - -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("BasicWriteTest", BasicWriteTest), - NL_TEST_DEF("SimpleDedup", SimpleDedup), - NL_TEST_DEF("ComplexDedup", ComplexDedup), - NL_TEST_DEF("TonsOfReferences", TonsOfReferences), - - NL_TEST_SENTINEL() -}; -// clang-format on - -int TestRecordWriter() -{ - // clang-format off - nlTestSuite theSuite = - { - "RecordWriter", - &sTests[0], - nullptr, - nullptr - }; - // clang-format on - - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestRecordWriter) diff --git a/src/lib/dnssd/minimal_mdns/records/tests/BUILD.gn b/src/lib/dnssd/minimal_mdns/records/tests/BUILD.gn index 0e1cfc18eb9491..90a73141ff61d0 100644 --- a/src/lib/dnssd/minimal_mdns/records/tests/BUILD.gn +++ b/src/lib/dnssd/minimal_mdns/records/tests/BUILD.gn @@ -14,11 +14,10 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libMinimalMdnsRecordsTests" test_sources = [ @@ -34,7 +33,5 @@ chip_test_suite_using_nltest("tests") { public_deps = [ "${chip_root}/src/lib/core", "${chip_root}/src/lib/dnssd/minimal_mdns/records", - "${chip_root}/src/lib/support:testing_nlunit", - "${nlunit_test_root}:nlunit-test", ] } diff --git a/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecord.cpp b/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecord.cpp index 517256ee19d464..3139635c54a56b 100644 --- a/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecord.cpp +++ b/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecord.cpp @@ -16,10 +16,9 @@ * limitations under the License. */ -#include -#include +#include -#include +#include namespace { @@ -41,7 +40,7 @@ class FakeResourceRecord : public ResourceRecord const char * mData; }; -void CanWriteSimpleRecord(nlTestSuite * inSuite, void * inContext) +TEST(TestResourceRecord, CanWriteSimpleRecord) { uint8_t headerBuffer[HeaderRef::kSizeBytes]; uint8_t dataBuffer[128]; @@ -68,15 +67,15 @@ void CanWriteSimpleRecord(nlTestSuite * inSuite, void * inContext) 's', 'o', 'm', 'e', 'd', 'a', 't', 'a', }; - NL_TEST_ASSERT(inSuite, record.Append(header, ResourceType::kAnswer, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == 1); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == 0); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == 0); - NL_TEST_ASSERT(inSuite, output.Needed() == sizeof(expectedOutput)); - NL_TEST_ASSERT(inSuite, memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)) == 0); + EXPECT_TRUE(record.Append(header, ResourceType::kAnswer, writer)); + EXPECT_EQ(header.GetAnswerCount(), 1); + EXPECT_EQ(header.GetAuthorityCount(), 0); + EXPECT_EQ(header.GetAdditionalCount(), 0); + EXPECT_EQ(output.Needed(), sizeof(expectedOutput)); + EXPECT_EQ(memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)), 0); } -void CanWriteMultipleRecords(nlTestSuite * inSuite, void * inContext) +TEST(TestResourceRecord, CanWriteMultipleRecords) { uint8_t headerBuffer[HeaderRef::kSizeBytes]; uint8_t dataBuffer[128]; @@ -118,26 +117,26 @@ void CanWriteMultipleRecords(nlTestSuite * inSuite, void * inContext) 'x', 'y', 'z', }; - NL_TEST_ASSERT(inSuite, record1.Append(header, ResourceType::kAnswer, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == 1); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == 0); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == 0); + EXPECT_TRUE(record1.Append(header, ResourceType::kAnswer, writer)); + EXPECT_EQ(header.GetAnswerCount(), 1); + EXPECT_EQ(header.GetAuthorityCount(), 0); + EXPECT_EQ(header.GetAdditionalCount(), 0); - NL_TEST_ASSERT(inSuite, record2.Append(header, ResourceType::kAuthority, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == 1); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == 1); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == 0); + EXPECT_TRUE(record2.Append(header, ResourceType::kAuthority, writer)); + EXPECT_EQ(header.GetAnswerCount(), 1); + EXPECT_EQ(header.GetAuthorityCount(), 1); + EXPECT_EQ(header.GetAdditionalCount(), 0); - NL_TEST_ASSERT(inSuite, record3.Append(header, ResourceType::kAdditional, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == 1); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == 1); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == 1); + EXPECT_TRUE(record3.Append(header, ResourceType::kAdditional, writer)); + EXPECT_EQ(header.GetAnswerCount(), 1); + EXPECT_EQ(header.GetAuthorityCount(), 1); + EXPECT_EQ(header.GetAdditionalCount(), 1); - NL_TEST_ASSERT(inSuite, output.Needed() == sizeof(expectedOutput)); - NL_TEST_ASSERT(inSuite, memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)) == 0); + EXPECT_EQ(output.Needed(), sizeof(expectedOutput)); + EXPECT_EQ(memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)), 0); } -void RecordOrderIsEnforced(nlTestSuite * inSuite, void * inContext) +TEST(TestResourceRecord, RecordOrderIsEnforced) { uint8_t headerBuffer[HeaderRef::kSizeBytes]; uint8_t dataBuffer[128]; @@ -151,15 +150,15 @@ void RecordOrderIsEnforced(nlTestSuite * inSuite, void * inContext) header.Clear(); header.SetAuthorityCount(1); - NL_TEST_ASSERT(inSuite, record.Append(header, ResourceType::kAnswer, writer) == false); + EXPECT_EQ(record.Append(header, ResourceType::kAnswer, writer), false); header.Clear(); header.SetAdditionalCount(1); - NL_TEST_ASSERT(inSuite, record.Append(header, ResourceType::kAnswer, writer) == false); - NL_TEST_ASSERT(inSuite, record.Append(header, ResourceType::kAuthority, writer) == false); + EXPECT_EQ(record.Append(header, ResourceType::kAnswer, writer), false); + EXPECT_EQ(record.Append(header, ResourceType::kAuthority, writer), false); } -void ErrorsOutOnSmallBuffers(nlTestSuite * inSuite, void * inContext) +TEST(TestResourceRecord, ErrorsOutOnSmallBuffers) { uint8_t headerBuffer[HeaderRef::kSizeBytes]; uint8_t dataBuffer[123]; @@ -191,23 +190,23 @@ void ErrorsOutOnSmallBuffers(nlTestSuite * inSuite, void * inContext) BufferWriter output(dataBuffer, i); RecordWriter writer(&output); - NL_TEST_ASSERT(inSuite, record.Append(header, ResourceType::kAnswer, writer) == false); + EXPECT_EQ(record.Append(header, ResourceType::kAnswer, writer), false); // header untouched - NL_TEST_ASSERT(inSuite, memcmp(headerBuffer, clearHeader, HeaderRef::kSizeBytes) == 0); + EXPECT_EQ(memcmp(headerBuffer, clearHeader, HeaderRef::kSizeBytes), 0); } memset(dataBuffer, 0, sizeof(dataBuffer)); BufferWriter output(dataBuffer, sizeof(expectedOutput)); RecordWriter writer(&output); - NL_TEST_ASSERT(inSuite, record.Append(header, ResourceType::kAnswer, writer)); - NL_TEST_ASSERT(inSuite, output.Needed() == sizeof(expectedOutput)); - NL_TEST_ASSERT(inSuite, memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)) == 0); - NL_TEST_ASSERT(inSuite, memcmp(headerBuffer, clearHeader, HeaderRef::kSizeBytes) != 0); + EXPECT_TRUE(record.Append(header, ResourceType::kAnswer, writer)); + EXPECT_EQ(output.Needed(), sizeof(expectedOutput)); + EXPECT_EQ(memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)), 0); + EXPECT_NE(memcmp(headerBuffer, clearHeader, HeaderRef::kSizeBytes), 0); } -void RecordCount(nlTestSuite * inSuite, void * inContext) +TEST(TestResourceRecord, RecordCount) { constexpr int kAppendCount = 10; uint8_t headerBuffer[HeaderRef::kSizeBytes]; @@ -223,10 +222,10 @@ void RecordCount(nlTestSuite * inSuite, void * inContext) BufferWriter output(dataBuffer, sizeof(dataBuffer)); RecordWriter writer(&output); - NL_TEST_ASSERT(inSuite, record.Append(header, ResourceType::kAnswer, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == i + 1); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == 0); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == 0); + EXPECT_TRUE(record.Append(header, ResourceType::kAnswer, writer)); + EXPECT_EQ(header.GetAnswerCount(), i + 1); + EXPECT_EQ(header.GetAuthorityCount(), 0); + EXPECT_EQ(header.GetAdditionalCount(), 0); } for (int i = 0; i < kAppendCount; i++) @@ -234,10 +233,10 @@ void RecordCount(nlTestSuite * inSuite, void * inContext) BufferWriter output(dataBuffer, sizeof(dataBuffer)); RecordWriter writer(&output); - NL_TEST_ASSERT(inSuite, record.Append(header, ResourceType::kAuthority, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == kAppendCount); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == i + 1); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == 0); + EXPECT_TRUE(record.Append(header, ResourceType::kAuthority, writer)); + EXPECT_EQ(header.GetAnswerCount(), kAppendCount); + EXPECT_EQ(header.GetAuthorityCount(), i + 1); + EXPECT_EQ(header.GetAdditionalCount(), 0); } for (int i = 0; i < kAppendCount; i++) @@ -245,47 +244,27 @@ void RecordCount(nlTestSuite * inSuite, void * inContext) BufferWriter output(dataBuffer, sizeof(dataBuffer)); RecordWriter writer(&output); - NL_TEST_ASSERT(inSuite, record.Append(header, ResourceType::kAdditional, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == kAppendCount); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == kAppendCount); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == i + 1); + EXPECT_TRUE(record.Append(header, ResourceType::kAdditional, writer)); + EXPECT_EQ(header.GetAnswerCount(), kAppendCount); + EXPECT_EQ(header.GetAuthorityCount(), kAppendCount); + EXPECT_EQ(header.GetAdditionalCount(), i + 1); } } -void CacheFlushBit(nlTestSuite * inSuite, void * inContext) +TEST(TestResourceRecord, CacheFlushBit) { FakeResourceRecord record("somedata"); // No cache flush bit by default. - NL_TEST_ASSERT(inSuite, record.GetClass() == QClass::IN); - NL_TEST_ASSERT(inSuite, record.GetCacheFlush() == false); + EXPECT_EQ(record.GetClass(), QClass::IN); + EXPECT_EQ(record.GetCacheFlush(), false); // Check we can set flush bit and the class marker reflects that. record.SetCacheFlush(true); - NL_TEST_ASSERT(inSuite, record.GetClass() == QClass::IN_FLUSH); - NL_TEST_ASSERT(inSuite, record.GetCacheFlush() == true); + EXPECT_EQ(record.GetClass(), QClass::IN_FLUSH); + EXPECT_EQ(record.GetCacheFlush(), true); // Check we can unset. record.SetCacheFlush(false); - NL_TEST_ASSERT(inSuite, record.GetClass() == QClass::IN); - NL_TEST_ASSERT(inSuite, record.GetCacheFlush() == false); + EXPECT_EQ(record.GetClass(), QClass::IN); + EXPECT_EQ(record.GetCacheFlush(), false); } - -const nlTest sTests[] = { - NL_TEST_DEF("CanWriteSimpleRecord", CanWriteSimpleRecord), // - NL_TEST_DEF("CanWriteMultipleRecords", CanWriteMultipleRecords), // - NL_TEST_DEF("RecordOrderIsEnforced", RecordOrderIsEnforced), // - NL_TEST_DEF("ErrorsOutOnSmallBuffers", ErrorsOutOnSmallBuffers), // - NL_TEST_DEF("RecordCount", RecordCount), // - NL_TEST_DEF("CacheFlushBit", CacheFlushBit), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestResourceRecord() -{ - nlTestSuite theSuite = { "ResourceRecord", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestResourceRecord) diff --git a/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordIP.cpp b/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordIP.cpp index 659b0609db11be..c79507d2f454e6 100644 --- a/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordIP.cpp +++ b/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordIP.cpp @@ -15,10 +15,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include -#include +#include + +#include namespace { @@ -30,11 +30,11 @@ using namespace chip::Encoding::BigEndian; const QNamePart kNames[] = { "some", "test", "local" }; #if INET_CONFIG_ENABLE_IPV4 -void WriteIPv4(nlTestSuite * inSuite, void * inContext) +TEST(TestResourceRecordIP, WriteIPv4) { IPAddress ipAddress; - NL_TEST_ASSERT(inSuite, IPAddress::FromString("10.20.30.40", ipAddress)); + EXPECT_TRUE(IPAddress::FromString("10.20.30.40", ipAddress)); uint8_t headerBuffer[HeaderRef::kSizeBytes]; uint8_t dataBuffer[128]; @@ -63,12 +63,12 @@ void WriteIPv4(nlTestSuite * inSuite, void * inContext) 10, 20, 30, 40 // IP Address }; - NL_TEST_ASSERT(inSuite, ipResourceRecord.Append(header, ResourceType::kAnswer, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == 1); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == 0); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == 0); - NL_TEST_ASSERT(inSuite, output.Needed() == sizeof(expectedOutput)); - NL_TEST_ASSERT(inSuite, memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)) == 0); + EXPECT_TRUE(ipResourceRecord.Append(header, ResourceType::kAnswer, writer)); + EXPECT_EQ(header.GetAnswerCount(), 1); + EXPECT_EQ(header.GetAuthorityCount(), 0); + EXPECT_EQ(header.GetAdditionalCount(), 0); + EXPECT_EQ(output.Needed(), sizeof(expectedOutput)); + EXPECT_EQ(memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)), 0); } { @@ -93,12 +93,12 @@ void WriteIPv4(nlTestSuite * inSuite, void * inContext) 10, 20, 30, 40 // IP Address }; - NL_TEST_ASSERT(inSuite, ipResourceRecord.Append(header, ResourceType::kAuthority, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == 0); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == 1); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == 0); - NL_TEST_ASSERT(inSuite, output.Needed() == sizeof(expectedOutput)); - NL_TEST_ASSERT(inSuite, memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)) == 0); + EXPECT_TRUE(ipResourceRecord.Append(header, ResourceType::kAuthority, writer)); + EXPECT_EQ(header.GetAnswerCount(), 0); + EXPECT_EQ(header.GetAuthorityCount(), 1); + EXPECT_EQ(header.GetAdditionalCount(), 0); + EXPECT_EQ(output.Needed(), sizeof(expectedOutput)); + EXPECT_EQ(memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)), 0); } { @@ -123,21 +123,21 @@ void WriteIPv4(nlTestSuite * inSuite, void * inContext) 10, 20, 30, 40 // IP Address }; - NL_TEST_ASSERT(inSuite, ipResourceRecord.Append(header, ResourceType::kAdditional, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == 0); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == 0); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == 1); - NL_TEST_ASSERT(inSuite, output.Needed() == sizeof(expectedOutput)); - NL_TEST_ASSERT(inSuite, memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)) == 0); + EXPECT_TRUE(ipResourceRecord.Append(header, ResourceType::kAdditional, writer)); + EXPECT_EQ(header.GetAnswerCount(), 0); + EXPECT_EQ(header.GetAuthorityCount(), 0); + EXPECT_EQ(header.GetAdditionalCount(), 1); + EXPECT_EQ(output.Needed(), sizeof(expectedOutput)); + EXPECT_EQ(memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)), 0); } } #endif // INET_CONFIG_ENABLE_IPV4 -void WriteIPv6(nlTestSuite * inSuite, void * inContext) +TEST(TestResourceRecordIP, WriteIPv6) { IPAddress ipAddress; - NL_TEST_ASSERT(inSuite, IPAddress::FromString("fe80::224:32ff:fe19:359b", ipAddress)); + EXPECT_TRUE(IPAddress::FromString("fe80::224:32ff:fe19:359b", ipAddress)); uint8_t headerBuffer[HeaderRef::kSizeBytes]; uint8_t dataBuffer[128]; @@ -167,31 +167,11 @@ void WriteIPv6(nlTestSuite * inSuite, void * inContext) 0xfe, 0x19, 0x35, 0x9b }; - NL_TEST_ASSERT(inSuite, ipResourceRecord.Append(header, ResourceType::kAnswer, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == 1); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == 0); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == 0); - NL_TEST_ASSERT(inSuite, output.Needed() == sizeof(expectedOutput)); - NL_TEST_ASSERT(inSuite, memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)) == 0); + EXPECT_TRUE(ipResourceRecord.Append(header, ResourceType::kAnswer, writer)); + EXPECT_EQ(header.GetAnswerCount(), 1); + EXPECT_EQ(header.GetAuthorityCount(), 0); + EXPECT_EQ(header.GetAdditionalCount(), 0); + EXPECT_EQ(output.Needed(), sizeof(expectedOutput)); + EXPECT_EQ(memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)), 0); } - -const nlTest sTests[] = { -#if INET_CONFIG_ENABLE_IPV4 - NL_TEST_DEF("IPV4", WriteIPv4), // -#endif // INET_CONFIG_ENABLE_IPV4 - NL_TEST_DEF("IPV6", WriteIPv6), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestIPResourceRecord() -{ - - nlTestSuite theSuite = { "IPResourceRecord", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestIPResourceRecord) diff --git a/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordPtr.cpp b/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordPtr.cpp index 3822fdf372f5ac..52cab32b727fd0 100644 --- a/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordPtr.cpp +++ b/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordPtr.cpp @@ -14,11 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include +#include -#include +#include namespace { @@ -26,7 +25,7 @@ using namespace chip; using namespace mdns::Minimal; using namespace chip::Encoding; -void TestPtrResourceRecord(nlTestSuite * inSuite, void * inContext) +TEST(TestResourceRecordPtr, TestPtrResourceRecord) { uint8_t headerBuffer[HeaderRef::kSizeBytes]; uint8_t dataBuffer[128]; @@ -59,26 +58,11 @@ void TestPtrResourceRecord(nlTestSuite * inSuite, void * inContext) 0 // QNAME ends }; - NL_TEST_ASSERT(inSuite, record.Append(header, ResourceType::kAnswer, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == 1); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == 0); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == 0); - NL_TEST_ASSERT(inSuite, output.Needed() == sizeof(expectedOutput)); - NL_TEST_ASSERT(inSuite, memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)) == 0); + EXPECT_TRUE(record.Append(header, ResourceType::kAnswer, writer)); + EXPECT_EQ(header.GetAnswerCount(), 1); + EXPECT_EQ(header.GetAuthorityCount(), 0); + EXPECT_EQ(header.GetAdditionalCount(), 0); + EXPECT_EQ(output.Needed(), sizeof(expectedOutput)); + EXPECT_EQ(memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)), 0); } - -const nlTest sTests[] = { - NL_TEST_DEF("TestPtrResourceRecord", TestPtrResourceRecord), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestPtrResourceRecord() -{ - nlTestSuite theSuite = { "PtrResourceRecord", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestPtrResourceRecord) diff --git a/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordSrv.cpp b/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordSrv.cpp index 6293f2eb8b130e..b213f11efd32cc 100644 --- a/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordSrv.cpp +++ b/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordSrv.cpp @@ -14,11 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include +#include -#include +#include namespace { @@ -26,7 +25,7 @@ using namespace chip; using namespace chip::Encoding; using namespace mdns::Minimal; -void TestSrv(nlTestSuite * inSuite, void * inContext) +TEST(TestResourceRecordSrv, TestSrv) { uint8_t headerBuffer[HeaderRef::kSizeBytes]; uint8_t dataBuffer[128]; @@ -45,10 +44,10 @@ void TestSrv(nlTestSuite * inSuite, void * inContext) header.Clear(); - NL_TEST_ASSERT(inSuite, record.Append(header, ResourceType::kAdditional, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == 0); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == 0); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == 1); + EXPECT_TRUE(record.Append(header, ResourceType::kAdditional, writer)); + EXPECT_EQ(header.GetAnswerCount(), 0); + EXPECT_EQ(header.GetAuthorityCount(), 0); + EXPECT_EQ(header.GetAdditionalCount(), 1); const uint8_t expectedOutput[] = { 4, 's', 'o', 'm', 'e', // QNAME part: some @@ -68,22 +67,7 @@ void TestSrv(nlTestSuite * inSuite, void * inContext) 0 // QNAME ends }; - NL_TEST_ASSERT(inSuite, output.Needed() == sizeof(expectedOutput)); - NL_TEST_ASSERT(inSuite, memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)) == 0); + EXPECT_EQ(output.Needed(), sizeof(expectedOutput)); + EXPECT_EQ(memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)), 0); } - -const nlTest sTests[] = { - NL_TEST_DEF("TestSrv", TestSrv), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestSrv() -{ - nlTestSuite theSuite = { "Srv", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestSrv) diff --git a/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordTxt.cpp b/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordTxt.cpp index 0930d68a875feb..f77066b8361fdc 100644 --- a/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordTxt.cpp +++ b/src/lib/dnssd/minimal_mdns/records/tests/TestResourceRecordTxt.cpp @@ -14,11 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include +#include -#include +#include namespace { @@ -26,7 +25,7 @@ using namespace chip; using namespace chip::Encoding; using namespace mdns::Minimal; -void TestTxt(nlTestSuite * inSuite, void * inContext) +TEST(TestResourceRecordTxt, TestTxt) { uint8_t headerBuffer[HeaderRef::kSizeBytes]; uint8_t dataBuffer[128]; @@ -41,14 +40,14 @@ void TestTxt(nlTestSuite * inSuite, void * inContext) TxtResourceRecord record(kName, kData); record.SetTtl(128); - NL_TEST_ASSERT(inSuite, record.GetNumEntries() == 3); + EXPECT_EQ(record.GetNumEntries(), 3u); header.Clear(); - NL_TEST_ASSERT(inSuite, record.Append(header, ResourceType::kAdditional, writer)); - NL_TEST_ASSERT(inSuite, header.GetAnswerCount() == 0); - NL_TEST_ASSERT(inSuite, header.GetAuthorityCount() == 0); - NL_TEST_ASSERT(inSuite, header.GetAdditionalCount() == 1); + EXPECT_TRUE(record.Append(header, ResourceType::kAdditional, writer)); + EXPECT_EQ(header.GetAnswerCount(), 0); + EXPECT_EQ(header.GetAuthorityCount(), 0); + EXPECT_EQ(header.GetAdditionalCount(), 1); const uint8_t expectedOutput[] = { 4, 's', 'o', 'm', 'e', // QNAME part: some @@ -64,22 +63,7 @@ void TestTxt(nlTestSuite * inSuite, void * inContext) 4, 'f', 'l', 'a', 'g' // ENTRY: flag }; - NL_TEST_ASSERT(inSuite, output.Needed() == sizeof(expectedOutput)); - NL_TEST_ASSERT(inSuite, memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)) == 0); + EXPECT_EQ(output.Needed(), sizeof(expectedOutput)); + EXPECT_EQ(memcmp(dataBuffer, expectedOutput, sizeof(expectedOutput)), 0); } - -const nlTest sTests[] = { - NL_TEST_DEF("TestTxt", TestTxt), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestTxt() -{ - nlTestSuite theSuite = { "Txt", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestTxt) diff --git a/src/lib/dnssd/minimal_mdns/responders/Responder.h b/src/lib/dnssd/minimal_mdns/responders/Responder.h index 534b661df64535..6675e0e957a257 100644 --- a/src/lib/dnssd/minimal_mdns/responders/Responder.h +++ b/src/lib/dnssd/minimal_mdns/responders/Responder.h @@ -21,7 +21,9 @@ #include #include -#include + +#include +#include namespace mdns { namespace Minimal { @@ -34,28 +36,26 @@ class ResponseConfiguration ResponseConfiguration() {} ~ResponseConfiguration() = default; - chip::Optional GetTtlSecondsOverride() const { return mTtlSecondsOverride; } - ResponseConfiguration & SetTtlSecondsOverride(chip::Optional override) + std::optional GetTtlSecondsOverride() const { return mTtlSecondsOverride; } + ResponseConfiguration & SetTtlSecondsOverride(std::optional override) { mTtlSecondsOverride = override; return *this; } - ResponseConfiguration & SetTtlSecondsOverride(uint32_t value) { return SetTtlSecondsOverride(chip::MakeOptional(value)); } - ResponseConfiguration & ClearTtlSecondsOverride() { return SetTtlSecondsOverride(chip::NullOptional); } + ResponseConfiguration & SetTtlSecondsOverride(uint32_t value) { return SetTtlSecondsOverride(std::make_optional(value)); } + ResponseConfiguration & ClearTtlSecondsOverride() { return SetTtlSecondsOverride(std::nullopt); } /// Applies any adjustments to resource records before they are being serialized /// to some form of reply. void Adjust(ResourceRecord & record) const { - if (mTtlSecondsOverride.HasValue()) - { - record.SetTtl(mTtlSecondsOverride.Value()); - } + VerifyOrReturn(mTtlSecondsOverride.has_value()); + record.SetTtl(*mTtlSecondsOverride); } private: - chip::Optional mTtlSecondsOverride; + std::optional mTtlSecondsOverride; }; // Delegates that responders can write themselves to diff --git a/src/lib/dnssd/minimal_mdns/responders/tests/BUILD.gn b/src/lib/dnssd/minimal_mdns/responders/tests/BUILD.gn index c09fcbbaa84d11..940cc82698e14a 100644 --- a/src/lib/dnssd/minimal_mdns/responders/tests/BUILD.gn +++ b/src/lib/dnssd/minimal_mdns/responders/tests/BUILD.gn @@ -14,11 +14,10 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libMinimalMdnsRespondersTests" test_sources = [ @@ -34,7 +33,5 @@ chip_test_suite_using_nltest("tests") { "${chip_root}/src/lib/dnssd/minimal_mdns", "${chip_root}/src/lib/dnssd/minimal_mdns:default_policy", "${chip_root}/src/lib/dnssd/minimal_mdns/responders", - "${chip_root}/src/lib/support:testing_nlunit", - "${nlunit_test_root}:nlunit-test", ] } diff --git a/src/lib/dnssd/minimal_mdns/responders/tests/TestIPResponder.cpp b/src/lib/dnssd/minimal_mdns/responders/tests/TestIPResponder.cpp index ca66dd184cc9e6..b24f2bedd4a1a8 100644 --- a/src/lib/dnssd/minimal_mdns/responders/tests/TestIPResponder.cpp +++ b/src/lib/dnssd/minimal_mdns/responders/tests/TestIPResponder.cpp @@ -20,9 +20,8 @@ #include #include -#include -#include +#include namespace { @@ -37,17 +36,13 @@ const QNamePart kNames[] = { "some", "test", "local" }; class IPResponseAccumulator : public ResponderDelegate { public: - IPResponseAccumulator(nlTestSuite * suite) : mSuite(suite) {} void AddResponse(const ResourceRecord & record) override { - NL_TEST_ASSERT(mSuite, (record.GetType() == QType::A) || (record.GetType() == QType::AAAA)); - NL_TEST_ASSERT(mSuite, record.GetClass() == QClass::IN_FLUSH); - NL_TEST_ASSERT(mSuite, record.GetName() == kNames); + EXPECT_TRUE((record.GetType() == QType::A) || (record.GetType() == QType::AAAA)); + EXPECT_EQ(record.GetClass(), QClass::IN_FLUSH); + EXPECT_EQ(record.GetName(), kNames); } - -private: - nlTestSuite * mSuite; }; InterfaceId FindValidInterfaceId() @@ -62,19 +57,30 @@ InterfaceId FindValidInterfaceId() return InterfaceId::Null(); } +class TestIPResponder : public ::testing::Test +{ +public: + static void SetUpTestSuite() + { + mdns::Minimal::SetDefaultAddressPolicy(); + ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); + } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + #if INET_CONFIG_ENABLE_IPV4 -void TestIPv4(nlTestSuite * inSuite, void * inContext) +TEST_F(TestIPResponder, TestIPv4) { IPAddress ipAddress; - NL_TEST_ASSERT(inSuite, IPAddress::FromString("10.20.30.40", ipAddress)); + EXPECT_TRUE(IPAddress::FromString("10.20.30.40", ipAddress)); IPv4Responder responder(kNames); - NL_TEST_ASSERT(inSuite, responder.GetQClass() == QClass::IN); - NL_TEST_ASSERT(inSuite, responder.GetQType() == QType::A); - NL_TEST_ASSERT(inSuite, responder.GetQName() == kNames); + EXPECT_EQ(responder.GetQClass(), QClass::IN); + EXPECT_EQ(responder.GetQType(), QType::A); + EXPECT_EQ(responder.GetQName(), kNames); - IPResponseAccumulator acc(inSuite); + IPResponseAccumulator acc; chip::Inet::IPPacketInfo packetInfo; packetInfo.SrcAddress = ipAddress; @@ -87,18 +93,18 @@ void TestIPv4(nlTestSuite * inSuite, void * inContext) } #endif // INET_CONFIG_ENABLE_IPV4 -void TestIPv6(nlTestSuite * inSuite, void * inContext) +TEST_F(TestIPResponder, TestIPv6) { IPAddress ipAddress; - NL_TEST_ASSERT(inSuite, IPAddress::FromString("fe80::224:32ff:aabb:ccdd", ipAddress)); + EXPECT_TRUE(IPAddress::FromString("fe80::224:32ff:aabb:ccdd", ipAddress)); IPv6Responder responder(kNames); - NL_TEST_ASSERT(inSuite, responder.GetQClass() == QClass::IN); - NL_TEST_ASSERT(inSuite, responder.GetQType() == QType::AAAA); - NL_TEST_ASSERT(inSuite, responder.GetQName() == kNames); + EXPECT_EQ(responder.GetQClass(), QClass::IN); + EXPECT_EQ(responder.GetQType(), QType::AAAA); + EXPECT_EQ(responder.GetQName(), kNames); - IPResponseAccumulator acc(inSuite); + IPResponseAccumulator acc; chip::Inet::IPPacketInfo packetInfo; packetInfo.SrcAddress = ipAddress; @@ -110,36 +116,4 @@ void TestIPv6(nlTestSuite * inSuite, void * inContext) responder.AddAllResponses(&packetInfo, &acc, ResponseConfiguration()); } -int Setup(void * inContext) -{ - mdns::Minimal::SetDefaultAddressPolicy(); - - CHIP_ERROR error = chip::Platform::MemoryInit(); - - return (error == CHIP_NO_ERROR) ? SUCCESS : FAILURE; -} - -int Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -const nlTest sTests[] = { -#if INET_CONFIG_ENABLE_IPV4 - NL_TEST_DEF("TestIPv4", TestIPv4), // -#endif // INET_CONFIG_ENABLE_IPV4 - NL_TEST_DEF("TestIPv6", TestIPv6), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestIP() -{ - nlTestSuite theSuite = { "IP", sTests, &Setup, &Teardown }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestIP) diff --git a/src/lib/dnssd/minimal_mdns/responders/tests/TestPtrResponder.cpp b/src/lib/dnssd/minimal_mdns/responders/tests/TestPtrResponder.cpp index 135a1a1d6e7f7c..f1c2ba6f9e25c2 100644 --- a/src/lib/dnssd/minimal_mdns/responders/tests/TestPtrResponder.cpp +++ b/src/lib/dnssd/minimal_mdns/responders/tests/TestPtrResponder.cpp @@ -20,9 +20,8 @@ #include #include -#include -#include +#include namespace { @@ -39,13 +38,13 @@ const QNamePart kTargetNames[] = { "point", "to", "this" }; class PtrResponseAccumulator : public ResponderDelegate { public: - PtrResponseAccumulator(nlTestSuite * suite, const uint32_t expectedTtl) : mSuite(suite), mExpectedTtl(expectedTtl) {} + PtrResponseAccumulator(const uint32_t expectedTtl) : mExpectedTtl(expectedTtl) {} void AddResponse(const ResourceRecord & record) override { - NL_TEST_ASSERT(mSuite, record.GetType() == QType::PTR); - NL_TEST_ASSERT(mSuite, record.GetClass() == QClass::IN); - NL_TEST_ASSERT(mSuite, record.GetName() == kNames); + EXPECT_EQ(record.GetType(), QType::PTR); + EXPECT_EQ(record.GetClass(), QClass::IN); + EXPECT_EQ(record.GetName(), kNames); if (record.GetType() == QType::PTR) { @@ -58,44 +57,43 @@ class PtrResponseAccumulator : public ResponderDelegate HeaderRef hdr(headerBuffer); hdr.Clear(); - NL_TEST_ASSERT(mSuite, record.Append(hdr, ResourceType::kAnswer, writer)); + EXPECT_TRUE(record.Append(hdr, ResourceType::kAnswer, writer)); ResourceData data; SerializedQNameIterator target; const uint8_t * start = buffer; - NL_TEST_ASSERT(mSuite, out.Fit()); + EXPECT_TRUE(out.Fit()); BytesRange validDataRange(buffer, buffer + out.Needed()); - NL_TEST_ASSERT(mSuite, data.Parse(validDataRange, &start)); - NL_TEST_ASSERT(mSuite, start == (buffer + out.Needed())); - NL_TEST_ASSERT(mSuite, data.GetName() == FullQName(kNames)); - NL_TEST_ASSERT(mSuite, data.GetType() == QType::PTR); - NL_TEST_ASSERT(mSuite, data.GetTtlSeconds() == mExpectedTtl); + EXPECT_TRUE(data.Parse(validDataRange, &start)); + EXPECT_EQ(start, (buffer + out.Needed())); + EXPECT_EQ(data.GetName(), FullQName(kNames)); + EXPECT_EQ(data.GetType(), QType::PTR); + EXPECT_EQ(data.GetTtlSeconds(), mExpectedTtl); - NL_TEST_ASSERT(mSuite, ParsePtrRecord(data.GetData(), validDataRange, &target)); - NL_TEST_ASSERT(mSuite, target == FullQName(kTargetNames)); + EXPECT_TRUE(ParsePtrRecord(data.GetData(), validDataRange, &target)); + EXPECT_EQ(target, FullQName(kTargetNames)); } } private: - nlTestSuite * mSuite; const uint32_t mExpectedTtl; }; -void TestPtrResponse(nlTestSuite * inSuite, void * inContext) +TEST(TestPtrResponder, TestPtrResponse) { IPAddress ipAddress; - NL_TEST_ASSERT(inSuite, IPAddress::FromString("2607:f8b0:4005:804::200e", ipAddress)); + EXPECT_TRUE(IPAddress::FromString("2607:f8b0:4005:804::200e", ipAddress)); PtrResponder responder(kNames, kTargetNames); - NL_TEST_ASSERT(inSuite, responder.GetQClass() == QClass::IN); - NL_TEST_ASSERT(inSuite, responder.GetQType() == QType::PTR); - NL_TEST_ASSERT(inSuite, responder.GetQName() == kNames); + EXPECT_EQ(responder.GetQClass(), QClass::IN); + EXPECT_EQ(responder.GetQType(), QType::PTR); + EXPECT_EQ(responder.GetQName(), kNames); - PtrResponseAccumulator acc(inSuite, ResourceRecord::kDefaultTtl); + PtrResponseAccumulator acc(ResourceRecord::kDefaultTtl); chip::Inet::IPPacketInfo packetInfo; packetInfo.SrcAddress = ipAddress; @@ -107,18 +105,18 @@ void TestPtrResponse(nlTestSuite * inSuite, void * inContext) responder.AddAllResponses(&packetInfo, &acc, ResponseConfiguration()); } -void TestPtrResponseOverrideTtl(nlTestSuite * inSuite, void * inContext) +TEST(TestPtrResponder, TestPtrResponseOverrideTtl) { IPAddress ipAddress; - NL_TEST_ASSERT(inSuite, IPAddress::FromString("2607:f8b0:4005:804::200e", ipAddress)); + EXPECT_TRUE(IPAddress::FromString("2607:f8b0:4005:804::200e", ipAddress)); PtrResponder responder(kNames, kTargetNames); - NL_TEST_ASSERT(inSuite, responder.GetQClass() == QClass::IN); - NL_TEST_ASSERT(inSuite, responder.GetQType() == QType::PTR); - NL_TEST_ASSERT(inSuite, responder.GetQName() == kNames); + EXPECT_EQ(responder.GetQClass(), QClass::IN); + EXPECT_EQ(responder.GetQType(), QType::PTR); + EXPECT_EQ(responder.GetQName(), kNames); - PtrResponseAccumulator acc(inSuite, 123); + PtrResponseAccumulator acc(123); chip::Inet::IPPacketInfo packetInfo; packetInfo.SrcAddress = ipAddress; @@ -129,20 +127,4 @@ void TestPtrResponseOverrideTtl(nlTestSuite * inSuite, void * inContext) responder.AddAllResponses(&packetInfo, &acc, ResponseConfiguration().SetTtlSecondsOverride(123)); } - -const nlTest sTests[] = { - NL_TEST_DEF("TestPtrResponse", TestPtrResponse), // - NL_TEST_DEF("TestPtrResponseOverrideTtl", TestPtrResponseOverrideTtl), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestPtr() -{ - nlTestSuite theSuite = { "IP", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestPtr) diff --git a/src/lib/dnssd/minimal_mdns/responders/tests/TestQueryResponder.cpp b/src/lib/dnssd/minimal_mdns/responders/tests/TestQueryResponder.cpp index 09494a40745f86..bf0ff0413e38f6 100644 --- a/src/lib/dnssd/minimal_mdns/responders/tests/TestQueryResponder.cpp +++ b/src/lib/dnssd/minimal_mdns/responders/tests/TestQueryResponder.cpp @@ -20,9 +20,7 @@ #include -#include - -#include +#include namespace { @@ -44,13 +42,12 @@ class EmptyResponder : public RecordResponder class DnssdReplyAccumulator : public ResponderDelegate { public: - DnssdReplyAccumulator(nlTestSuite * suite) : mSuite(suite) {} void AddResponse(const ResourceRecord & record) override { - NL_TEST_ASSERT(mSuite, record.GetType() == QType::PTR); - NL_TEST_ASSERT(mSuite, record.GetClass() == QClass::IN); - NL_TEST_ASSERT(mSuite, record.GetName() == kDnsSdname); + EXPECT_EQ(record.GetType(), QType::PTR); + EXPECT_EQ(record.GetClass(), QClass::IN); + EXPECT_EQ(record.GetName(), kDnsSdname); mCaptures.push_back(reinterpret_cast(record).GetPtr()); } @@ -58,11 +55,10 @@ class DnssdReplyAccumulator : public ResponderDelegate std::vector & Captures() { return mCaptures; } private: - nlTestSuite * mSuite; std::vector mCaptures; }; -void CanIterateOverResponders(nlTestSuite * inSuite, void * inContext) +TEST(TestQueryResponder, CanIterateOverResponders) { QueryResponder<10> responder; @@ -70,24 +66,24 @@ void CanIterateOverResponders(nlTestSuite * inSuite, void * inContext) EmptyResponder empty2(kName2); EmptyResponder empty3(kName2); - NL_TEST_ASSERT(inSuite, responder.AddResponder(&empty1).SetReportInServiceListing(true).IsValid()); - NL_TEST_ASSERT(inSuite, responder.AddResponder(&empty2).SetReportInServiceListing(true).IsValid()); - NL_TEST_ASSERT(inSuite, responder.AddResponder(&empty3).SetReportInServiceListing(true).IsValid()); + EXPECT_TRUE(responder.AddResponder(&empty1).SetReportInServiceListing(true).IsValid()); + EXPECT_TRUE(responder.AddResponder(&empty2).SetReportInServiceListing(true).IsValid()); + EXPECT_TRUE(responder.AddResponder(&empty3).SetReportInServiceListing(true).IsValid()); int idx = 0; QueryResponderRecordFilter noFilter; for (auto it = responder.begin(&noFilter); it != responder.end(); it++, idx++) { FullQName qName = it->responder->GetQName(); - NL_TEST_ASSERT(inSuite, (idx != 0) || (qName == kDnsSdname)); - NL_TEST_ASSERT(inSuite, (idx != 1) || (qName == kName1)); - NL_TEST_ASSERT(inSuite, (idx != 2) || (qName == kName2)); - NL_TEST_ASSERT(inSuite, (idx != 3) || (qName == kName2)); + EXPECT_TRUE((idx != 0) || (qName == kDnsSdname)); + EXPECT_TRUE((idx != 1) || (qName == kName1)); + EXPECT_TRUE((idx != 2) || (qName == kName2)); + EXPECT_TRUE((idx != 3) || (qName == kName2)); } - NL_TEST_ASSERT(inSuite, idx == 4); + EXPECT_EQ(idx, 4); } -void RespondsToDnsSdQueries(nlTestSuite * inSuite, void * inContext) +TEST(TestQueryResponder, RespondsToDnsSdQueries) { QueryResponder<10> responder; QueryResponderRecordFilter noFilter; @@ -97,44 +93,44 @@ void RespondsToDnsSdQueries(nlTestSuite * inSuite, void * inContext) EmptyResponder empty3(kName1); EmptyResponder empty4(kName1); - NL_TEST_ASSERT(inSuite, responder.AddResponder(&empty1).IsValid()); - NL_TEST_ASSERT(inSuite, responder.AddResponder(&empty2).SetReportInServiceListing(true).IsValid()); - NL_TEST_ASSERT(inSuite, responder.AddResponder(&empty3).SetReportInServiceListing(true).IsValid()); - NL_TEST_ASSERT(inSuite, responder.AddResponder(&empty4).IsValid()); + EXPECT_TRUE(responder.AddResponder(&empty1).IsValid()); + EXPECT_TRUE(responder.AddResponder(&empty2).SetReportInServiceListing(true).IsValid()); + EXPECT_TRUE(responder.AddResponder(&empty3).SetReportInServiceListing(true).IsValid()); + EXPECT_TRUE(responder.AddResponder(&empty4).IsValid()); // It reports itself inside the iterator - NL_TEST_ASSERT(inSuite, &(*responder.begin(&noFilter)->responder) == &responder); + EXPECT_EQ(&(*responder.begin(&noFilter)->responder), &responder); // It reponds dnssd PTR answers - NL_TEST_ASSERT(inSuite, responder.GetQClass() == QClass::IN); - NL_TEST_ASSERT(inSuite, responder.GetQType() == QType::PTR); - NL_TEST_ASSERT(inSuite, responder.GetQName() == kDnsSdname); + EXPECT_EQ(responder.GetQClass(), QClass::IN); + EXPECT_EQ(responder.GetQType(), QType::PTR); + EXPECT_EQ(responder.GetQName(), kDnsSdname); - DnssdReplyAccumulator accumulator(inSuite); + DnssdReplyAccumulator accumulator; responder.AddAllResponses(nullptr, &accumulator, ResponseConfiguration()); - NL_TEST_ASSERT(inSuite, accumulator.Captures().size() == 2); + EXPECT_EQ(accumulator.Captures().size(), 2u); if (accumulator.Captures().size() == 2) { - NL_TEST_ASSERT(inSuite, accumulator.Captures()[0] == kName2); - NL_TEST_ASSERT(inSuite, accumulator.Captures()[1] == kName1); + EXPECT_EQ(accumulator.Captures()[0], kName2); + EXPECT_EQ(accumulator.Captures()[1], kName1); } } -void LimitedStorage(nlTestSuite * inSuite, void * inContext) +TEST(TestQueryResponder, LimitedStorage) { QueryResponder<3> responder; EmptyResponder empty1(kName1); EmptyResponder empty2(kName2); - NL_TEST_ASSERT(inSuite, responder.AddResponder(&empty1).SetReportInServiceListing(true).IsValid()); - NL_TEST_ASSERT(inSuite, responder.AddResponder(&empty2).SetReportInServiceListing(true).IsValid()); + EXPECT_TRUE(responder.AddResponder(&empty1).SetReportInServiceListing(true).IsValid()); + EXPECT_TRUE(responder.AddResponder(&empty2).SetReportInServiceListing(true).IsValid()); for (int i = 0; i < 100; i++) { EmptyResponder emptyX(kName1); - NL_TEST_ASSERT(inSuite, !responder.AddResponder(&emptyX).SetReportInServiceListing(true).IsValid()); + EXPECT_FALSE(responder.AddResponder(&emptyX).SetReportInServiceListing(true).IsValid()); } int idx = 0; @@ -142,48 +138,30 @@ void LimitedStorage(nlTestSuite * inSuite, void * inContext) for (auto it = responder.begin(&noFilter); it != responder.end(); it++, idx++) { FullQName qName = it->responder->GetQName(); - NL_TEST_ASSERT(inSuite, (idx != 0) || (qName == kDnsSdname)); - NL_TEST_ASSERT(inSuite, (idx != 1) || (qName == kName1)); - NL_TEST_ASSERT(inSuite, (idx != 2) || (qName == kName2)); + EXPECT_TRUE((idx != 0) || (qName == kDnsSdname)); + EXPECT_TRUE((idx != 1) || (qName == kName1)); + EXPECT_TRUE((idx != 2) || (qName == kName2)); } - NL_TEST_ASSERT(inSuite, idx == 3); + EXPECT_EQ(idx, 3); } -void NonDiscoverableService(nlTestSuite * inSuite, void * inContext) +TEST(TestQueryResponder, NonDiscoverableService) { QueryResponder<3> responder; EmptyResponder empty1(kName1); EmptyResponder empty2(kName2); - NL_TEST_ASSERT(inSuite, responder.AddResponder(&empty1).IsValid()); - NL_TEST_ASSERT(inSuite, responder.AddResponder(&empty2).SetReportInServiceListing(true).IsValid()); + EXPECT_TRUE(responder.AddResponder(&empty1).IsValid()); + EXPECT_TRUE(responder.AddResponder(&empty2).SetReportInServiceListing(true).IsValid()); - DnssdReplyAccumulator accumulator(inSuite); + DnssdReplyAccumulator accumulator; responder.AddAllResponses(nullptr, &accumulator, ResponseConfiguration()); - NL_TEST_ASSERT(inSuite, accumulator.Captures().size() == 1); + EXPECT_EQ(accumulator.Captures().size(), 1u); if (accumulator.Captures().size() == 1) { - NL_TEST_ASSERT(inSuite, accumulator.Captures()[0] == kName2); + EXPECT_EQ(accumulator.Captures()[0], kName2); } } - -const nlTest sTests[] = { - NL_TEST_DEF("CanIterateOverResponders", CanIterateOverResponders), // - NL_TEST_DEF("RespondsToDnsSdQueries", RespondsToDnsSdQueries), // - NL_TEST_DEF("LimitedStorage", LimitedStorage), // - NL_TEST_DEF("NonDiscoverableService", NonDiscoverableService), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestQueryResponder() -{ - nlTestSuite theSuite = { "QueryResponder", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestQueryResponder) diff --git a/src/lib/dnssd/minimal_mdns/tests/BUILD.gn b/src/lib/dnssd/minimal_mdns/tests/BUILD.gn index 8d99854046e307..dc09e4b4b59d5d 100644 --- a/src/lib/dnssd/minimal_mdns/tests/BUILD.gn +++ b/src/lib/dnssd/minimal_mdns/tests/BUILD.gn @@ -14,12 +14,11 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") import("${chip_root}/build/chip/fuzz_test.gni") -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libMinimalMdnstests" sources = [ "CheckOnlyServer.h" ] @@ -40,9 +39,7 @@ chip_test_suite_using_nltest("tests") { "${chip_root}/src/lib/core", "${chip_root}/src/lib/dnssd", "${chip_root}/src/lib/dnssd/minimal_mdns", - "${chip_root}/src/lib/support:testing_nlunit", "${chip_root}/src/transport/raw/tests:helpers", - "${nlunit_test_root}:nlunit-test", ] } diff --git a/src/lib/dnssd/minimal_mdns/tests/CheckOnlyServer.h b/src/lib/dnssd/minimal_mdns/tests/CheckOnlyServer.h index c5b8f9e21f060b..1aabc6738d00e6 100644 --- a/src/lib/dnssd/minimal_mdns/tests/CheckOnlyServer.h +++ b/src/lib/dnssd/minimal_mdns/tests/CheckOnlyServer.h @@ -29,10 +29,9 @@ #include #include #include -#include #include -#include +#include namespace mdns { namespace Minimal { @@ -78,23 +77,19 @@ class CheckOnlyServer : private chip::PoolImpl(this)), mInSuite(inSuite) - { - Reset(); - } - CheckOnlyServer() : ServerBase(*static_cast(this)), mInSuite(nullptr) { Reset(); } + CheckOnlyServer() : ServerBase(*static_cast(this)) { Reset(); } ~CheckOnlyServer() {} // Parser delegates void OnHeader(ConstHeaderRef & header) override { - NL_TEST_ASSERT(mInSuite, header.GetFlags().IsResponse()); - NL_TEST_ASSERT(mInSuite, header.GetFlags().IsValidMdns()); + EXPECT_TRUE(header.GetFlags().IsResponse()); + EXPECT_TRUE(header.GetFlags().IsValidMdns()); mTotalRecords += header.GetAnswerCount() + header.GetAdditionalCount(); if (!header.GetFlags().IsTruncated()) { - NL_TEST_ASSERT(mInSuite, mTotalRecords == GetNumExpectedRecords()); + EXPECT_EQ(mTotalRecords, GetNumExpectedRecords()); if (mTotalRecords != GetNumExpectedRecords()) { ChipLogError(Discovery, "Received %d records, expected %d", mTotalRecords, GetNumExpectedRecords()); @@ -114,7 +109,7 @@ class CheckOnlyServer : private chip::PoolImplGetNumEntries(); ++t) { bool ok = AddExpectedTxtRecord(expectedTxt->GetEntries()[t]); - NL_TEST_ASSERT(mInSuite, ok); + EXPECT_TRUE(ok); } ParseTxtRecord(data.GetData(), this); if (CheckTxtRecordMatches()) @@ -164,7 +159,7 @@ class CheckOnlyServer : private chip::PoolImpl #include #include -#include -#include + #include #include -#include +#include namespace { @@ -237,29 +236,57 @@ CHIP_ERROR SendQuery(FullQName qname) return CHIP_NO_ERROR; } -void OperationalAdverts(nlTestSuite * inSuite, void * inContext) +class TestAdvertiser : public ::testing::Test { - auto & mdnsAdvertiser = chip::Dnssd::ServiceAdvertiser::Instance(); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.RemoveServices() == CHIP_NO_ERROR); +public: + static chip::Test::IOContext context; + static CheckOnlyServer server; + static chip::Dnssd::ServiceAdvertiser * mdnsAdvertiser; + + static void SetUpTestSuite() + { + chip::Platform::MemoryInit(); + context.Init(); + chip::Dnssd::GlobalMinimalMdnsServer::Instance().Server().Shutdown(); + chip::Dnssd::GlobalMinimalMdnsServer::Instance().SetReplacementServer(&server); + mdnsAdvertiser = &chip::Dnssd::ServiceAdvertiser::Instance(); + mdnsAdvertiser->Init(context.GetUDPEndPointManager()); + } + static void TearDownTestSuite() + { + server.Shutdown(); + context.Shutdown(); + mdnsAdvertiser->RemoveServices(); + mdnsAdvertiser->Shutdown(); + chip::Dnssd::GlobalMinimalMdnsServer::Instance().SetReplacementServer(nullptr); + chip::Platform::MemoryShutdown(); + } +}; + +chip::Test::IOContext TestAdvertiser::context; +CheckOnlyServer TestAdvertiser::server; +chip::Dnssd::ServiceAdvertiser * TestAdvertiser::mdnsAdvertiser; + +TEST_F(TestAdvertiser, OperationalAdverts) +{ + EXPECT_EQ(mdnsAdvertiser->RemoveServices(), CHIP_NO_ERROR); - auto & server = static_cast(GlobalMinimalMdnsServer::Server()); - server.SetTestSuite(inSuite); server.Reset(); // Start a single operational advertiser ChipLogProgress(Discovery, "Testing single operational advertiser"); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.Advertise(operationalParams1) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.FinalizeServiceUpdate() == CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->Advertise(operationalParams1), CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->FinalizeServiceUpdate(), CHIP_NO_ERROR); // Test for PTR response to _services request. ChipLogProgress(Discovery, "Checking response to _services._dns-sd._udp.local"); server.AddExpectedRecord(&ptrOperationalService); server.AddExpectedRecord(&ptrServiceSubCompressedId1); - NL_TEST_ASSERT(inSuite, SendQuery(kDnsSdQueryName) == CHIP_NO_ERROR); + EXPECT_EQ(SendQuery(kDnsSdQueryName), CHIP_NO_ERROR); // These check that the requested records added are sent out correctly. - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); // Want PTR response to _matter.tcp. We will also get the SRV and TXT as additionals. // We won't get any A/AAAA because this is a test and we don't have addresses. @@ -271,31 +298,31 @@ void OperationalAdverts(nlTestSuite * inSuite, void * inContext) server.AddExpectedRecord(&srvOperational1); server.AddExpectedRecord(&txtOperational1); - NL_TEST_ASSERT(inSuite, SendQuery(kMatterOperationalQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kMatterOperationalQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); ChipLogProgress(Discovery, "Testing response to instance name"); server.Reset(); // Just the SRV and TXT should return server.AddExpectedRecord(&srvOperational1); server.AddExpectedRecord(&txtOperational1); - NL_TEST_ASSERT(inSuite, SendQuery(kInstanceName1) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kInstanceName1), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); // If we try to re-advertise with the same operational parameters, we should not get duplicates - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.Advertise(operationalParams1) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.FinalizeServiceUpdate() == CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->Advertise(operationalParams1), CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->FinalizeServiceUpdate(), CHIP_NO_ERROR); ChipLogProgress(Discovery, "Testing single operational advertiser with Advertise called twice"); // We should get a single PTR back for _services ChipLogProgress(Discovery, "Checking response to _services._dns-sd._udp.local"); server.Reset(); server.AddExpectedRecord(&ptrOperationalService); server.AddExpectedRecord(&ptrServiceSubCompressedId1); - NL_TEST_ASSERT(inSuite, SendQuery(kDnsSdQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kDnsSdQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); // Same records should come back for _matter._tcp.local queries. ChipLogProgress(Discovery, "Testing response to _matter._tcp.local"); @@ -303,16 +330,16 @@ void OperationalAdverts(nlTestSuite * inSuite, void * inContext) server.AddExpectedRecord(&ptrOperational1); server.AddExpectedRecord(&srvOperational1); server.AddExpectedRecord(&txtOperational1); - NL_TEST_ASSERT(inSuite, SendQuery(kMatterOperationalQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kMatterOperationalQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); // Adding a second operational advertiser. ChipLogProgress(Discovery, "Adding a second operational Advertiser"); server.Reset(); // Mac is the same, peer id is different - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.Advertise(operationalParams2) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.FinalizeServiceUpdate() == CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->Advertise(operationalParams2), CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->FinalizeServiceUpdate(), CHIP_NO_ERROR); // For now, we'll get back two copies of the PTR. Not sure if that's totally correct, but for now, that's expected. ChipLogProgress(Discovery, "Checking response to _services._dns-sd._udp.local"); @@ -320,9 +347,9 @@ void OperationalAdverts(nlTestSuite * inSuite, void * inContext) server.AddExpectedRecord(&ptrOperationalService); server.AddExpectedRecord(&ptrServiceSubCompressedId1); server.AddExpectedRecord(&ptrServiceSubCompressedId2); - NL_TEST_ASSERT(inSuite, SendQuery(kDnsSdQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kDnsSdQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); // Requests for _matter._tcp.local will respond with all records from both parameter sets ChipLogProgress(Discovery, "Testing response to _matter._tcp.local"); @@ -333,9 +360,9 @@ void OperationalAdverts(nlTestSuite * inSuite, void * inContext) server.AddExpectedRecord(&ptrOperational2); server.AddExpectedRecord(&srvOperational2); server.AddExpectedRecord(&txtOperational2); - NL_TEST_ASSERT(inSuite, SendQuery(kMatterOperationalQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kMatterOperationalQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); // Requests for each SRV record should give only records specific to that fabric. ChipLogProgress(Discovery, "Testing response to instance name for fabric 1"); @@ -343,79 +370,75 @@ void OperationalAdverts(nlTestSuite * inSuite, void * inContext) // Just the SRV and TXT should return server.AddExpectedRecord(&srvOperational1); server.AddExpectedRecord(&txtOperational1); - NL_TEST_ASSERT(inSuite, SendQuery(kInstanceName1) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kInstanceName1), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); ChipLogProgress(Discovery, "Testing response to instance name for fabric 2"); server.Reset(); // Just the SRV and TXT should return server.AddExpectedRecord(&srvOperational2); server.AddExpectedRecord(&txtOperational2); - NL_TEST_ASSERT(inSuite, SendQuery(kInstanceName2) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kInstanceName2), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); // All devices should support at least 5 operational network additions (spec min) // however larger devices may support more. - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.Advertise(operationalParams3) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.Advertise(operationalParams4) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.Advertise(operationalParams5) == CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->Advertise(operationalParams3), CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->Advertise(operationalParams4), CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->Advertise(operationalParams5), CHIP_NO_ERROR); } -void CommissionableAdverts(nlTestSuite * inSuite, void * inContext) +TEST_F(TestAdvertiser, CommissionableAdverts) { - auto & mdnsAdvertiser = chip::Dnssd::ServiceAdvertiser::Instance(); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.RemoveServices() == CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->RemoveServices(), CHIP_NO_ERROR); - auto & server = static_cast(GlobalMinimalMdnsServer::Server()); - server.SetTestSuite(inSuite); server.Reset(); // Start a single operational advertiser ChipLogProgress(Discovery, "Testing commissionable advertiser"); // Start very basic - only the mandatory values (short and long discriminator and commissioning modes) - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.Advertise(commissionableNodeParamsSmall) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.FinalizeServiceUpdate() == CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->Advertise(commissionableNodeParamsSmall), CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->FinalizeServiceUpdate(), CHIP_NO_ERROR); // Test for PTR response to _services request. ChipLogProgress(Discovery, "Checking response to _services._dns-sd._udp.local for small parameters"); server.AddExpectedRecord(&ptrCommissionableNodeService); server.AddExpectedRecord(&ptrServiceSubLFullLen); server.AddExpectedRecord(&ptrServiceSubSFullLen); - NL_TEST_ASSERT(inSuite, SendQuery(kDnsSdQueryName) == CHIP_NO_ERROR); + EXPECT_EQ(SendQuery(kDnsSdQueryName), CHIP_NO_ERROR); // These check that the requested records added are sent out correctly. - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); // Want PTR response to _matterc._udp. We will also get the SRV and TXT as additionals. // We won't get any A/AAAA because this is a test and we don't have addresses. // First fill in the instance name - FullQNames already have this space included. - NL_TEST_ASSERT(inSuite, - mdnsAdvertiser.GetCommissionableInstanceName(instanceNamePrefix, sizeof(instanceNamePrefix)) == CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->GetCommissionableInstanceName(instanceNamePrefix, sizeof(instanceNamePrefix)), CHIP_NO_ERROR); ChipLogProgress(Discovery, "Testing response to _matterc._udp.local for small parameters"); server.Reset(); server.AddExpectedRecord(&ptrCommissionableNode); server.AddExpectedRecord(&srvCommissionableNode); server.AddExpectedRecord(&txtCommissionableNodeParamsSmall); - NL_TEST_ASSERT(inSuite, SendQuery(kMatterCommissionableNodeQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kMatterCommissionableNodeQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); ChipLogProgress(Discovery, "Testing response to instance name for small parameters"); server.Reset(); // Just the SRV and TXT should return server.AddExpectedRecord(&srvCommissionableNode); server.AddExpectedRecord(&txtCommissionableNodeParamsSmall); - NL_TEST_ASSERT(inSuite, SendQuery(instanceName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(instanceName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); // Add more parameters, check that the subtypes and TXT values get set correctly. // Also check that we get proper values when the discriminators are small (no leading 0's) - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.Advertise(commissionableNodeParamsLargeBasic) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.FinalizeServiceUpdate() == CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->Advertise(commissionableNodeParamsLargeBasic), CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->FinalizeServiceUpdate(), CHIP_NO_ERROR); ChipLogProgress(Discovery, "Checking response to _services._dns-sd._udp.local for large basic parameters"); server.Reset(); server.AddExpectedRecord(&ptrCommissionableNodeService); @@ -424,30 +447,30 @@ void CommissionableAdverts(nlTestSuite * inSuite, void * inContext) server.AddExpectedRecord(&ptrServiceSubCM); server.AddExpectedRecord(&ptrServiceSubVendor); server.AddExpectedRecord(&ptrServiceSubDeviceType); - NL_TEST_ASSERT(inSuite, SendQuery(kDnsSdQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kDnsSdQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); ChipLogProgress(Discovery, "Testing response to _matterc._udp.local for large basic parameters"); server.Reset(); server.AddExpectedRecord(&ptrCommissionableNode); server.AddExpectedRecord(&srvCommissionableNode); server.AddExpectedRecord(&txtCommissionableNodeParamsLargeBasic); - NL_TEST_ASSERT(inSuite, SendQuery(kMatterCommissionableNodeQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kMatterCommissionableNodeQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); ChipLogProgress(Discovery, "Testing response to instance name for large basic parameters"); server.Reset(); // Just the SRV and TXT should return server.AddExpectedRecord(&srvCommissionableNode); server.AddExpectedRecord(&txtCommissionableNodeParamsLargeBasic); - NL_TEST_ASSERT(inSuite, SendQuery(instanceName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(instanceName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.Advertise(commissionableNodeParamsLargeEnhanced) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.FinalizeServiceUpdate() == CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->Advertise(commissionableNodeParamsLargeEnhanced), CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->FinalizeServiceUpdate(), CHIP_NO_ERROR); ChipLogProgress(Discovery, "Checking response to _services._dns-sd._udp.local for large enhanced parameters"); server.Reset(); server.AddExpectedRecord(&ptrCommissionableNodeService); @@ -456,65 +479,62 @@ void CommissionableAdverts(nlTestSuite * inSuite, void * inContext) server.AddExpectedRecord(&ptrServiceSubCM); server.AddExpectedRecord(&ptrServiceSubVendor); server.AddExpectedRecord(&ptrServiceSubDeviceType); - NL_TEST_ASSERT(inSuite, SendQuery(kDnsSdQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kDnsSdQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); ChipLogProgress(Discovery, "Testing response to _matterc._udp.local for large enhanced parameters"); server.Reset(); server.AddExpectedRecord(&ptrCommissionableNode); server.AddExpectedRecord(&srvCommissionableNode); server.AddExpectedRecord(&txtCommissionableNodeParamsLargeEnhanced); - NL_TEST_ASSERT(inSuite, SendQuery(kMatterCommissionableNodeQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kMatterCommissionableNodeQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); ChipLogProgress(Discovery, "Testing response to instance name for large enhanced parameters"); server.Reset(); // Just the SRV and TXT should return server.AddExpectedRecord(&srvCommissionableNode); server.AddExpectedRecord(&txtCommissionableNodeParamsLargeEnhanced); - NL_TEST_ASSERT(inSuite, SendQuery(instanceName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(instanceName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); #if CHIP_CONFIG_ENABLE_ICD_SERVER - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.Advertise(commissionableNodeParamsEnhancedAsICDLIT) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.FinalizeServiceUpdate() == CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->Advertise(commissionableNodeParamsEnhancedAsICDLIT), CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->FinalizeServiceUpdate(), CHIP_NO_ERROR); ChipLogProgress(Discovery, "Testing response to _matterc._udp.local for enhanced parameters With ICD as LIT"); server.Reset(); server.AddExpectedRecord(&ptrCommissionableNode); server.AddExpectedRecord(&srvCommissionableNode); server.AddExpectedRecord(&txtCommissionableNodeParamsEnhancedAsICDLIT); - NL_TEST_ASSERT(inSuite, SendQuery(kMatterCommissionableNodeQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kMatterCommissionableNodeQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); ChipLogProgress(Discovery, "Testing response to instance name for enhanced parameters With ICD as LIT"); server.Reset(); // Just the SRV and TXT should return server.AddExpectedRecord(&srvCommissionableNode); server.AddExpectedRecord(&txtCommissionableNodeParamsEnhancedAsICDLIT); - NL_TEST_ASSERT(inSuite, SendQuery(instanceName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(instanceName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); #endif } -void CommissionableAndOperationalAdverts(nlTestSuite * inSuite, void * inContext) +TEST_F(TestAdvertiser, CommissionableAndOperationalAdverts) { - auto & mdnsAdvertiser = chip::Dnssd::ServiceAdvertiser::Instance(); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.RemoveServices() == CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->RemoveServices(), CHIP_NO_ERROR); - auto & server = static_cast(GlobalMinimalMdnsServer::Server()); - server.SetTestSuite(inSuite); server.Reset(); // Add two operational and a commissionable and test that we get the correct values back. - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.Advertise(operationalParams1) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.Advertise(operationalParams2) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.Advertise(commissionableNodeParamsLargeEnhanced) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsAdvertiser.FinalizeServiceUpdate() == CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->Advertise(operationalParams1), CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->Advertise(operationalParams2), CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->Advertise(commissionableNodeParamsLargeEnhanced), CHIP_NO_ERROR); + EXPECT_EQ(mdnsAdvertiser->FinalizeServiceUpdate(), CHIP_NO_ERROR); // Services listing should have two operational ptrs, the base commissionable node ptr and the various _sub ptrs ChipLogProgress(Discovery, "Checking response to _services._dns-sd._udp.local"); @@ -529,9 +549,9 @@ void CommissionableAndOperationalAdverts(nlTestSuite * inSuite, void * inContext server.AddExpectedRecord(&ptrServiceSubDeviceType); server.AddExpectedRecord(&ptrServiceSubCompressedId1); server.AddExpectedRecord(&ptrServiceSubCompressedId2); - NL_TEST_ASSERT(inSuite, SendQuery(kDnsSdQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kDnsSdQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); // Requests for _matter._tcp.local will respond with all records from both operational records, but no commissionable. ChipLogProgress(Discovery, "Testing response to _matter._tcp.local"); @@ -542,9 +562,9 @@ void CommissionableAndOperationalAdverts(nlTestSuite * inSuite, void * inContext server.AddExpectedRecord(&ptrOperational2); server.AddExpectedRecord(&srvOperational2); server.AddExpectedRecord(&txtOperational2); - NL_TEST_ASSERT(inSuite, SendQuery(kMatterOperationalQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kMatterOperationalQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); // Responses to _matterc query should return commissionable node, but no operational. ChipLogProgress(Discovery, "Testing response to _matterc._udp.local"); @@ -552,9 +572,9 @@ void CommissionableAndOperationalAdverts(nlTestSuite * inSuite, void * inContext server.AddExpectedRecord(&ptrCommissionableNode); server.AddExpectedRecord(&srvCommissionableNode); server.AddExpectedRecord(&txtCommissionableNodeParamsLargeEnhanced); - NL_TEST_ASSERT(inSuite, SendQuery(kMatterCommissionableNodeQueryName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kMatterCommissionableNodeQueryName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); // Requests for each SRV record should give only records specific to that fabric. ChipLogProgress(Discovery, "Testing response to operational instance name for fabric 1"); @@ -562,56 +582,26 @@ void CommissionableAndOperationalAdverts(nlTestSuite * inSuite, void * inContext // Just the SRV and TXT should return server.AddExpectedRecord(&srvOperational1); server.AddExpectedRecord(&txtOperational1); - NL_TEST_ASSERT(inSuite, SendQuery(kInstanceName1) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kInstanceName1), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); ChipLogProgress(Discovery, "Testing response to operational instance name for fabric 2"); server.Reset(); // Just the SRV and TXT should return server.AddExpectedRecord(&srvOperational2); server.AddExpectedRecord(&txtOperational2); - NL_TEST_ASSERT(inSuite, SendQuery(kInstanceName2) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(kInstanceName2), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); ChipLogProgress(Discovery, "Testing response to commissionable instance name"); server.Reset(); // Just the SRV and TXT should return server.AddExpectedRecord(&srvCommissionableNode); server.AddExpectedRecord(&txtCommissionableNodeParamsLargeEnhanced); - NL_TEST_ASSERT(inSuite, SendQuery(instanceName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, server.GetHeaderFound()); + EXPECT_EQ(SendQuery(instanceName), CHIP_NO_ERROR); + EXPECT_TRUE(server.GetSendCalled()); + EXPECT_TRUE(server.GetHeaderFound()); } - -const nlTest sTests[] = { - NL_TEST_DEF("OperationalAdverts", OperationalAdverts), // - NL_TEST_DEF("CommissionableNodeAdverts", CommissionableAdverts), // - NL_TEST_DEF("CommissionableAndOperationalAdverts", CommissionableAndOperationalAdverts), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestAdvertiser() -{ - chip::Platform::MemoryInit(); - chip::Test::IOContext context; - context.Init(); - nlTestSuite theSuite = { "AdvertiserImplMinimal", sTests, nullptr, nullptr }; - CheckOnlyServer server(&theSuite); - test::ServerSwapper swapper(&server); - auto & mdnsAdvertiser = chip::Dnssd::ServiceAdvertiser::Instance(); - mdnsAdvertiser.Init(context.GetUDPEndPointManager()); - nlTestRunner(&theSuite, &server); - server.Shutdown(); - context.Shutdown(); - mdnsAdvertiser.RemoveServices(); - mdnsAdvertiser.Shutdown(); - chip::Platform::MemoryShutdown(); - - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestAdvertiser) diff --git a/src/lib/dnssd/minimal_mdns/tests/TestMinimalMdnsAllocator.cpp b/src/lib/dnssd/minimal_mdns/tests/TestMinimalMdnsAllocator.cpp index c712b1bd647f47..f571e81fcf27d1 100644 --- a/src/lib/dnssd/minimal_mdns/tests/TestMinimalMdnsAllocator.cpp +++ b/src/lib/dnssd/minimal_mdns/tests/TestMinimalMdnsAllocator.cpp @@ -16,11 +16,9 @@ * limitations under the License. */ -#include - -#include +#include -#include +#include using namespace chip; using namespace chip::Dnssd; @@ -42,21 +40,21 @@ class TestAllocator : public QueryResponderAllocator // void dmalloc_track(const dmalloc_track_t track_func) #endif } - void TestAllQNamesAreNull(nlTestSuite * inSuite) + void TestAllQNamesAreNull() { for (size_t i = 0; i < GetMaxAllocatedQNames(); ++i) { - NL_TEST_ASSERT(inSuite, GetQNamePart(i) == nullptr); + EXPECT_EQ(GetQNamePart(i), nullptr); } } - void TestAllRecordRespondersAreNull(nlTestSuite * inSuite) + void TestAllRecordRespondersAreNull() { for (size_t i = 0; i < kMaxRecords; ++i) { - NL_TEST_ASSERT(inSuite, GetRecordResponder(i) == nullptr); + EXPECT_EQ(GetRecordResponder(i), nullptr); } } - void TestRecordRespondersMatchQuery(nlTestSuite * inSuite) + void TestRecordRespondersMatchQuery() { mdns::Minimal::QueryResponderRecordFilter noFilter; auto queryResponder = GetQueryResponder(); @@ -64,56 +62,63 @@ class TestAllocator : public QueryResponderAllocator for (auto it = queryResponder->begin(&noFilter); it != queryResponder->end(); it++, idx++) { // TODO: Once the responders are exposed in the query responder, check that they match. - NL_TEST_ASSERT(inSuite, idx < kMaxRecords); + EXPECT_LT(idx, kMaxRecords); } } size_t GetMaxAllocatedQNames() { return QueryResponderAllocator::GetMaxAllocatedQNames(); } }; -void TestQueryAllocatorQName(nlTestSuite * inSuite, void * inContext) +class TestMinimalMdnsAllocator : public ::testing::Test +{ +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestMinimalMdnsAllocator, TestQueryAllocatorQName) { TestAllocator test; #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC unsigned long mark = dmalloc_mark(); #endif // Start empty. - test.TestAllRecordRespondersAreNull(inSuite); - test.TestAllQNamesAreNull(inSuite); + test.TestAllRecordRespondersAreNull(); + test.TestAllQNamesAreNull(); // We should be able to add up to GetMaxAllocatedQNames QNames for (size_t i = 0; i < test.GetMaxAllocatedQNames(); ++i) { - NL_TEST_ASSERT(inSuite, test.AllocateQName("test", "testy", "udp") != FullQName()); - test.TestAllRecordRespondersAreNull(inSuite); + EXPECT_NE(test.AllocateQName("test", "testy", "udp"), FullQName()); + test.TestAllRecordRespondersAreNull(); } #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC // Count the memory that has not been freed at this point (since mark) unsigned long nAllocated = dmalloc_count_changed(mark, 1, 0); - NL_TEST_ASSERT(inSuite, nAllocated != 0); + EXPECT_NE(nAllocated, 0); #endif // Adding one more should fail. - NL_TEST_ASSERT(inSuite, test.AllocateQName("test", "testy", "udp") == FullQName()); - test.TestAllRecordRespondersAreNull(inSuite); + EXPECT_EQ(test.AllocateQName("test", "testy", "udp"), FullQName()); + test.TestAllRecordRespondersAreNull(); #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC // We should not have allocated any more memory - NL_TEST_ASSERT(inSuite, nAllocated == dmalloc_count_changed(mark, 1, 0)); + EXPECT_EQ(nAllocated, dmalloc_count_changed(mark, 1, 0)); #endif // Clear should take us back to all empty. test.Clear(); - test.TestAllQNamesAreNull(inSuite); - test.TestAllRecordRespondersAreNull(inSuite); + test.TestAllQNamesAreNull(); + test.TestAllRecordRespondersAreNull(); #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC // The amount of unfreed pointers should be 0. - NL_TEST_ASSERT(inSuite, dmalloc_count_changed(mark, 1, 0) == 0); + EXPECT_EQ(dmalloc_count_changed(mark, 1, 0), 0); #endif } -void TestQueryAllocatorQNameArray(nlTestSuite * inSuite, void * inContext) +TEST_F(TestMinimalMdnsAllocator, TestQueryAllocatorQNameArray) { TestAllocator test; @@ -125,43 +130,43 @@ void TestQueryAllocatorQNameArray(nlTestSuite * inSuite, void * inContext) const char * kArray[kNumParts] = { "this", "is", "a", "test" }; // Start empty. - test.TestAllRecordRespondersAreNull(inSuite); - test.TestAllQNamesAreNull(inSuite); + test.TestAllRecordRespondersAreNull(); + test.TestAllQNamesAreNull(); // We should be able to add up to GetMaxAllocatedQNames QNames for (size_t i = 0; i < test.GetMaxAllocatedQNames(); ++i) { - NL_TEST_ASSERT(inSuite, test.AllocateQNameFromArray(kArray, kNumParts) != FullQName()); - test.TestAllRecordRespondersAreNull(inSuite); + EXPECT_NE(test.AllocateQNameFromArray(kArray, kNumParts), FullQName()); + test.TestAllRecordRespondersAreNull(); } #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC // Count the memory that has not been freed at this point (since mark) unsigned long nAllocated = dmalloc_count_changed(mark, 1, 0); - NL_TEST_ASSERT(inSuite, nAllocated != 0); + EXPECT_NE(nAllocated, 0); #endif // Adding one more should fail. - NL_TEST_ASSERT(inSuite, test.AllocateQNameFromArray(kArray, kNumParts) == FullQName()); - test.TestAllRecordRespondersAreNull(inSuite); + EXPECT_EQ(test.AllocateQNameFromArray(kArray, kNumParts), FullQName()); + test.TestAllRecordRespondersAreNull(); #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC // We should not have allocated any more memory - NL_TEST_ASSERT(inSuite, nAllocated == dmalloc_count_changed(mark, 1, 0)); + EXPECT_EQ(nAllocated, dmalloc_count_changed(mark, 1, 0)); #endif // Clear should take us back to all empty. test.Clear(); - test.TestAllQNamesAreNull(inSuite); - test.TestAllRecordRespondersAreNull(inSuite); + test.TestAllQNamesAreNull(); + test.TestAllRecordRespondersAreNull(); #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC // The amount of unfreed pointers should be 0. - NL_TEST_ASSERT(inSuite, dmalloc_count_changed(mark, 1, 0) == 0); + EXPECT_EQ(dmalloc_count_changed(mark, 1, 0), 0); #endif } -void TestQueryAllocatorRecordResponder(nlTestSuite * inSuite, void * inContext) +TEST_F(TestMinimalMdnsAllocator, TestQueryAllocatorRecordResponder) { TestAllocator test; @@ -169,42 +174,42 @@ void TestQueryAllocatorRecordResponder(nlTestSuite * inSuite, void * inContext) unsigned long mark = dmalloc_mark(); #endif // Start empty. - test.TestAllRecordRespondersAreNull(inSuite); - test.TestAllQNamesAreNull(inSuite); + test.TestAllRecordRespondersAreNull(); + test.TestAllQNamesAreNull(); FullQName serviceName = test.AllocateQName("test", "service"); FullQName instanceName = test.AllocateQName("test", "instance"); for (size_t i = 0; i < kMaxRecords; ++i) { - NL_TEST_ASSERT(inSuite, test.AddResponder(serviceName, instanceName).IsValid()); + EXPECT_TRUE(test.AddResponder(serviceName, instanceName).IsValid()); } #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC // Count the memory that has not been freed at this point (since mark) unsigned long nAllocated = dmalloc_count_changed(mark, 1, 0); - NL_TEST_ASSERT(inSuite, nAllocated != 0); + EXPECT_NE(nAllocated, 0); #endif // Adding one more should fail. - NL_TEST_ASSERT(inSuite, !test.AddResponder(serviceName, instanceName).IsValid()); + EXPECT_FALSE(test.AddResponder(serviceName, instanceName).IsValid()); #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC // We should not have allocated any more memory - NL_TEST_ASSERT(inSuite, nAllocated == dmalloc_count_changed(mark, 1, 0)); + EXPECT_EQ(nAllocated, dmalloc_count_changed(mark, 1, 0)); #endif // Clear should take us back to all empty. test.Clear(); - test.TestAllQNamesAreNull(inSuite); - test.TestAllRecordRespondersAreNull(inSuite); + test.TestAllQNamesAreNull(); + test.TestAllRecordRespondersAreNull(); #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC // The amount of unfreed pointers should be 0. - NL_TEST_ASSERT(inSuite, dmalloc_count_changed(mark, 1, 0) == 0); + EXPECT_EQ(dmalloc_count_changed(mark, 1, 0), 0); #endif } -void TestQueryAllocatorRecordResponderTypes(nlTestSuite * inSuite, void * inContext) +TEST_F(TestMinimalMdnsAllocator, TestQueryAllocatorRecordResponderTypes) { TestAllocator test; @@ -212,49 +217,49 @@ void TestQueryAllocatorRecordResponderTypes(nlTestSuite * inSuite, void * inCont unsigned long mark = dmalloc_mark(); #endif // Start empty. - test.TestAllRecordRespondersAreNull(inSuite); - test.TestAllQNamesAreNull(inSuite); + test.TestAllRecordRespondersAreNull(); + test.TestAllQNamesAreNull(); FullQName serviceName = test.AllocateQName("test", "service"); FullQName instanceName = test.AllocateQName("test", "instance"); FullQName hostName = test.AllocateQName("test", "host"); FullQName someTxt = test.AllocateQName("L1=some text", "L2=some other text"); - NL_TEST_ASSERT(inSuite, serviceName != FullQName()); - NL_TEST_ASSERT(inSuite, instanceName != FullQName()); - NL_TEST_ASSERT(inSuite, hostName != FullQName()); - NL_TEST_ASSERT(inSuite, someTxt != FullQName()); + EXPECT_NE(serviceName, FullQName()); + EXPECT_NE(instanceName, FullQName()); + EXPECT_NE(hostName, FullQName()); + EXPECT_NE(someTxt, FullQName()); // Test that we can add all types - NL_TEST_ASSERT(inSuite, test.AddResponder(serviceName, instanceName).IsValid()); - NL_TEST_ASSERT(inSuite, test.AddResponder(SrvResourceRecord(instanceName, hostName, 57)).IsValid()); - NL_TEST_ASSERT(inSuite, test.AddResponder(TxtResourceRecord(instanceName, someTxt)).IsValid()); - NL_TEST_ASSERT(inSuite, test.AddResponder(hostName).IsValid()); - NL_TEST_ASSERT(inSuite, test.AddResponder(hostName).IsValid()); + EXPECT_TRUE(test.AddResponder(serviceName, instanceName).IsValid()); + EXPECT_TRUE(test.AddResponder(SrvResourceRecord(instanceName, hostName, 57)).IsValid()); + EXPECT_TRUE(test.AddResponder(TxtResourceRecord(instanceName, someTxt)).IsValid()); + EXPECT_TRUE(test.AddResponder(hostName).IsValid()); + EXPECT_TRUE(test.AddResponder(hostName).IsValid()); #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC // Count the memory that has not been freed at this point (since mark) unsigned long nAllocated = dmalloc_count_changed(mark, 1, 0); - NL_TEST_ASSERT(inSuite, nAllocated != 0); + EXPECT_NE(nAllocated, 0); #endif // Clear should take us back to all empty. test.Clear(); - test.TestAllQNamesAreNull(inSuite); - test.TestAllRecordRespondersAreNull(inSuite); + test.TestAllQNamesAreNull(); + test.TestAllRecordRespondersAreNull(); #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC // The amount of unfreed pointers should be 0. - NL_TEST_ASSERT(inSuite, dmalloc_count_changed(mark, 1, 0) == 0); + EXPECT_EQ(dmalloc_count_changed(mark, 1, 0), 0); #endif } -void TestGetResponder(nlTestSuite * inSuite, void * inContext) +TEST_F(TestMinimalMdnsAllocator, TestGetResponder) { TestAllocator test; // Start empty. - test.TestAllRecordRespondersAreNull(inSuite); - test.TestAllQNamesAreNull(inSuite); + test.TestAllRecordRespondersAreNull(); + test.TestAllQNamesAreNull(); FullQName serviceName = test.AllocateQName("test", "service"); FullQName instanceName = test.AllocateQName("test", "instance"); @@ -262,68 +267,40 @@ void TestGetResponder(nlTestSuite * inSuite, void * inContext) FullQName someTxt = test.AllocateQName("L1=some text", "L2=some other text"); FullQName notAdded = test.AllocateQName("not", "added"); - NL_TEST_ASSERT(inSuite, serviceName != FullQName()); - NL_TEST_ASSERT(inSuite, instanceName != FullQName()); - NL_TEST_ASSERT(inSuite, hostName != FullQName()); - NL_TEST_ASSERT(inSuite, someTxt != FullQName()); + EXPECT_NE(serviceName, FullQName()); + EXPECT_NE(instanceName, FullQName()); + EXPECT_NE(hostName, FullQName()); + EXPECT_NE(someTxt, FullQName()); - NL_TEST_ASSERT(inSuite, test.AddResponder(serviceName, instanceName).IsValid()); - NL_TEST_ASSERT(inSuite, test.AddResponder(SrvResourceRecord(instanceName, hostName, 57)).IsValid()); - NL_TEST_ASSERT(inSuite, test.AddResponder(TxtResourceRecord(instanceName, someTxt)).IsValid()); - NL_TEST_ASSERT(inSuite, test.AddResponder(hostName).IsValid()); - NL_TEST_ASSERT(inSuite, test.AddResponder(hostName).IsValid()); + EXPECT_TRUE(test.AddResponder(serviceName, instanceName).IsValid()); + EXPECT_TRUE(test.AddResponder(SrvResourceRecord(instanceName, hostName, 57)).IsValid()); + EXPECT_TRUE(test.AddResponder(TxtResourceRecord(instanceName, someTxt)).IsValid()); + EXPECT_TRUE(test.AddResponder(hostName).IsValid()); + EXPECT_TRUE(test.AddResponder(hostName).IsValid()); // These should all exist - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::PTR, serviceName) != nullptr); - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::SRV, instanceName) != nullptr); - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::TXT, instanceName) != nullptr); - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::A, hostName) != nullptr); - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::AAAA, hostName) != nullptr); + ASSERT_NE(test.GetResponder(QType::PTR, serviceName), nullptr); + ASSERT_NE(test.GetResponder(QType::SRV, instanceName), nullptr); + ASSERT_NE(test.GetResponder(QType::TXT, instanceName), nullptr); + ASSERT_NE(test.GetResponder(QType::A, hostName), nullptr); + ASSERT_NE(test.GetResponder(QType::AAAA, hostName), nullptr); // incorrect types - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::SRV, notAdded) == nullptr); - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::AAAA, instanceName) == nullptr); - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::A, instanceName) == nullptr); - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::PTR, hostName) == nullptr); - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::TXT, hostName) == nullptr); + EXPECT_EQ(test.GetResponder(QType::SRV, notAdded), nullptr); + EXPECT_EQ(test.GetResponder(QType::AAAA, instanceName), nullptr); + EXPECT_EQ(test.GetResponder(QType::A, instanceName), nullptr); + EXPECT_EQ(test.GetResponder(QType::PTR, hostName), nullptr); + EXPECT_EQ(test.GetResponder(QType::TXT, hostName), nullptr); // incorrect names - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::PTR, notAdded) == nullptr); - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::SRV, notAdded) == nullptr); - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::TXT, notAdded) == nullptr); - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::A, notAdded) == nullptr); - NL_TEST_ASSERT(inSuite, test.GetResponder(QType::AAAA, notAdded) == nullptr); + EXPECT_EQ(test.GetResponder(QType::PTR, notAdded), nullptr); + EXPECT_EQ(test.GetResponder(QType::SRV, notAdded), nullptr); + EXPECT_EQ(test.GetResponder(QType::TXT, notAdded), nullptr); + EXPECT_EQ(test.GetResponder(QType::A, notAdded), nullptr); + EXPECT_EQ(test.GetResponder(QType::AAAA, notAdded), nullptr); test.Clear(); } -const nlTest sTests[] = { - NL_TEST_DEF("TestQueryAllocatorQName", TestQueryAllocatorQName), // - NL_TEST_DEF("TestQueryAllocatorQNameArray", TestQueryAllocatorQNameArray), // - NL_TEST_DEF("TestQueryAllocatorRecordResponder", TestQueryAllocatorRecordResponder), // - NL_TEST_DEF("TestQueryAllocatorRecordResponderTypes", TestQueryAllocatorRecordResponderTypes), // - NL_TEST_DEF("TestGetResponder", TestGetResponder), // - - NL_TEST_SENTINEL() // -}; - -int TestSetup(void * inContext) -{ - return chip::Platform::MemoryInit() == CHIP_NO_ERROR ? SUCCESS : FAILURE; -} - -int TestTeardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - } // namespace -int TestMinimalMdnsAllocator() -{ - nlTestSuite theSuite = { "MinimalMdnsAllocator", &sTests[0], &TestSetup, &TestTeardown }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestMinimalMdnsAllocator); +; diff --git a/src/lib/dnssd/minimal_mdns/tests/TestQueryReplyFilter.cpp b/src/lib/dnssd/minimal_mdns/tests/TestQueryReplyFilter.cpp index 690c28b6193929..234b6876c6b7fe 100644 --- a/src/lib/dnssd/minimal_mdns/tests/TestQueryReplyFilter.cpp +++ b/src/lib/dnssd/minimal_mdns/tests/TestQueryReplyFilter.cpp @@ -14,10 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include +#include -#include +#include namespace { @@ -35,7 +34,7 @@ QueryData buildQueryData(QType qType, QClass qClass, const uint8_t (&query)[N]) return QueryData(qType, qClass, false, query, BytesRange(query, query + N)); } -void TestQueryReplyFilter(nlTestSuite * inSuite, void * inContext) +TEST(TestQueryReplyFilter, TestQueryReplyFilter) { const uint8_t query[] = { 4, 's', 'o', 'm', 'e', // @@ -44,45 +43,34 @@ void TestQueryReplyFilter(nlTestSuite * inSuite, void * inContext) }; // sanity test that the serialized qname was build correctly - NL_TEST_ASSERT(inSuite, SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query) == FullQName(kName1)); - NL_TEST_ASSERT(inSuite, SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query) != FullQName(kName2)); - NL_TEST_ASSERT(inSuite, SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query) != FullQName(kName3)); - NL_TEST_ASSERT(inSuite, SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query) != FullQName(kName4)); + EXPECT_EQ(SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query), FullQName(kName1)); + EXPECT_NE(SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query), FullQName(kName2)); + EXPECT_NE(SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query), FullQName(kName3)); + EXPECT_NE(SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query), FullQName(kName4)); // Acceptable cases - NL_TEST_ASSERT( - inSuite, QueryReplyFilter(buildQueryData(QType::ANY, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); - NL_TEST_ASSERT(inSuite, - QueryReplyFilter(buildQueryData(QType::A, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); + EXPECT_TRUE(QueryReplyFilter(buildQueryData(QType::ANY, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); + EXPECT_TRUE(QueryReplyFilter(buildQueryData(QType::A, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); - NL_TEST_ASSERT(inSuite, - QueryReplyFilter(buildQueryData(QType::ANY, QClass::IN, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); + EXPECT_TRUE(QueryReplyFilter(buildQueryData(QType::ANY, QClass::IN, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); - NL_TEST_ASSERT(inSuite, - QueryReplyFilter(buildQueryData(QType::A, QClass::IN, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); + EXPECT_TRUE(QueryReplyFilter(buildQueryData(QType::A, QClass::IN, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); // Reject cases - NL_TEST_ASSERT( - inSuite, !QueryReplyFilter(buildQueryData(QType::ANY, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName2))); + EXPECT_FALSE(QueryReplyFilter(buildQueryData(QType::ANY, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName2))); - NL_TEST_ASSERT( - inSuite, !QueryReplyFilter(buildQueryData(QType::ANY, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName3))); + EXPECT_FALSE(QueryReplyFilter(buildQueryData(QType::ANY, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName3))); - NL_TEST_ASSERT( - inSuite, !QueryReplyFilter(buildQueryData(QType::ANY, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName4))); + EXPECT_FALSE(QueryReplyFilter(buildQueryData(QType::ANY, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName4))); - NL_TEST_ASSERT( - inSuite, - !QueryReplyFilter(buildQueryData(QType::AAAA, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); + EXPECT_FALSE(QueryReplyFilter(buildQueryData(QType::AAAA, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); - NL_TEST_ASSERT( - inSuite, !QueryReplyFilter(buildQueryData(QType::SRV, QClass::IN, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); + EXPECT_FALSE(QueryReplyFilter(buildQueryData(QType::SRV, QClass::IN, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); - NL_TEST_ASSERT( - inSuite, !QueryReplyFilter(buildQueryData(QType::PTR, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); + EXPECT_FALSE(QueryReplyFilter(buildQueryData(QType::PTR, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); } -void TestLongerQueryPath(nlTestSuite * inSuite, void * inContext) +TEST(TestQueryReplyFilter, TestLongerQueryPath) { const uint8_t query[] = { 4, 'm', 'o', 'r', 'e', // @@ -93,30 +81,12 @@ void TestLongerQueryPath(nlTestSuite * inSuite, void * inContext) }; // sanity test that the serialized qname was build correctly - NL_TEST_ASSERT(inSuite, SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query) != FullQName(kName1)); - NL_TEST_ASSERT(inSuite, SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query) != FullQName(kName2)); - NL_TEST_ASSERT(inSuite, SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query) == FullQName(kName3)); - NL_TEST_ASSERT(inSuite, SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query) != FullQName(kName4)); - - NL_TEST_ASSERT( - inSuite, !QueryReplyFilter(buildQueryData(QType::ANY, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); - NL_TEST_ASSERT( - inSuite, QueryReplyFilter(buildQueryData(QType::ANY, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName3))); -} + EXPECT_NE(SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query), FullQName(kName1)); + EXPECT_NE(SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query), FullQName(kName2)); + EXPECT_EQ(SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query), FullQName(kName3)); + EXPECT_NE(SerializedQNameIterator(BytesRange(query, query + sizeof(query)), query), FullQName(kName4)); -const nlTest sTests[] = { - NL_TEST_DEF("TestQueryReplyFilter", TestQueryReplyFilter), // - NL_TEST_DEF("TestLongerQueryPath", TestLongerQueryPath), // - NL_TEST_SENTINEL() // -}; - -} // namespace - -int TestQueryReplyFilter() -{ - nlTestSuite theSuite = { "QueryReplyFilter", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); + EXPECT_FALSE(QueryReplyFilter(buildQueryData(QType::ANY, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName1))); + EXPECT_TRUE(QueryReplyFilter(buildQueryData(QType::ANY, QClass::ANY, query)).Accept(QType::A, QClass::IN, FullQName(kName3))); } - -CHIP_REGISTER_TEST_SUITE(TestQueryReplyFilter) +} // namespace diff --git a/src/lib/dnssd/minimal_mdns/tests/TestRecordData.cpp b/src/lib/dnssd/minimal_mdns/tests/TestRecordData.cpp index 181b9d3b6f93fa..295ed2296215bf 100644 --- a/src/lib/dnssd/minimal_mdns/tests/TestRecordData.cpp +++ b/src/lib/dnssd/minimal_mdns/tests/TestRecordData.cpp @@ -19,9 +19,7 @@ #include #include -#include - -#include +#include namespace { @@ -29,7 +27,7 @@ using namespace std; using namespace chip; using namespace mdns::Minimal; -void SrvRecordSimpleParsing(nlTestSuite * inSuite, void * inContext) +TEST(TestRecordData, SrvRecordSimpleParsing) { const uint8_t record[] = { 0, 12, // Priority @@ -46,27 +44,27 @@ void SrvRecordSimpleParsing(nlTestSuite * inSuite, void * inContext) SrvRecord srv; - NL_TEST_ASSERT(inSuite, srv.Parse(data, packet)); - NL_TEST_ASSERT(inSuite, srv.GetPriority() == 12); - NL_TEST_ASSERT(inSuite, srv.GetWeight() == 3); - NL_TEST_ASSERT(inSuite, srv.GetPort() == 0x1234); + EXPECT_TRUE(srv.Parse(data, packet)); + EXPECT_EQ(srv.GetPriority(), 12); + EXPECT_EQ(srv.GetWeight(), 3); + EXPECT_EQ(srv.GetPort(), 0x1234); // name can be read several times for (int i = 0; i < 3; i++) { SerializedQNameIterator name = srv.GetName(); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "some") == 0); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "test") == 0); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "local") == 0); - NL_TEST_ASSERT(inSuite, name.Next() == false); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "some"); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "test"); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "local"); + EXPECT_EQ(name.Next(), false); } } -void SrvWithPtrRecord(nlTestSuite * inSuite, void * inContext) +TEST(TestRecordData, SrvWithPtrRecord) { const uint8_t record[] = { 'x', 'y', 'z', // dummy data (3 bytes) @@ -86,27 +84,27 @@ void SrvWithPtrRecord(nlTestSuite * inSuite, void * inContext) SrvRecord srv; - NL_TEST_ASSERT(inSuite, srv.Parse(data, packet)); - NL_TEST_ASSERT(inSuite, srv.GetPriority() == 12); - NL_TEST_ASSERT(inSuite, srv.GetWeight() == 3); - NL_TEST_ASSERT(inSuite, srv.GetPort() == 0x1234); + EXPECT_TRUE(srv.Parse(data, packet)); + EXPECT_EQ(srv.GetPriority(), 12); + EXPECT_EQ(srv.GetWeight(), 3); + EXPECT_EQ(srv.GetPort(), 0x1234); // name can be read several times for (int i = 0; i < 3; i++) { SerializedQNameIterator name = srv.GetName(); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "foo") == 0); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "some") == 0); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "test") == 0); - NL_TEST_ASSERT(inSuite, name.Next() == false); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "foo"); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "some"); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "test"); + EXPECT_EQ(name.Next(), false); } } -void ARecordParsing(nlTestSuite * inSuite, void * inContext) +TEST(TestRecordData, ARecordParsing) { const uint8_t record[] = { 10, @@ -120,15 +118,15 @@ void ARecordParsing(nlTestSuite * inSuite, void * inContext) #if INET_CONFIG_ENABLE_IPV4 Inet::IPAddress expected; - NL_TEST_ASSERT(inSuite, ParseARecord(BytesRange(record, record + sizeof(record)), &addr)); - NL_TEST_ASSERT(inSuite, Inet::IPAddress::FromString("10.11.12.13", expected)); - NL_TEST_ASSERT(inSuite, addr == expected); + EXPECT_TRUE(ParseARecord(BytesRange(record, record + sizeof(record)), &addr)); + EXPECT_TRUE(Inet::IPAddress::FromString("10.11.12.13", expected)); + EXPECT_EQ(addr, expected); #else - NL_TEST_ASSERT(inSuite, !ParseARecord(BytesRange(record, record + sizeof(record)), &addr)); + EXPECT_FALSE(ParseARecord(BytesRange(record, record + sizeof(record)), &addr)); #endif // INET_CONFIG_ENABLE_IPV4 } -void AAAARecordParsing(nlTestSuite * inSuite, void * inContext) +TEST(TestRecordData, AAAARecordParsing) { const uint8_t record[] = { 0x12, 0x23, 0x00, 0x00, // @@ -140,12 +138,12 @@ void AAAARecordParsing(nlTestSuite * inSuite, void * inContext) Inet::IPAddress addr; Inet::IPAddress expected; - NL_TEST_ASSERT(inSuite, ParseAAAARecord(BytesRange(record, record + sizeof(record)), &addr)); - NL_TEST_ASSERT(inSuite, Inet::IPAddress::FromString("1223::3456:789A", expected)); - NL_TEST_ASSERT(inSuite, addr == expected); + EXPECT_TRUE(ParseAAAARecord(BytesRange(record, record + sizeof(record)), &addr)); + EXPECT_TRUE(Inet::IPAddress::FromString("1223::3456:789A", expected)); + EXPECT_EQ(addr, expected); } -void PtrRecordSimpleParsing(nlTestSuite * inSuite, void * inContext) +TEST(TestRecordData, PtrRecordSimpleParsing) { const uint8_t record[] = { 4, 's', 'o', 'm', 'e', // QNAME part: some @@ -159,17 +157,17 @@ void PtrRecordSimpleParsing(nlTestSuite * inSuite, void * inContext) SerializedQNameIterator name; - NL_TEST_ASSERT(inSuite, ParsePtrRecord(data, packet, &name)); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "some") == 0); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "test") == 0); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "local") == 0); - NL_TEST_ASSERT(inSuite, name.Next() == false); + EXPECT_TRUE(ParsePtrRecord(data, packet, &name)); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "some"); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "test"); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "local"); + EXPECT_EQ(name.Next(), false); } -void PtrRecordComplexParsing(nlTestSuite * inSuite, void * inContext) +TEST(TestRecordData, PtrRecordComplexParsing) { const uint8_t record[] = { 'x', 'y', 'z', // dummy data (3 bytes) @@ -187,18 +185,18 @@ void PtrRecordComplexParsing(nlTestSuite * inSuite, void * inContext) BytesRange data(record + 24, record + sizeof(record)); SerializedQNameIterator name; - NL_TEST_ASSERT(inSuite, ParsePtrRecord(data, packet, &name)); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "foo") == 0); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "bar") == 0); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "baz") == 0); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "some") == 0); - NL_TEST_ASSERT(inSuite, name.Next()); - NL_TEST_ASSERT(inSuite, strcmp(name.Value(), "test") == 0); - NL_TEST_ASSERT(inSuite, name.Next() == false); + EXPECT_TRUE(ParsePtrRecord(data, packet, &name)); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "foo"); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "bar"); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "baz"); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "some"); + EXPECT_TRUE(name.Next()); + EXPECT_STREQ(name.Value(), "test"); + EXPECT_EQ(name.Next(), false); } class TxtRecordAccumulator : public TxtRecordDelegate @@ -223,7 +221,7 @@ class TxtRecordAccumulator : public TxtRecordDelegate } }; -void TxtRecord(nlTestSuite * inSuite, void * inContext) +TEST(TestRecordData, TxtRecord) { const uint8_t record[] = { 4, 's', 'o', 'm', 'e', // some @@ -234,32 +232,11 @@ void TxtRecord(nlTestSuite * inSuite, void * inContext) TxtRecordAccumulator accumulator; - NL_TEST_ASSERT(inSuite, ParseTxtRecord(BytesRange(record, record + sizeof(record)), &accumulator)); - NL_TEST_ASSERT(inSuite, accumulator.Data().size() == 4); - NL_TEST_ASSERT(inSuite, (accumulator.Data()[0] == make_pair("some", ""))); - NL_TEST_ASSERT(inSuite, (accumulator.Data()[1] == make_pair("foo", "bar"))); - NL_TEST_ASSERT(inSuite, (accumulator.Data()[2] == make_pair("x", "y=z"))); - NL_TEST_ASSERT(inSuite, (accumulator.Data()[3] == make_pair("a", ""))); + EXPECT_TRUE(ParseTxtRecord(BytesRange(record, record + sizeof(record)), &accumulator)); + EXPECT_EQ(accumulator.Data().size(), 4u); + EXPECT_EQ(accumulator.Data()[0], (make_pair("some", ""))); + EXPECT_EQ(accumulator.Data()[1], (make_pair("foo", "bar"))); + EXPECT_EQ(accumulator.Data()[2], (make_pair("x", "y=z"))); + EXPECT_EQ(accumulator.Data()[3], (make_pair("a", ""))); } - -const nlTest sTests[] = { - NL_TEST_DEF("SrvRecordSimpleParsing", SrvRecordSimpleParsing), // - NL_TEST_DEF("SrvWithPtrRecord", SrvWithPtrRecord), // - NL_TEST_DEF("ARecordParsing", ARecordParsing), // - NL_TEST_DEF("AAAARecordParsing", AAAARecordParsing), // - NL_TEST_DEF("PtrRecordSimpleParsing", PtrRecordSimpleParsing), // - NL_TEST_DEF("PtrRecordComplexParsing", PtrRecordComplexParsing), // - NL_TEST_DEF("TxtRecord", TxtRecord), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestRecordData() -{ - nlTestSuite theSuite = { "RecordData", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestRecordData) diff --git a/src/lib/dnssd/minimal_mdns/tests/TestResponseSender.cpp b/src/lib/dnssd/minimal_mdns/tests/TestResponseSender.cpp index 39316ae129bd36..80ae9dc1b2c55b 100644 --- a/src/lib/dnssd/minimal_mdns/tests/TestResponseSender.cpp +++ b/src/lib/dnssd/minimal_mdns/tests/TestResponseSender.cpp @@ -19,6 +19,8 @@ #include #include +#include + #include #include #include @@ -28,9 +30,6 @@ #include #include -#include - -#include namespace { @@ -72,24 +71,31 @@ struct CommonTestElements QueryResponder<10> queryResponder; Inet::IPPacketInfo packetInfo; - CommonTestElements(nlTestSuite * inSuite, const char * tag) : + CommonTestElements(const char * tag) : recordWriter(&requestBufferWriter), dnsSd(FlatAllocatedQName::Build(dnsSdServiceStorage, "_services", "_dns-sd", "_udp", "local")), service(FlatAllocatedQName::Build(serviceNameStorage, tag, "service")), instance(FlatAllocatedQName::Build(instanceNameStorage, tag, "instance")), host(FlatAllocatedQName::Build(hostNameStorage, tag, "host")), - txt(FlatAllocatedQName::Build(txtStorage, tag, "L1=something", "L2=other")), server(inSuite) + txt(FlatAllocatedQName::Build(txtStorage, tag, "L1=something", "L2=other")), server() { queryResponder.Init(); header.SetQueryCount(1); } }; -void SrvAnyResponseToInstance(nlTestSuite * inSuite, void * inContext) +class TestResponseSender : public ::testing::Test +{ +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestResponseSender, SrvAnyResponseToInstance) { - CommonTestElements common(inSuite, "test"); + CommonTestElements common("test"); ResponseSender responseSender(&common.server); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&common.queryResponder) == CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&common.queryResponder), CHIP_NO_ERROR); common.queryResponder.AddResponder(&common.srvResponder); // Build a query for our srv record @@ -100,15 +106,15 @@ void SrvAnyResponseToInstance(nlTestSuite * inSuite, void * inContext) common.server.AddExpectedRecord(&common.srvRecord); responseSender.Respond(1, queryData, &common.packetInfo, ResponseConfiguration()); - NL_TEST_ASSERT(inSuite, common.server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, common.server.GetHeaderFound()); + EXPECT_TRUE(common.server.GetSendCalled()); + EXPECT_TRUE(common.server.GetHeaderFound()); } -void SrvTxtAnyResponseToInstance(nlTestSuite * inSuite, void * inContext) +TEST_F(TestResponseSender, SrvTxtAnyResponseToInstance) { - CommonTestElements common(inSuite, "test"); + CommonTestElements common("test"); ResponseSender responseSender(&common.server); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&common.queryResponder) == CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&common.queryResponder), CHIP_NO_ERROR); common.queryResponder.AddResponder(&common.srvResponder); common.queryResponder.AddResponder(&common.txtResponder); @@ -122,15 +128,15 @@ void SrvTxtAnyResponseToInstance(nlTestSuite * inSuite, void * inContext) common.server.AddExpectedRecord(&common.txtRecord); responseSender.Respond(1, queryData, &common.packetInfo, ResponseConfiguration()); - NL_TEST_ASSERT(inSuite, common.server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, common.server.GetHeaderFound()); + EXPECT_TRUE(common.server.GetSendCalled()); + EXPECT_TRUE(common.server.GetHeaderFound()); } -void PtrSrvTxtAnyResponseToServiceName(nlTestSuite * inSuite, void * inContext) +TEST_F(TestResponseSender, PtrSrvTxtAnyResponseToServiceName) { - CommonTestElements common(inSuite, "test"); + CommonTestElements common("test"); ResponseSender responseSender(&common.server); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&common.queryResponder) == CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&common.queryResponder), CHIP_NO_ERROR); common.queryResponder.AddResponder(&common.ptrResponder).SetReportAdditional(common.instance); common.queryResponder.AddResponder(&common.srvResponder); common.queryResponder.AddResponder(&common.txtResponder); @@ -147,15 +153,15 @@ void PtrSrvTxtAnyResponseToServiceName(nlTestSuite * inSuite, void * inContext) responseSender.Respond(1, queryData, &common.packetInfo, ResponseConfiguration()); - NL_TEST_ASSERT(inSuite, common.server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, common.server.GetHeaderFound()); + EXPECT_TRUE(common.server.GetSendCalled()); + EXPECT_TRUE(common.server.GetHeaderFound()); } -void PtrSrvTxtAnyResponseToInstance(nlTestSuite * inSuite, void * inContext) +TEST_F(TestResponseSender, PtrSrvTxtAnyResponseToInstance) { - CommonTestElements common(inSuite, "test"); + CommonTestElements common("test"); ResponseSender responseSender(&common.server); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&common.queryResponder) == CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&common.queryResponder), CHIP_NO_ERROR); common.queryResponder.AddResponder(&common.ptrResponder); common.queryResponder.AddResponder(&common.srvResponder); common.queryResponder.AddResponder(&common.txtResponder); @@ -171,15 +177,15 @@ void PtrSrvTxtAnyResponseToInstance(nlTestSuite * inSuite, void * inContext) responseSender.Respond(1, queryData, &common.packetInfo, ResponseConfiguration()); - NL_TEST_ASSERT(inSuite, common.server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, common.server.GetHeaderFound()); + EXPECT_TRUE(common.server.GetSendCalled()); + EXPECT_TRUE(common.server.GetHeaderFound()); } -void PtrSrvTxtSrvResponseToInstance(nlTestSuite * inSuite, void * inContext) +TEST_F(TestResponseSender, PtrSrvTxtSrvResponseToInstance) { - CommonTestElements common(inSuite, "test"); + CommonTestElements common("test"); ResponseSender responseSender(&common.server); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&common.queryResponder) == CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&common.queryResponder), CHIP_NO_ERROR); common.queryResponder.AddResponder(&common.ptrResponder).SetReportInServiceListing(true); common.queryResponder.AddResponder(&common.srvResponder); common.queryResponder.AddResponder(&common.txtResponder); @@ -194,15 +200,15 @@ void PtrSrvTxtSrvResponseToInstance(nlTestSuite * inSuite, void * inContext) responseSender.Respond(1, queryData, &common.packetInfo, ResponseConfiguration()); - NL_TEST_ASSERT(inSuite, common.server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, common.server.GetHeaderFound()); + EXPECT_TRUE(common.server.GetSendCalled()); + EXPECT_TRUE(common.server.GetHeaderFound()); } -void PtrSrvTxtAnyResponseToServiceListing(nlTestSuite * inSuite, void * inContext) +TEST_F(TestResponseSender, PtrSrvTxtAnyResponseToServiceListing) { - CommonTestElements common(inSuite, "test"); + CommonTestElements common("test"); ResponseSender responseSender(&common.server); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&common.queryResponder) == CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&common.queryResponder), CHIP_NO_ERROR); common.queryResponder.AddResponder(&common.ptrResponder).SetReportInServiceListing(true); common.queryResponder.AddResponder(&common.srvResponder); common.queryResponder.AddResponder(&common.txtResponder); @@ -218,31 +224,31 @@ void PtrSrvTxtAnyResponseToServiceListing(nlTestSuite * inSuite, void * inContex responseSender.Respond(1, queryData, &common.packetInfo, ResponseConfiguration()); - NL_TEST_ASSERT(inSuite, common.server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, common.server.GetHeaderFound()); + EXPECT_TRUE(common.server.GetSendCalled()); + EXPECT_TRUE(common.server.GetHeaderFound()); } -void NoQueryResponder(nlTestSuite * inSuite, void * inContext) +TEST_F(TestResponseSender, NoQueryResponder) { - CommonTestElements common(inSuite, "test"); + CommonTestElements common("test"); ResponseSender responseSender(&common.server); QueryData queryData = QueryData(QType::ANY, QClass::IN, false, common.requestNameStart, common.requestBytesRange); common.recordWriter.WriteQName(common.dnsSd); responseSender.Respond(1, queryData, &common.packetInfo, ResponseConfiguration()); - NL_TEST_ASSERT(inSuite, !common.server.GetSendCalled()); + EXPECT_FALSE(common.server.GetSendCalled()); common.recordWriter.WriteQName(common.service); responseSender.Respond(1, queryData, &common.packetInfo, ResponseConfiguration()); - NL_TEST_ASSERT(inSuite, !common.server.GetSendCalled()); + EXPECT_FALSE(common.server.GetSendCalled()); common.recordWriter.WriteQName(common.instance); responseSender.Respond(1, queryData, &common.packetInfo, ResponseConfiguration()); - NL_TEST_ASSERT(inSuite, !common.server.GetSendCalled()); + EXPECT_FALSE(common.server.GetSendCalled()); } -void AddManyQueryResponders(nlTestSuite * inSuite, void * inContext) +TEST_F(TestResponseSender, AddManyQueryResponders) { // TODO(cecille): Fix this test once #8000 gets resolved. ResponseSender responseSender(nullptr); @@ -259,39 +265,39 @@ void AddManyQueryResponders(nlTestSuite * inSuite, void * inContext) constexpr size_t kAddLoopSize = 1000; for (size_t i = 0; i < kAddLoopSize; ++i) { - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&q1) == CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&q1), CHIP_NO_ERROR); } // removing the only copy should clear out everything responseSender.RemoveQueryResponder(&q1); - NL_TEST_ASSERT(inSuite, !responseSender.HasQueryResponders()); + EXPECT_FALSE(responseSender.HasQueryResponders()); // At least 7 should be supported: // - 5 is the spec minimum // - 2 for commissionable and commisioner responders - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&q1) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&q2) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&q3) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&q4) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&q5) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&q6) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&q7) == CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&q1), CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&q2), CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&q3), CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&q4), CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&q5), CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&q6), CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&q7), CHIP_NO_ERROR); } -void PtrSrvTxtMultipleRespondersToInstance(nlTestSuite * inSuite, void * inContext) +TEST_F(TestResponseSender, PtrSrvTxtMultipleRespondersToInstance) { - CommonTestElements common1(inSuite, "test1"); - CommonTestElements common2(inSuite, "test2"); + CommonTestElements common1("test1"); + CommonTestElements common2("test2"); // Just use the server from common1. ResponseSender responseSender(&common1.server); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&common1.queryResponder) == CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&common1.queryResponder), CHIP_NO_ERROR); common1.queryResponder.AddResponder(&common1.ptrResponder).SetReportInServiceListing(true); common1.queryResponder.AddResponder(&common1.srvResponder); common1.queryResponder.AddResponder(&common1.txtResponder); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&common2.queryResponder) == CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&common2.queryResponder), CHIP_NO_ERROR); common2.queryResponder.AddResponder(&common2.ptrResponder).SetReportInServiceListing(true); common2.queryResponder.AddResponder(&common2.srvResponder); common2.queryResponder.AddResponder(&common2.txtResponder); @@ -306,23 +312,23 @@ void PtrSrvTxtMultipleRespondersToInstance(nlTestSuite * inSuite, void * inConte responseSender.Respond(1, queryData, &common1.packetInfo, ResponseConfiguration()); - NL_TEST_ASSERT(inSuite, common1.server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, common1.server.GetHeaderFound()); + EXPECT_TRUE(common1.server.GetSendCalled()); + EXPECT_TRUE(common1.server.GetHeaderFound()); } -void PtrSrvTxtMultipleRespondersToServiceListing(nlTestSuite * inSuite, void * inContext) +TEST_F(TestResponseSender, PtrSrvTxtMultipleRespondersToServiceListing) { - auto common1 = std::make_unique(inSuite, "test1"); - auto common2 = std::make_unique(inSuite, "test2"); + auto common1 = std::make_unique("test1"); + auto common2 = std::make_unique("test2"); // Just use the server from common1. ResponseSender responseSender(&common1->server); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&common1->queryResponder) == CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&common1->queryResponder), CHIP_NO_ERROR); common1->queryResponder.AddResponder(&common1->ptrResponder).SetReportInServiceListing(true); common1->queryResponder.AddResponder(&common1->srvResponder); common1->queryResponder.AddResponder(&common1->txtResponder); - NL_TEST_ASSERT(inSuite, responseSender.AddQueryResponder(&common2->queryResponder) == CHIP_NO_ERROR); + EXPECT_EQ(responseSender.AddQueryResponder(&common2->queryResponder), CHIP_NO_ERROR); common2->queryResponder.AddResponder(&common2->ptrResponder).SetReportInServiceListing(true); common2->queryResponder.AddResponder(&common2->srvResponder); common2->queryResponder.AddResponder(&common2->txtResponder); @@ -339,44 +345,9 @@ void PtrSrvTxtMultipleRespondersToServiceListing(nlTestSuite * inSuite, void * i responseSender.Respond(1, queryData, &common1->packetInfo, ResponseConfiguration()); - NL_TEST_ASSERT(inSuite, common1->server.GetSendCalled()); + EXPECT_TRUE(common1->server.GetSendCalled()); - NL_TEST_ASSERT(inSuite, common1->server.GetHeaderFound()); -} - -const nlTest sTests[] = { - NL_TEST_DEF("SrvAnyResponseToInstance", SrvAnyResponseToInstance), // - NL_TEST_DEF("SrvTxtAnyResponseToInstance", SrvTxtAnyResponseToInstance), // - NL_TEST_DEF("PtrSrvTxtAnyResponseToServiceName", PtrSrvTxtAnyResponseToServiceName), // - NL_TEST_DEF("PtrSrvTxtAnyResponseToInstance", PtrSrvTxtAnyResponseToInstance), // - NL_TEST_DEF("PtrSrvTxtSrvResponseToInstance", PtrSrvTxtSrvResponseToInstance), // - NL_TEST_DEF("PtrSrvTxtAnyResponseToServiceListing", PtrSrvTxtAnyResponseToServiceListing), // - NL_TEST_DEF("NoQueryResponder", NoQueryResponder), // - NL_TEST_DEF("AddManyQueryResponders", AddManyQueryResponders), // - NL_TEST_DEF("PtrSrvTxtMultipleRespondersToInstance", PtrSrvTxtMultipleRespondersToInstance), // - NL_TEST_DEF("PtrSrvTxtMultipleRespondersToServiceListing", PtrSrvTxtMultipleRespondersToServiceListing), // - - NL_TEST_SENTINEL() // -}; - -int TestSetup(void * inContext) -{ - return chip::Platform::MemoryInit() == CHIP_NO_ERROR ? SUCCESS : FAILURE; -} - -int TestTeardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; + EXPECT_TRUE(common1->server.GetHeaderFound()); } } // namespace - -int TestResponseSender() -{ - nlTestSuite theSuite = { "RecordData", sTests, &TestSetup, &TestTeardown }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestResponseSender) diff --git a/src/lib/dnssd/platform/tests/BUILD.gn b/src/lib/dnssd/platform/tests/BUILD.gn index 92b83195390f9c..966923eebae998 100644 --- a/src/lib/dnssd/platform/tests/BUILD.gn +++ b/src/lib/dnssd/platform/tests/BUILD.gn @@ -14,19 +14,14 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libMdnsFakePlatformTests" if (chip_device_platform == "fake") { test_sources = [ "TestPlatform.cpp" ] - public_deps = [ - "${chip_root}/src/lib/dnssd", - "${chip_root}/src/lib/support:testing_nlunit", - "${nlunit_test_root}:nlunit-test", - ] + public_deps = [ "${chip_root}/src/lib/dnssd" ] } } diff --git a/src/lib/dnssd/platform/tests/TestPlatform.cpp b/src/lib/dnssd/platform/tests/TestPlatform.cpp index 91a79f1efdc64a..ebdb46643847c6 100644 --- a/src/lib/dnssd/platform/tests/TestPlatform.cpp +++ b/src/lib/dnssd/platform/tests/TestPlatform.cpp @@ -18,12 +18,12 @@ #include #include -#include + #include #include #include -#include +#include #if CHIP_DEVICE_LAYER_TARGET_FAKE != 1 #error "This test is designed for use only with the fake platform" @@ -152,102 +152,87 @@ test::ExpectedCall commissionableLargeEnhanced = test::ExpectedCall() .AddSubtype("_V555") .AddSubtype("_T70000") .AddSubtype("_CM"); -void TestStub(nlTestSuite * inSuite, void * inContext) + +class TestDnssdPlatform : public ::testing::Test +{ +public: + static void SetUpTestSuite() + { + ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); + DiscoveryImplPlatform & mdnsPlatform = DiscoveryImplPlatform::GetInstance(); + EXPECT_EQ(mdnsPlatform.Init(DeviceLayer::UDPEndPointManager()), CHIP_NO_ERROR); + EXPECT_EQ(mdnsPlatform.RemoveServices(), CHIP_NO_ERROR); + } + + static void TearDownTestSuite() + { + DiscoveryImplPlatform::GetInstance().Shutdown(); + chip::Platform::MemoryShutdown(); + } + + void TearDown() override { test::Reset(); } +}; + +TEST_F(TestDnssdPlatform, TestStub) { // This is a test of the fake platform impl. We want // We want the platform to return unexpected event if it gets a start // without an expected event. ChipLogError(Discovery, "Test platform returns error correctly"); DiscoveryImplPlatform & mdnsPlatform = DiscoveryImplPlatform::GetInstance(); - NL_TEST_ASSERT(inSuite, mdnsPlatform.Init(DeviceLayer::UDPEndPointManager()) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsPlatform.RemoveServices() == CHIP_NO_ERROR); OperationalAdvertisingParameters params; - NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(params) == CHIP_ERROR_UNEXPECTED_EVENT); + EXPECT_EQ(mdnsPlatform.Advertise(params), CHIP_ERROR_UNEXPECTED_EVENT); } -void TestOperational(nlTestSuite * inSuite, void * inContext) +TEST_F(TestDnssdPlatform, TestOperational) { ChipLogError(Discovery, "Test operational"); - test::Reset(); DiscoveryImplPlatform & mdnsPlatform = DiscoveryImplPlatform::GetInstance(); - NL_TEST_ASSERT(inSuite, mdnsPlatform.Init(DeviceLayer::UDPEndPointManager()) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsPlatform.RemoveServices() == CHIP_NO_ERROR); operationalCall1.callType = test::CallType::kStart; - NL_TEST_ASSERT(inSuite, test::AddExpectedCall(operationalCall1) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(operationalParams1) == CHIP_NO_ERROR); + EXPECT_EQ(test::AddExpectedCall(operationalCall1), CHIP_NO_ERROR); + EXPECT_EQ(mdnsPlatform.Advertise(operationalParams1), CHIP_NO_ERROR); // Next call to advertise should call start again with just the new data. test::Reset(); operationalCall2.callType = test::CallType::kStart; - NL_TEST_ASSERT(inSuite, test::AddExpectedCall(operationalCall2) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(operationalParams2) == CHIP_NO_ERROR); + EXPECT_EQ(test::AddExpectedCall(operationalCall2), CHIP_NO_ERROR); + EXPECT_EQ(mdnsPlatform.Advertise(operationalParams2), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsPlatform.FinalizeServiceUpdate() == CHIP_NO_ERROR); + EXPECT_EQ(mdnsPlatform.FinalizeServiceUpdate(), CHIP_NO_ERROR); } -void TestCommissionableNode(nlTestSuite * inSuite, void * inContext) +TEST_F(TestDnssdPlatform, TestCommissionableNode) { ChipLogError(Discovery, "Test commissionable"); - test::Reset(); DiscoveryImplPlatform & mdnsPlatform = DiscoveryImplPlatform::GetInstance(); - NL_TEST_ASSERT(inSuite, mdnsPlatform.Init(DeviceLayer::UDPEndPointManager()) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsPlatform.RemoveServices() == CHIP_NO_ERROR); commissionableSmall.callType = test::CallType::kStart; - NL_TEST_ASSERT(inSuite, - mdnsPlatform.GetCommissionableInstanceName(commissionableSmall.instanceName, - sizeof(commissionableSmall.instanceName)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, test::AddExpectedCall(commissionableSmall) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(commissionableNodeParamsSmall) == CHIP_NO_ERROR); + EXPECT_EQ( + mdnsPlatform.GetCommissionableInstanceName(commissionableSmall.instanceName, sizeof(commissionableSmall.instanceName)), + CHIP_NO_ERROR); + EXPECT_EQ(test::AddExpectedCall(commissionableSmall), CHIP_NO_ERROR); + EXPECT_EQ(mdnsPlatform.Advertise(commissionableNodeParamsSmall), CHIP_NO_ERROR); // TODO: Right now, platform impl doesn't stop commissionable node before starting a new one. Add stop call here once that is // fixed. test::Reset(); commissionableLargeBasic.callType = test::CallType::kStart; - NL_TEST_ASSERT(inSuite, - mdnsPlatform.GetCommissionableInstanceName(commissionableLargeBasic.instanceName, - sizeof(commissionableLargeBasic.instanceName)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, test::AddExpectedCall(commissionableLargeBasic) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(commissionableNodeParamsLargeBasic) == CHIP_NO_ERROR); + EXPECT_EQ(mdnsPlatform.GetCommissionableInstanceName(commissionableLargeBasic.instanceName, + sizeof(commissionableLargeBasic.instanceName)), + CHIP_NO_ERROR); + EXPECT_EQ(test::AddExpectedCall(commissionableLargeBasic), CHIP_NO_ERROR); + EXPECT_EQ(mdnsPlatform.Advertise(commissionableNodeParamsLargeBasic), CHIP_NO_ERROR); test::Reset(); commissionableLargeEnhanced.callType = test::CallType::kStart; - NL_TEST_ASSERT(inSuite, - mdnsPlatform.GetCommissionableInstanceName(commissionableLargeEnhanced.instanceName, - sizeof(commissionableLargeEnhanced.instanceName)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, test::AddExpectedCall(commissionableLargeEnhanced) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(commissionableNodeParamsLargeEnhanced) == CHIP_NO_ERROR); + EXPECT_EQ(mdnsPlatform.GetCommissionableInstanceName(commissionableLargeEnhanced.instanceName, + sizeof(commissionableLargeEnhanced.instanceName)), + CHIP_NO_ERROR); + EXPECT_EQ(test::AddExpectedCall(commissionableLargeEnhanced), CHIP_NO_ERROR); + EXPECT_EQ(mdnsPlatform.Advertise(commissionableNodeParamsLargeEnhanced), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, mdnsPlatform.FinalizeServiceUpdate() == CHIP_NO_ERROR); -} - -int TestSetup(void * inContext) -{ - return chip::Platform::MemoryInit() == CHIP_NO_ERROR ? SUCCESS : FAILURE; + EXPECT_EQ(mdnsPlatform.FinalizeServiceUpdate(), CHIP_NO_ERROR); } -int TestTeardown(void * inContext) -{ - DiscoveryImplPlatform::GetInstance().Shutdown(); - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -const nlTest sTests[] = { - NL_TEST_DEF("TestStub", TestStub), // - NL_TEST_DEF("TestOperational", TestOperational), // - NL_TEST_DEF("TestCommissionableNode", TestCommissionableNode), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestDnssdPlatform() -{ - nlTestSuite theSuite = { "DnssdPlatform", &sTests[0], &TestSetup, &TestTeardown }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestDnssdPlatform) diff --git a/src/lib/dnssd/tests/TestTxtFields.cpp b/src/lib/dnssd/tests/TestTxtFields.cpp index 4593a4903b1a01..d6e7e6ea240670 100644 --- a/src/lib/dnssd/tests/TestTxtFields.cpp +++ b/src/lib/dnssd/tests/TestTxtFields.cpp @@ -309,7 +309,7 @@ bool NodeDataIsEmpty(const DiscoveredNodeData & node) node.nodeData.pairingHint != 0 || node.resolutionData.mrpRetryIntervalIdle.HasValue() || node.resolutionData.mrpRetryIntervalActive.HasValue() || node.resolutionData.mrpRetryActiveThreshold.HasValue() || node.resolutionData.isICDOperatingAsLIT.HasValue() || node.resolutionData.supportsTcp || - node.nodeData.commissionerPasscode != 0) + node.nodeData.supportsCommissionerGeneratedPasscode != 0) { return false; } @@ -360,12 +360,12 @@ void TestFillDiscoveredNodeDataFromTxt(nlTestSuite * inSuite, void * inContext) filled.nodeData.commissioningMode = 0; NL_TEST_ASSERT(inSuite, NodeDataIsEmpty(filled)); - // Commissioning mode + // Supports Commissioner Generated Passcode strcpy(key, "CP"); strcpy(val, "1"); FillNodeDataFromTxt(GetSpan(key), GetSpan(val), filled.nodeData); - NL_TEST_ASSERT(inSuite, filled.nodeData.commissionerPasscode == 1); - filled.nodeData.commissionerPasscode = 0; + NL_TEST_ASSERT(inSuite, filled.nodeData.supportsCommissionerGeneratedPasscode == true); + filled.nodeData.supportsCommissionerGeneratedPasscode = false; NL_TEST_ASSERT(inSuite, NodeDataIsEmpty(filled)); // Device type diff --git a/src/lib/format/tests/BUILD.gn b/src/lib/format/tests/BUILD.gn index 64be2e38a3f402..1001a3bd9e77d4 100644 --- a/src/lib/format/tests/BUILD.gn +++ b/src/lib/format/tests/BUILD.gn @@ -14,12 +14,11 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") import("${chip_root}/build/chip/fuzz_test.gni") -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libFormatTests" test_sources = [ @@ -40,8 +39,6 @@ chip_test_suite_using_nltest("tests") { "${chip_root}/src/lib/format:flat-tree", "${chip_root}/src/lib/format:protocol-decoder", "${chip_root}/src/lib/format:protocol-tlv-metadata", - "${chip_root}/src/lib/support:testing_nlunit", - "${nlunit_test_root}:nlunit-test", ] } diff --git a/src/lib/format/tests/TestDecoding.cpp b/src/lib/format/tests/TestDecoding.cpp index 0a848e5de8f835..ae5c2efc553fb6 100644 --- a/src/lib/format/tests/TestDecoding.cpp +++ b/src/lib/format/tests/TestDecoding.cpp @@ -17,12 +17,11 @@ #include #include #include -#include #include #include -#include +#include #include "sample_data.h" @@ -57,8 +56,7 @@ const std::array, 53 + 2> fake_protocols_meta = { { { 2, _FakeProtocolData }, } }; -void TestSampleData(nlTestSuite * inSuite, const PayloadDecoderInitParams & params, const SamplePayload & data, - const char * expectation) +void TestSampleData(const PayloadDecoderInitParams & params, const SamplePayload & data, const char * expectation) { chip::Decoders::PayloadDecoder<64, 128> decoder( PayloadDecoderInitParams(params).SetProtocol(data.protocolId).SetMessageType(data.messageType)); @@ -130,23 +128,23 @@ void TestSampleData(nlTestSuite * inSuite, const PayloadDecoderInitParams & para printf("ACTUAL: '%s'\n", partial.Reset().Add(output_builder.c_str() + idx).AddMarkerIfOverflow().c_str()); } - NL_TEST_ASSERT(inSuite, strcmp(output_builder.c_str(), expectation) == 0); + EXPECT_STREQ(output_builder.c_str(), expectation); } -void TestFullDataDecoding(nlTestSuite * inSuite, void * inContext) +TEST(TestDecoding, TestFullDataDecoding) { PayloadDecoderInitParams params; params.SetProtocolDecodeTree(chip::TLVMeta::protocols_meta).SetClusterDecodeTree(chip::TLVMeta::clusters_meta); - TestSampleData(inSuite, params, secure_channel_mrp_ack, "mrp_ack: EMPTY\n"); - TestSampleData(inSuite, params, secure_channel_pkbdf_param_request, + TestSampleData(params, secure_channel_mrp_ack, "mrp_ack: EMPTY\n"); + TestSampleData(params, secure_channel_pkbdf_param_request, "pbkdf_param_request\n" " initiator_random: hex:7C8698755B8E9866BB4FFDC27B733F3B6EF7F83D43FBE0CA6AD2B8C52C8F4236\n" " initiator_session_id: 37677\n" " passcode_id: 0\n" " has_pbkdf_parameters: false\n"); - TestSampleData(inSuite, params, secure_channel_pkbdf_param_response, + TestSampleData(params, secure_channel_pkbdf_param_response, "pbkdf_param_response\n" " initiator_random: hex:7C8698755B8E9866BB4FFDC27B733F3B6EF7F83D43FBE0CA6AD2B8C52C8F4236\n" " responder_random: hex:A44EB3E1A751A88A32BAB59EF16EB9764C20E1A9DDBEF6EFE3F588C943C58424\n" @@ -154,24 +152,24 @@ void TestFullDataDecoding(nlTestSuite * inSuite, void * inContext) " pbkdf_parameters\n" " iterations: 1000\n" " salt: hex:E8FC1E6FD0023422B3CA7ECEDD344444551C814D3D0B0EB9C096F00E8A8051B2\n"); - TestSampleData(inSuite, params, secure_channel_pase_pake1, + TestSampleData(params, secure_channel_pase_pake1, // clang-format off "pase_pake1\n" " pA: hex:0422ABC7A84352850456BD4A510905FE6BB782A0863A9382550E1228020801B22EEC4102C60F80082842B9739705FCD37F134651442A41E3723DFFE0...\n" // clang-format on ); - TestSampleData(inSuite, params, secure_channel_pase_pake2, + TestSampleData(params, secure_channel_pase_pake2, // clang-format off "pase_pake2\n" " pB: hex:04B6A44A3347C6B77900A3674CA19F40F25F056F8CB344EC1B4FA7888B9E6B570B7010431C5D0BE4021FE74A96C40721765FDA6802BE8DFDF5624332...\n" " cB: hex:40E7452275E38AEBAF0E0F6FAB33A1B0CB5AEB5E824230DD40D0071DC7E55C87\n" // clang-format on ); - TestSampleData(inSuite, params, secure_channel_pase_pake3, + TestSampleData(params, secure_channel_pase_pake3, "pase_pake3\n" " cA: hex:6008C72EDEC9D25D4A36522F0BF23058F9378EFE38CBBCCE8C6853900169BC38\n"); - TestSampleData(inSuite, params, secure_channel_status_report, "status_report: BINARY DATA\n"); - TestSampleData(inSuite, params, im_protocol_read_request, + TestSampleData(params, secure_channel_status_report, "status_report: BINARY DATA\n"); + TestSampleData(params, im_protocol_read_request, "read_request\n" " attribute_requests\n" " Anonymous<>\n" @@ -206,7 +204,7 @@ void TestFullDataDecoding(nlTestSuite * inSuite, void * inContext) " attribute_id: 3 == 'connectMaxTimeSeconds'\n" " fabric_filtered: false\n" " interaction_model_revison: 1\n"); - TestSampleData(inSuite, params, im_protocol_report_data, + TestSampleData(params, im_protocol_report_data, "report_data\n" " attribute_reports\n" " Anonymous<>\n" @@ -279,7 +277,7 @@ void TestFullDataDecoding(nlTestSuite * inSuite, void * inContext) " interaction_model_revison: 1\n"); // Different content - TestSampleData(inSuite, params, im_protocol_report_data_acl, + TestSampleData(params, im_protocol_report_data_acl, "report_data\n" " attribute_reports\n" " Anonymous<>\n" @@ -301,7 +299,7 @@ void TestFullDataDecoding(nlTestSuite * inSuite, void * inContext) " interaction_model_revison: 1\n"); TestSampleData( - inSuite, params, im_protocol_report_data_window_covering, + params, im_protocol_report_data_window_covering, "report_data\n" " attribute_reports\n" " Anonymous<>\n" @@ -315,7 +313,7 @@ void TestFullDataDecoding(nlTestSuite * inSuite, void * inContext) " suppress_response: true\n" " interaction_model_revison: 1\n"); - TestSampleData(inSuite, params, im_protocol_invoke_request, + TestSampleData(params, im_protocol_invoke_request, "invoke_request\n" " suppress_response: false\n" " timed_request: false\n" @@ -328,7 +326,7 @@ void TestFullDataDecoding(nlTestSuite * inSuite, void * inContext) " OnOff::Toggle\n" " interaction_model_revison: 1\n"); - TestSampleData(inSuite, params, im_protocol_invoke_response, + TestSampleData(params, im_protocol_invoke_response, "invoke_response\n" " suppress_response: false\n" " invoke_responses\n" @@ -342,7 +340,7 @@ void TestFullDataDecoding(nlTestSuite * inSuite, void * inContext) " status: 0 == kSuccess\n" " interaction_model_revison: 1\n"); - TestSampleData(inSuite, params, im_protocol_invoke_request_change_channel, + TestSampleData(params, im_protocol_invoke_request_change_channel, "invoke_request\n" " suppress_response: false\n" " timed_request: false\n" @@ -356,7 +354,7 @@ void TestFullDataDecoding(nlTestSuite * inSuite, void * inContext) " match: \"channel name\"\n" " interaction_model_revison: 1\n"); - TestSampleData(inSuite, params, im_protocol_event_software_fault, + TestSampleData(params, im_protocol_event_software_fault, "report_data\n" " event_reports\n" " Anonymous<>\n" @@ -375,7 +373,7 @@ void TestFullDataDecoding(nlTestSuite * inSuite, void * inContext) " suppress_response: true\n" " interaction_model_revison: 1\n"); - TestSampleData(inSuite, params, im_protocol_event_multipress, + TestSampleData(params, im_protocol_event_multipress, "report_data\n" " event_reports\n" " Anonymous<>\n" @@ -394,22 +392,22 @@ void TestFullDataDecoding(nlTestSuite * inSuite, void * inContext) " interaction_model_revison: 1\n"); } -void TestMetaDataOnlyDecoding(nlTestSuite * inSuite, void * inContext) +TEST(TestDecoding, TestMetaDataOnlyDecoding) { PayloadDecoderInitParams params; // NO CLUSTER DECODE TREE params.SetProtocolDecodeTree(chip::TLVMeta::protocols_meta); - TestSampleData(inSuite, params, secure_channel_mrp_ack, "mrp_ack: EMPTY\n"); - TestSampleData(inSuite, params, secure_channel_pkbdf_param_request, + TestSampleData(params, secure_channel_mrp_ack, "mrp_ack: EMPTY\n"); + TestSampleData(params, secure_channel_pkbdf_param_request, "pbkdf_param_request\n" " initiator_random: hex:7C8698755B8E9866BB4FFDC27B733F3B6EF7F83D43FBE0CA6AD2B8C52C8F4236\n" " initiator_session_id: 37677\n" " passcode_id: 0\n" " has_pbkdf_parameters: false\n"); - TestSampleData(inSuite, params, im_protocol_read_request, + TestSampleData(params, im_protocol_read_request, "read_request\n" " attribute_requests\n" " Anonymous<>\n" @@ -444,7 +442,7 @@ void TestMetaDataOnlyDecoding(nlTestSuite * inSuite, void * inContext) " attribute_id: 3\n" " fabric_filtered: false\n" " interaction_model_revison: 1\n"); - TestSampleData(inSuite, params, im_protocol_report_data, + TestSampleData(params, im_protocol_report_data, "report_data\n" " attribute_reports\n" " Anonymous<>\n" @@ -515,7 +513,7 @@ void TestMetaDataOnlyDecoding(nlTestSuite * inSuite, void * inContext) " interaction_model_revison: 1\n"); // Different content - TestSampleData(inSuite, params, im_protocol_report_data_acl, + TestSampleData(params, im_protocol_report_data_acl, "report_data\n" " attribute_reports\n" " Anonymous<>\n" @@ -530,14 +528,14 @@ void TestMetaDataOnlyDecoding(nlTestSuite * inSuite, void * inContext) " interaction_model_revison: 1\n"); } -void TestEmptyClusterMetaDataDecode(nlTestSuite * inSuite, void * inContext) +TEST(TestDecoding, TestEmptyClusterMetaDataDecode) { PayloadDecoderInitParams params; params.SetProtocolDecodeTree(chip::TLVMeta::protocols_meta).SetClusterDecodeTree(empty_meta); - TestSampleData(inSuite, params, secure_channel_mrp_ack, "mrp_ack: EMPTY\n"); - TestSampleData(inSuite, params, im_protocol_report_data_acl, + TestSampleData(params, secure_channel_mrp_ack, "mrp_ack: EMPTY\n"); + TestSampleData(params, im_protocol_report_data_acl, "report_data\n" " attribute_reports\n" " Anonymous<>\n" @@ -559,24 +557,24 @@ void TestEmptyClusterMetaDataDecode(nlTestSuite * inSuite, void * inContext) " interaction_model_revison: 1\n"); } -void TestMissingDecodeData(nlTestSuite * inSuite, void * inContext) +TEST(TestDecoding, TestMissingDecodeData) { PayloadDecoderInitParams params; params.SetProtocolDecodeTree(empty_meta).SetClusterDecodeTree(empty_meta); - TestSampleData(inSuite, params, secure_channel_mrp_ack, "PROTO(0x0, 0x10): UNKNOWN\n"); - TestSampleData(inSuite, params, im_protocol_report_data_acl, "PROTO(0x1, 0x5): UNKNOWN\n"); + TestSampleData(params, secure_channel_mrp_ack, "PROTO(0x0, 0x10): UNKNOWN\n"); + TestSampleData(params, im_protocol_report_data_acl, "PROTO(0x1, 0x5): UNKNOWN\n"); } -void TestWrongDecodeData(nlTestSuite * inSuite, void * inContext) +TEST(TestDecoding, TestWrongDecodeData) { PayloadDecoderInitParams params; params.SetProtocolDecodeTree(fake_protocols_meta).SetClusterDecodeTree(empty_meta); - TestSampleData(inSuite, params, secure_channel_mrp_ack, "proto16: EMPTY\n"); - TestSampleData(inSuite, params, im_protocol_report_data_acl, + TestSampleData(params, secure_channel_mrp_ack, "proto16: EMPTY\n"); + TestSampleData(params, im_protocol_report_data_acl, "proto5\n" " ContextTag(0x1)\n" " AnonymousTag()\n" @@ -598,7 +596,7 @@ void TestWrongDecodeData(nlTestSuite * inSuite, void * inContext) " ContextTag(0xFF): 1\n"); } -void TestNestingOverflow(nlTestSuite * inSuite, void * inContext) +TEST(TestDecoding, TestNestingOverflow) { PayloadDecoderInitParams params; params.SetProtocolDecodeTree(fake_protocols_meta).SetClusterDecodeTree(empty_meta); @@ -611,65 +609,62 @@ void TestNestingOverflow(nlTestSuite * inSuite, void * inContext) chip::TLV::TLVType unusedType; // Protocols start with an anonymous tagged structure, after which lists can be of any tags - NL_TEST_ASSERT(inSuite, writer.StartContainer(AnonymousTag(), kTLVType_Structure, unusedType) == CHIP_NO_ERROR); + EXPECT_EQ(writer.StartContainer(AnonymousTag(), kTLVType_Structure, unusedType), CHIP_NO_ERROR); // nesting overflow here for (uint8_t i = 0; i < 32; i++) { - NL_TEST_ASSERT(inSuite, writer.StartContainer(ContextTag(i), kTLVType_List, unusedType) == CHIP_NO_ERROR); + EXPECT_EQ(writer.StartContainer(ContextTag(i), kTLVType_List, unusedType), CHIP_NO_ERROR); } // Go back to 24 (still too much nesting) for (uint8_t i = 0; i < 8; i++) { - NL_TEST_ASSERT(inSuite, writer.EndContainer(kTLVType_List) == CHIP_NO_ERROR); + EXPECT_EQ(writer.EndContainer(kTLVType_List), CHIP_NO_ERROR); } for (uint8_t i = 0; i < 4; i++) { - NL_TEST_ASSERT( - inSuite, writer.StartContainer(ContextTag(static_cast(i + 0x10)), kTLVType_List, unusedType) == CHIP_NO_ERROR); + EXPECT_EQ(writer.StartContainer(ContextTag(static_cast(i + 0x10)), kTLVType_List, unusedType), CHIP_NO_ERROR); } for (uint8_t i = 0; i < 4; i++) { - NL_TEST_ASSERT(inSuite, writer.EndContainer(kTLVType_List) == CHIP_NO_ERROR); + EXPECT_EQ(writer.EndContainer(kTLVType_List), CHIP_NO_ERROR); } // Go back to 8 for (uint8_t i = 0; i < 16; i++) { - NL_TEST_ASSERT(inSuite, writer.EndContainer(kTLVType_List) == CHIP_NO_ERROR); + EXPECT_EQ(writer.EndContainer(kTLVType_List), CHIP_NO_ERROR); } for (uint8_t i = 0; i < 4; i++) { - NL_TEST_ASSERT( - inSuite, writer.StartContainer(ContextTag(static_cast(i + 0x20)), kTLVType_List, unusedType) == CHIP_NO_ERROR); + EXPECT_EQ(writer.StartContainer(ContextTag(static_cast(i + 0x20)), kTLVType_List, unusedType), CHIP_NO_ERROR); } for (uint8_t i = 0; i < 4; i++) { - NL_TEST_ASSERT(inSuite, writer.EndContainer(kTLVType_List) == CHIP_NO_ERROR); + EXPECT_EQ(writer.EndContainer(kTLVType_List), CHIP_NO_ERROR); } // Go back to 4 for (uint8_t i = 0; i < 4; i++) { - NL_TEST_ASSERT(inSuite, writer.EndContainer(kTLVType_List) == CHIP_NO_ERROR); + EXPECT_EQ(writer.EndContainer(kTLVType_List), CHIP_NO_ERROR); } for (uint8_t i = 0; i < 4; i++) { - NL_TEST_ASSERT( - inSuite, writer.StartContainer(ContextTag(static_cast(i + 0x30)), kTLVType_List, unusedType) == CHIP_NO_ERROR); + EXPECT_EQ(writer.StartContainer(ContextTag(static_cast(i + 0x30)), kTLVType_List, unusedType), CHIP_NO_ERROR); } for (uint8_t i = 0; i < 4; i++) { - NL_TEST_ASSERT(inSuite, writer.EndContainer(kTLVType_List) == CHIP_NO_ERROR); + EXPECT_EQ(writer.EndContainer(kTLVType_List), CHIP_NO_ERROR); } // close everything for (uint8_t i = 0; i < 4; i++) { - NL_TEST_ASSERT(inSuite, writer.EndContainer(kTLVType_List) == CHIP_NO_ERROR); + EXPECT_EQ(writer.EndContainer(kTLVType_List), CHIP_NO_ERROR); } - NL_TEST_ASSERT(inSuite, writer.EndContainer(kTLVType_Structure) == CHIP_NO_ERROR); + EXPECT_EQ(writer.EndContainer(kTLVType_Structure), CHIP_NO_ERROR); SamplePayload fake_payload{ chip::Protocols::InteractionModel::Id, 5, chip::ByteSpan(data_buffer, writer.GetLengthWritten()) }; - TestSampleData(inSuite, params, fake_payload, + TestSampleData(params, fake_payload, "proto5\n" " ContextTag(0x0)\n" " ContextTag(0x1)\n" @@ -696,24 +691,4 @@ void TestNestingOverflow(nlTestSuite * inSuite, void * inContext) " ContextTag(0x32)\n" " ContextTag(0x33)\n"); } - -const nlTest sTests[] = { - NL_TEST_DEF("TestFullDataDecoding", TestFullDataDecoding), // - NL_TEST_DEF("TestMetaDataOnlyDecoding", TestMetaDataOnlyDecoding), // - NL_TEST_DEF("TestEmptyClusterMetaDataDecode", TestEmptyClusterMetaDataDecode), // - NL_TEST_DEF("TestMissingDecodeData", TestMissingDecodeData), // - NL_TEST_DEF("TestWrongDecodeData", TestWrongDecodeData), // - NL_TEST_DEF("TestNestingOverflow", TestNestingOverflow), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestDecode() -{ - nlTestSuite theSuite = { "TestDecode", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestDecode) diff --git a/src/lib/format/tests/TestFlatTree.cpp b/src/lib/format/tests/TestFlatTree.cpp index 8eebb984b6adb9..fcf8e2713bf6b5 100644 --- a/src/lib/format/tests/TestFlatTree.cpp +++ b/src/lib/format/tests/TestFlatTree.cpp @@ -17,13 +17,12 @@ #include #include -#include #include #include -#include +#include namespace { @@ -82,43 +81,28 @@ class ByName const char * mName; }; -void TestFlatTreeFind(nlTestSuite * inSuite, void * inContext) +TEST(TestFlatTree, TestFlatTreeFind) { - NL_TEST_ASSERT(inSuite, strcmp(FindEntry(tree, 0, ByTag(ContextTag(1)))->data.name, "hello") == 0); - NL_TEST_ASSERT(inSuite, strcmp(FindEntry(tree, 0, ByTag(ContextTag(2)))->data.name, "world") == 0); - NL_TEST_ASSERT(inSuite, FindEntry(tree, 0, ByTag(ContextTag(3))) == nullptr); + EXPECT_STREQ(FindEntry(tree, 0, ByTag(ContextTag(1)))->data.name, "hello"); + EXPECT_STREQ(FindEntry(tree, 0, ByTag(ContextTag(2)))->data.name, "world"); + EXPECT_EQ(FindEntry(tree, 0, ByTag(ContextTag(3))), nullptr); - NL_TEST_ASSERT(inSuite, FindEntry(tree, 0, ByName("hello"))->data.tag == ContextTag(1)); - NL_TEST_ASSERT(inSuite, FindEntry(tree, 0, ByName("world"))->data.tag == ContextTag(2)); - NL_TEST_ASSERT(inSuite, FindEntry(tree, 0, ByName("foo")) == nullptr); + EXPECT_EQ(FindEntry(tree, 0, ByName("hello"))->data.tag, ContextTag(1)); + EXPECT_EQ(FindEntry(tree, 0, ByName("world"))->data.tag, ContextTag(2)); + EXPECT_EQ(FindEntry(tree, 0, ByName("foo")), nullptr); - NL_TEST_ASSERT(inSuite, FindEntry(tree, 1, ByTag(ContextTag(1))) == nullptr); - NL_TEST_ASSERT(inSuite, strcmp(FindEntry(tree, 1, ByTag(ProfileTag(234, 2)))->data.name, "b") == 0); - NL_TEST_ASSERT(inSuite, strcmp(FindEntry(tree, 1, ByTag(ProfileTag(345, 3)))->data.name, "c") == 0); - NL_TEST_ASSERT(inSuite, FindEntry(tree, 1, ByTag(AnonymousTag())) == nullptr); + EXPECT_EQ(FindEntry(tree, 1, ByTag(ContextTag(1))), nullptr); + EXPECT_STREQ(FindEntry(tree, 1, ByTag(ProfileTag(234, 2)))->data.name, "b"); + EXPECT_STREQ(FindEntry(tree, 1, ByTag(ProfileTag(345, 3)))->data.name, "c"); + EXPECT_EQ(FindEntry(tree, 1, ByTag(AnonymousTag())), nullptr); - NL_TEST_ASSERT(inSuite, FindEntry(tree, 2, ByTag(ContextTag(1))) == nullptr); - NL_TEST_ASSERT(inSuite, strcmp(FindEntry(tree, 2, ByTag(AnonymousTag()))->data.name, "foo") == 0); + EXPECT_EQ(FindEntry(tree, 2, ByTag(ContextTag(1))), nullptr); + EXPECT_STREQ(FindEntry(tree, 2, ByTag(AnonymousTag()))->data.name, "foo"); // out of array - NL_TEST_ASSERT(inSuite, FindEntry(tree, 3, ByTag(AnonymousTag())) == nullptr); - NL_TEST_ASSERT(inSuite, FindEntry(tree, 100, ByTag(AnonymousTag())) == nullptr); - NL_TEST_ASSERT(inSuite, FindEntry(tree, 1000, ByTag(AnonymousTag())) == nullptr); - NL_TEST_ASSERT(inSuite, FindEntry(tree, 9999999, ByTag(AnonymousTag())) == nullptr); + EXPECT_EQ(FindEntry(tree, 3, ByTag(AnonymousTag())), nullptr); + EXPECT_EQ(FindEntry(tree, 100, ByTag(AnonymousTag())), nullptr); + EXPECT_EQ(FindEntry(tree, 1000, ByTag(AnonymousTag())), nullptr); + EXPECT_EQ(FindEntry(tree, 9999999, ByTag(AnonymousTag())), nullptr); } - -const nlTest sTests[] = { - NL_TEST_DEF("TestFlatTreeFind", TestFlatTreeFind), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestFlatTree() -{ - nlTestSuite theSuite = { "FlatTree", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestFlatTree) diff --git a/src/lib/format/tests/TestFlatTreePosition.cpp b/src/lib/format/tests/TestFlatTreePosition.cpp index ee5f6b3c94176d..cf5a26e6c8662f 100644 --- a/src/lib/format/tests/TestFlatTreePosition.cpp +++ b/src/lib/format/tests/TestFlatTreePosition.cpp @@ -18,14 +18,13 @@ #include #include -#include #include #include #include -#include +#include namespace { @@ -94,16 +93,16 @@ class ByName }; #define ASSERT_HAS_NAME(p, n) \ - NL_TEST_ASSERT(inSuite, p.Get() != nullptr); \ - NL_TEST_ASSERT(inSuite, strcmp(p.Get()->name, n) == 0) + EXPECT_NE(p.Get(), nullptr); \ + EXPECT_STREQ(p.Get()->name, n); #define ASSERT_HAS_CONTEXT_TAG(p, t) \ - NL_TEST_ASSERT(inSuite, p.Get() != nullptr); \ - NL_TEST_ASSERT(inSuite, p.Get()->tag == ContextTag(t)) + EXPECT_NE(p.Get(), nullptr); \ + EXPECT_EQ(p.Get()->tag, ContextTag(t)) #define ASSERT_HAS_PROFILE_TAG(p, a, b) \ - NL_TEST_ASSERT(inSuite, p.Get() != nullptr); \ - NL_TEST_ASSERT(inSuite, p.Get()->tag == ProfileTag(a, b)) + EXPECT_NE(p.Get(), nullptr); \ + EXPECT_EQ(p.Get()->tag, ProfileTag(a, b)) template std::vector GetPath(Position & position) @@ -133,54 +132,54 @@ bool HasPath(const std::vector & v, Tag a, Tag b, Tag c) return (v.size() == 3) && (v[0] == a) && (v[1] == b) && (v[2] == c); } -void TestSimpleEnterExit(nlTestSuite * inSuite, void * inContext) +TEST(TestFlatTreePosition, TestSimpleEnterExit) { Position position(tree.data(), tree.size()); // at start, top of tree has no value - NL_TEST_ASSERT(inSuite, position.Get() == nullptr); - NL_TEST_ASSERT(inSuite, GetPath(position).empty()); + EXPECT_EQ(position.Get(), nullptr); + EXPECT_TRUE(GetPath(position).empty()); // Go to hello, try going to invalid 2x, then go back position.Enter(ByTag(ContextTag(1))); ASSERT_HAS_NAME(position, "hello"); - NL_TEST_ASSERT(inSuite, HasPath(GetPath(position), ContextTag(1))); + EXPECT_TRUE(HasPath(GetPath(position), ContextTag(1))); position.Enter(ByTag(ContextTag(1))); - NL_TEST_ASSERT(inSuite, position.Get() == nullptr); - NL_TEST_ASSERT(inSuite, GetPath(position).empty()); + EXPECT_EQ(position.Get(), nullptr); + EXPECT_TRUE(GetPath(position).empty()); position.Enter(ByTag(ContextTag(1))); - NL_TEST_ASSERT(inSuite, position.Get() == nullptr); + EXPECT_EQ(position.Get(), nullptr); position.Exit(); - NL_TEST_ASSERT(inSuite, position.Get() == nullptr); + EXPECT_EQ(position.Get(), nullptr); position.Exit(); - NL_TEST_ASSERT(inSuite, position.Get() != nullptr); + ASSERT_NE(position.Get(), nullptr); ASSERT_HAS_NAME(position, "hello"); - NL_TEST_ASSERT(inSuite, HasPath(GetPath(position), ContextTag(1))); + EXPECT_TRUE(HasPath(GetPath(position), ContextTag(1))); position.Exit(); - NL_TEST_ASSERT(inSuite, position.Get() == nullptr); + EXPECT_EQ(position.Get(), nullptr); } -void TestDeeperEnter(nlTestSuite * inSuite, void * inContext) +TEST(TestFlatTreePosition, TestDeeperEnter) { Position position(tree.data(), tree.size()); - NL_TEST_ASSERT(inSuite, position.Get() == nullptr); + EXPECT_EQ(position.Get(), nullptr); position.Enter(ByName("world")); ASSERT_HAS_CONTEXT_TAG(position, 2); - NL_TEST_ASSERT(inSuite, HasPath(GetPath(position), ContextTag(2))); + EXPECT_TRUE(HasPath(GetPath(position), ContextTag(2))); position.Enter(ByTag(ProfileTag(123, 1))); ASSERT_HAS_NAME(position, "a"); - NL_TEST_ASSERT(inSuite, HasPath(GetPath(position), ContextTag(2), ProfileTag(123, 1))); + EXPECT_TRUE(HasPath(GetPath(position), ContextTag(2), ProfileTag(123, 1))); position.Enter(ByTag(AnonymousTag())); - NL_TEST_ASSERT(inSuite, position.Get() == nullptr); - NL_TEST_ASSERT(inSuite, GetPath(position).empty()); + EXPECT_EQ(position.Get(), nullptr); + EXPECT_TRUE(GetPath(position).empty()); position.Exit(); ASSERT_HAS_NAME(position, "a"); - NL_TEST_ASSERT(inSuite, HasPath(GetPath(position), ContextTag(2), ProfileTag(123, 1))); + EXPECT_TRUE(HasPath(GetPath(position), ContextTag(2), ProfileTag(123, 1))); position.Exit(); ASSERT_HAS_NAME(position, "world"); @@ -190,30 +189,30 @@ void TestDeeperEnter(nlTestSuite * inSuite, void * inContext) position.Enter(ByTag(AnonymousTag())); ASSERT_HAS_NAME(position, "foo"); - NL_TEST_ASSERT(inSuite, HasPath(GetPath(position), ContextTag(2), ProfileTag(234, 2), AnonymousTag())); + EXPECT_TRUE(HasPath(GetPath(position), ContextTag(2), ProfileTag(234, 2), AnonymousTag())); // test some unknown for (int i = 0; i < 100; i++) { position.Enter(ByTag(AnonymousTag())); - NL_TEST_ASSERT(inSuite, position.Get() == nullptr); - NL_TEST_ASSERT(inSuite, GetPath(position).empty()); + EXPECT_EQ(position.Get(), nullptr); + EXPECT_TRUE(GetPath(position).empty()); } for (int i = 0; i < 100; i++) { - NL_TEST_ASSERT(inSuite, position.Get() == nullptr); - NL_TEST_ASSERT(inSuite, GetPath(position).empty()); + EXPECT_EQ(position.Get(), nullptr); + EXPECT_TRUE(GetPath(position).empty()); position.Exit(); } - NL_TEST_ASSERT(inSuite, HasPath(GetPath(position), ContextTag(2), ProfileTag(234, 2), AnonymousTag())); + EXPECT_TRUE(HasPath(GetPath(position), ContextTag(2), ProfileTag(234, 2), AnonymousTag())); ASSERT_HAS_NAME(position, "foo"); position.Exit(); - NL_TEST_ASSERT(inSuite, HasPath(GetPath(position), ContextTag(2), ProfileTag(234, 2))); + EXPECT_TRUE(HasPath(GetPath(position), ContextTag(2), ProfileTag(234, 2))); ASSERT_HAS_NAME(position, "b"); position.Exit(); - NL_TEST_ASSERT(inSuite, HasPath(GetPath(position), ContextTag(2))); + EXPECT_TRUE(HasPath(GetPath(position), ContextTag(2))); ASSERT_HAS_NAME(position, "world"); // root and stay there @@ -221,15 +220,15 @@ void TestDeeperEnter(nlTestSuite * inSuite, void * inContext) position.Exit(); position.Exit(); position.Exit(); - NL_TEST_ASSERT(inSuite, GetPath(position).empty()); + EXPECT_TRUE(GetPath(position).empty()); // can still navigate from the root position.Enter(ByName("world")); - NL_TEST_ASSERT(inSuite, HasPath(GetPath(position), ContextTag(2))); + EXPECT_TRUE(HasPath(GetPath(position), ContextTag(2))); ASSERT_HAS_CONTEXT_TAG(position, 2); } -void TestDescendLimit(nlTestSuite * inSuite, void * inContext) +TEST(TestFlatTreePosition, TestDescendLimit) { Position position(tree.data(), tree.size()); @@ -241,34 +240,17 @@ void TestDescendLimit(nlTestSuite * inSuite, void * inContext) // only 2 positions can be remembered. Running out of space position.Enter(ByName("foo")); - NL_TEST_ASSERT(inSuite, position.Get() == nullptr); - NL_TEST_ASSERT(inSuite, GetPath(position).empty()); + EXPECT_EQ(position.Get(), nullptr); + EXPECT_TRUE(GetPath(position).empty()); position.Exit(); - NL_TEST_ASSERT(inSuite, HasPath(GetPath(position), ContextTag(2), ProfileTag(234, 2))); + EXPECT_TRUE(HasPath(GetPath(position), ContextTag(2), ProfileTag(234, 2))); ASSERT_HAS_NAME(position, "b"); ASSERT_HAS_PROFILE_TAG(position, 234, 2); position.Exit(); - NL_TEST_ASSERT(inSuite, HasPath(GetPath(position), ContextTag(2))); + EXPECT_TRUE(HasPath(GetPath(position), ContextTag(2))); ASSERT_HAS_NAME(position, "world"); ASSERT_HAS_CONTEXT_TAG(position, 2); } - -const nlTest sTests[] = { - NL_TEST_DEF("TestSimpleEnterExit", TestSimpleEnterExit), // - NL_TEST_DEF("TestDeeperEnter", TestDeeperEnter), // - NL_TEST_DEF("TestDescendLimit", TestDescendLimit), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestFlatTreePosition() -{ - nlTestSuite theSuite = { "FlatTree", sTests, nullptr, nullptr }; - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestFlatTreePosition) diff --git a/src/lib/shell/commands/BUILD.gn b/src/lib/shell/commands/BUILD.gn index d4dd5820ad7f7a..f3da2760f641b1 100644 --- a/src/lib/shell/commands/BUILD.gn +++ b/src/lib/shell/commands/BUILD.gn @@ -36,7 +36,10 @@ source_set("commands") { } if (chip_enable_wifi) { - sources += [ "WiFi.cpp" ] + sources += [ + "WiFi.cpp", + "WiFi.h", + ] } if (chip_enable_ble && chip_device_platform != "none") { diff --git a/src/lib/shell/commands/WiFi.cpp b/src/lib/shell/commands/WiFi.cpp index 9bd891f20430da..35ab5e26ae23a2 100644 --- a/src/lib/shell/commands/WiFi.cpp +++ b/src/lib/shell/commands/WiFi.cpp @@ -18,17 +18,22 @@ #include #include #include +#include #include +#include #include #include +#include using chip::DeviceLayer::ConnectivityManager; using chip::DeviceLayer::ConnectivityMgr; +using namespace chip::DeviceLayer::NetworkCommissioning; namespace chip { namespace Shell { -static chip::Shell::Engine sShellWiFiSubCommands; +static Shell::Engine sShellWiFiSubCommands; +static DeviceLayer::NetworkCommissioning::WiFiDriver * sDriver; static CHIP_ERROR WiFiHelpHandler(int argc, char ** argv) { @@ -104,13 +109,38 @@ static CHIP_ERROR WiFiModeHandler(int argc, char ** argv) static CHIP_ERROR WiFiConnectHandler(int argc, char ** argv) { - if (argc != 2) - { - return CHIP_ERROR_INVALID_ARGUMENT; - } + CHIP_ERROR error = CHIP_NO_ERROR; + uint8_t networkIndex; + char debugBuffer[CHIP_CONFIG_NETWORK_COMMISSIONING_DEBUG_TEXT_BUFFER_SIZE]; + MutableCharSpan debugText(debugBuffer); + + VerifyOrReturnError(GetWiFiDriver() != nullptr, CHIP_ERROR_NOT_IMPLEMENTED); + + /* Command accepts running with SSID and password as parameters */ + VerifyOrReturnError((argc == 2), CHIP_ERROR_INVALID_ARGUMENT); + + ByteSpan ssidSpan = ByteSpan(Uint8::from_const_char(argv[0]), strlen(argv[0])); + ByteSpan passwordSpan = ByteSpan(Uint8::from_const_char(argv[1]), strlen(argv[1])); + + VerifyOrReturnError(IsSpanUsable(ssidSpan) && IsSpanUsable(passwordSpan), CHIP_ERROR_INVALID_ARGUMENT); + + ChipLogProgress(Shell, "Adding/Updating network %s", argv[0]); + + /* AddOrUpdateNetwork() checks ssid length and password length. The network info is not persistent. */ + GetWiFiDriver()->AddOrUpdateNetwork(ssidSpan, passwordSpan, debugText, networkIndex); + + ChipLogProgress(Shell, "Connecting to network"); + /* Connection event will be returned in OnWiFiConnectivityChange from DeviceCallbacks.cpp */ + GetWiFiDriver()->ConnectNetwork(ssidSpan, nullptr); - // TODO:Provision WiFi using WirelessDriver - return CHIP_ERROR_NOT_IMPLEMENTED; + return error; +} + +static CHIP_ERROR WiFiDisconnectHandler(int argc, char ** argv) +{ + VerifyOrReturnError((argc == 0), CHIP_ERROR_INVALID_ARGUMENT); + + return ConnectivityMgr().DisconnectNetwork(); } static CHIP_ERROR WiFiDispatch(int argc, char ** argv) @@ -122,13 +152,24 @@ static CHIP_ERROR WiFiDispatch(int argc, char ** argv) return sShellWiFiSubCommands.ExecCommand(argc, argv); } +void SetWiFiDriver(WiFiDriver * driver) +{ + sDriver = driver; +} + +WiFiDriver * GetWiFiDriver() +{ + return sDriver; +} + void RegisterWiFiCommands() { /// Subcommands for root command: `device ` static const shell_command_t sWiFiSubCommands[] = { { &WiFiHelpHandler, "help", "" }, - { &WiFiModeHandler, "mode", "Get/Set wifi mode. Usage: wifi mode [disable|ap|sta]." }, - { &WiFiConnectHandler, "connect", "Connect to AP. Usage: wifi connect ssid psk." }, + { &WiFiModeHandler, "mode", "Get/Set wifi mode. Usage: wifi mode [disable|ap|sta]" }, + { &WiFiConnectHandler, "connect", "Connect to AP. Usage: wifi connect " }, + { &WiFiDisconnectHandler, "disconnect", "Disconnect device from AP. Usage: wifi disconnect" }, }; static const shell_command_t sWiFiCommand = { &WiFiDispatch, "wifi", "Usage: wifi " }; diff --git a/src/lib/shell/commands/WiFi.h b/src/lib/shell/commands/WiFi.h new file mode 100644 index 00000000000000..858a960f5b11d0 --- /dev/null +++ b/src/lib/shell/commands/WiFi.h @@ -0,0 +1,35 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Header that defines default shell commands for CHIP examples + */ + +#pragma once + +#include +#include + +namespace chip { +namespace Shell { + +void SetWiFiDriver(DeviceLayer::NetworkCommissioning::WiFiDriver * driver); +DeviceLayer::NetworkCommissioning::WiFiDriver * GetWiFiDriver(); + +} // namespace Shell +} // namespace chip diff --git a/src/lib/shell/tests/BUILD.gn b/src/lib/shell/tests/BUILD.gn index 12c15d84c531c7..0b5f7d5fd43222 100644 --- a/src/lib/shell/tests/BUILD.gn +++ b/src/lib/shell/tests/BUILD.gn @@ -14,11 +14,10 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libTestShell" test_sources = [ @@ -31,7 +30,5 @@ chip_test_suite_using_nltest("tests") { public_deps = [ "${chip_root}/src/lib/core", "${chip_root}/src/lib/shell", - "${chip_root}/src/lib/support:testing_nlunit", - "${nlunit_test_root}:nlunit-test", ] } diff --git a/src/lib/shell/tests/TestShellStreamerStdio.cpp b/src/lib/shell/tests/TestShellStreamerStdio.cpp index 170fc377e36e95..dde770c950183c 100644 --- a/src/lib/shell/tests/TestShellStreamerStdio.cpp +++ b/src/lib/shell/tests/TestShellStreamerStdio.cpp @@ -15,11 +15,10 @@ * limitations under the License. */ -#include +#include #include #include -#include #include #include @@ -48,7 +47,7 @@ static const struct test_streamer_vector test_vector_streamer_out[] = { // Unit tests // ================================= -static void TestStreamer_Output(nlTestSuite * inSuite, void * inContext) +TEST(TestShellStreamerStdio, TestStreamer_Output) { int numOfTestVectors = ArraySize(test_vector_streamer_out); int numOfTestsRan = 0; @@ -64,29 +63,8 @@ static void TestStreamer_Output(nlTestSuite * inSuite, void * inContext) num_chars = streamer_write(streamer_get(), output, strlen(output)); // Let's assume that all our output lengths fit in ssize_t. - NL_TEST_ASSERT(inSuite, num_chars == static_cast(strlen(output))); + EXPECT_EQ(num_chars, static_cast(strlen(output))); numOfTestsRan++; } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); + EXPECT_GT(numOfTestsRan, 0); } - -/** - * Test Suite. It lists all the test functions. - */ -static const nlTest sTests[] = { - - NL_TEST_DEF("Test Shell: TestStreamer_Output", TestStreamer_Output), - - NL_TEST_SENTINEL() -}; - -int TestStreamerStdio() -{ - nlTestSuite theSuite = { "Test Shell: Streamer", &sTests[0], nullptr, nullptr }; - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestStreamerStdio) diff --git a/src/lib/shell/tests/TestShellTokenizeLine.cpp b/src/lib/shell/tests/TestShellTokenizeLine.cpp index cbd0d751344670..8ed6c0eecde779 100644 --- a/src/lib/shell/tests/TestShellTokenizeLine.cpp +++ b/src/lib/shell/tests/TestShellTokenizeLine.cpp @@ -15,10 +15,9 @@ * limitations under the License. */ -#include +#include #include -#include // Include entire C++ file to have access to functions-under-test // such as TokenizeLine despite them being declared within an anonymous namespace. @@ -99,7 +98,7 @@ static const struct test_shell_vector test_vector_shell_tokenizer[] = { // Unit tests // ================================= -static void TestShell_Tokenizer(nlTestSuite * inSuite, void * inContext) +TEST(TestShellTokenizeLine, TestShell_Tokenizer) { int numOfTestVectors = ArraySize(test_vector_shell_tokenizer); int numOfTestsRan = 0; @@ -115,34 +114,13 @@ static void TestShell_Tokenizer(nlTestSuite * inSuite, void * inContext) char * argv[TEST_SHELL_MAX_TOKENS]; int argc = TokenizeLine(line, argv, TEST_SHELL_MAX_TOKENS); - NL_TEST_ASSERT(inSuite, argc == test_params->argc); + EXPECT_EQ(argc, test_params->argc); for (int i = 0; i < argc; i++) { - NL_TEST_ASSERT(inSuite, strcmp(argv[i], test_params->argv[i]) == 0); + EXPECT_EQ(strcmp(argv[i], test_params->argv[i]), 0); } numOfTestsRan++; } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); + EXPECT_GT(numOfTestsRan, 0); } - -/** - * Test Suite. It lists all the test functions. - */ -static const nlTest sTests[] = { - - NL_TEST_DEF("Test Shell: TestShell_Tokenizer", TestShell_Tokenizer), - - NL_TEST_SENTINEL() -}; - -int TestShellTokenizeLine() -{ - nlTestSuite theSuite = { "Test Shell: MainLoop", &sTests[0], nullptr, nullptr }; - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestShellTokenizeLine) diff --git a/src/lib/support/BUILD.gn b/src/lib/support/BUILD.gn index a5bf63a0034b41..34906592214fbd 100644 --- a/src/lib/support/BUILD.gn +++ b/src/lib/support/BUILD.gn @@ -350,6 +350,7 @@ pw_static_library("pw_tests_wrapper") { public_deps = [ "$dir_pw_log:impl", "$dir_pw_unit_test", + "$dir_pw_unit_test:logging", ] sources = [ "UnitTest.cpp", diff --git a/src/lib/support/UnitTest.cpp b/src/lib/support/UnitTest.cpp index 787898cccd82f2..95389398fefecb 100644 --- a/src/lib/support/UnitTest.cpp +++ b/src/lib/support/UnitTest.cpp @@ -1,12 +1,16 @@ #include "UnitTest.h" #include "pw_unit_test/framework.h" +#include "pw_unit_test/logging_event_handler.h" namespace chip { namespace test { int RunAllTests() { + testing::InitGoogleTest(nullptr, static_cast(nullptr)); + pw::unit_test::LoggingEventHandler handler; + pw::unit_test::RegisterEventHandler(&handler); return RUN_ALL_TESTS(); } diff --git a/src/lwip/cc13xx_26xx/lwipopts.h b/src/lwip/cc13xx_26xx/lwipopts.h index 925a06d2615bf8..d89c33afb5ed84 100644 --- a/src/lwip/cc13xx_26xx/lwipopts.h +++ b/src/lwip/cc13xx_26xx/lwipopts.h @@ -89,7 +89,7 @@ #define MEMP_SEPARATE_POOLS (1) #define LWIP_PBUF_FROM_CUSTOM_POOLS (0) #define MEMP_USE_CUSTOM_POOLS (0) -#define PBUF_POOL_SIZE (6) +#define PBUF_POOL_SIZE (12) #define PBUF_POOL_BUFSIZE (1280) #define PBUF_CUSTOM_POOL_IDX_START (MEMP_PBUF_POOL_SMALL) #define PBUF_CUSTOM_POOL_IDX_END (MEMP_PBUF_POOL_LARGE) diff --git a/src/messaging/ExchangeContext.cpp b/src/messaging/ExchangeContext.cpp index 74a861c1170b7f..3869ab4c48c921 100644 --- a/src/messaging/ExchangeContext.cpp +++ b/src/messaging/ExchangeContext.cpp @@ -322,6 +322,7 @@ ExchangeContext::ExchangeContext(ExchangeManager * em, uint16_t ExchangeId, cons SetAutoRequestAck(session->AllowsMRP()); #if CHIP_CONFIG_ENABLE_ICD_SERVER + // TODO(#33075) : Add check for group context to not a req since it serves no purpose app::ICDNotifier::GetInstance().NotifyActiveRequestNotification(app::ICDListener::KeepActiveFlag::kExchangeContextOpen); #endif @@ -341,6 +342,7 @@ ExchangeContext::~ExchangeContext() VerifyOrDie(mFlags.Has(Flags::kFlagClosed)); #if CHIP_CONFIG_ENABLE_ICD_SERVER + // TODO(#33075) : Add check for group context to not a req since it serves no purpose app::ICDNotifier::GetInstance().NotifyActiveRequestWithdrawal(app::ICDListener::KeepActiveFlag::kExchangeContextOpen); #endif // CHIP_CONFIG_ENABLE_ICD_SERVER diff --git a/src/platform/ASR/BLEAppSvc.cpp b/src/platform/ASR/BLEAppSvc.cpp index 124a58a3c5a188..d56485df2238cd 100644 --- a/src/platform/ASR/BLEAppSvc.cpp +++ b/src/platform/ASR/BLEAppSvc.cpp @@ -39,7 +39,7 @@ extern "C" { } #endif #include "BLEAppSvc.h" -#include +#include #include #include using namespace chip::DeviceLayer; diff --git a/src/platform/ASR/BLEManagerImpl.cpp b/src/platform/ASR/BLEManagerImpl.cpp index e960a617b4e33b..88f7460a962a3a 100644 --- a/src/platform/ASR/BLEManagerImpl.cpp +++ b/src/platform/ASR/BLEManagerImpl.cpp @@ -23,7 +23,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #include "BLEAppSvc.h" -#include +#include #include #include #include diff --git a/src/platform/Ameba/BLEManagerImpl.cpp b/src/platform/Ameba/BLEManagerImpl.cpp index 969febfffb5842..2d0a6d99515367 100644 --- a/src/platform/Ameba/BLEManagerImpl.cpp +++ b/src/platform/Ameba/BLEManagerImpl.cpp @@ -30,7 +30,7 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #include "stdio.h" #include "timers.h" diff --git a/src/platform/Beken/BLEManagerImpl.cpp b/src/platform/Beken/BLEManagerImpl.cpp index 3437a16acfdb79..37f9fea9b9106e 100644 --- a/src/platform/Beken/BLEManagerImpl.cpp +++ b/src/platform/Beken/BLEManagerImpl.cpp @@ -30,7 +30,7 @@ #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING #include #endif diff --git a/src/platform/Darwin/BLEManagerImpl.cpp b/src/platform/Darwin/BLEManagerImpl.cpp index 639e8d1e1c4657..c0af6ccf17d93e 100644 --- a/src/platform/Darwin/BLEManagerImpl.cpp +++ b/src/platform/Darwin/BLEManagerImpl.cpp @@ -23,7 +23,7 @@ */ #include -#include +#include #include #include #include diff --git a/src/platform/Darwin/BUILD.gn b/src/platform/Darwin/BUILD.gn index 8728178735404d..9dbb8460ae0566 100644 --- a/src/platform/Darwin/BUILD.gn +++ b/src/platform/Darwin/BUILD.gn @@ -76,6 +76,8 @@ static_library("Darwin") { "PosixConfig.h", "SystemPlatformConfig.h", "SystemTimeSupport.cpp", + "UserDefaults.h", + "UserDefaults.mm", ] if (chip_enable_wifi) { diff --git a/src/platform/Darwin/BleApplicationDelegate.h b/src/platform/Darwin/BleApplicationDelegate.h index 662b43b7b53c97..72aba4e65b397b 100644 --- a/src/platform/Darwin/BleApplicationDelegate.h +++ b/src/platform/Darwin/BleApplicationDelegate.h @@ -17,7 +17,7 @@ #pragma once -#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/Darwin/BleApplicationDelegateImpl.mm b/src/platform/Darwin/BleApplicationDelegateImpl.mm index c61f17a894d7c1..883f2a2bcd8916 100644 --- a/src/platform/Darwin/BleApplicationDelegateImpl.mm +++ b/src/platform/Darwin/BleApplicationDelegateImpl.mm @@ -24,7 +24,7 @@ #error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). #endif -#include +#include #include using namespace ::chip; diff --git a/src/platform/Darwin/BleConnectionDelegate.h b/src/platform/Darwin/BleConnectionDelegate.h index de97ac383729c1..1441f60610c822 100644 --- a/src/platform/Darwin/BleConnectionDelegate.h +++ b/src/platform/Darwin/BleConnectionDelegate.h @@ -17,7 +17,7 @@ #pragma once -#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/Darwin/BleConnectionDelegateImpl.mm b/src/platform/Darwin/BleConnectionDelegateImpl.mm index 8ec68fc35ea8f4..b325d079ba61a5 100644 --- a/src/platform/Darwin/BleConnectionDelegateImpl.mm +++ b/src/platform/Darwin/BleConnectionDelegateImpl.mm @@ -25,10 +25,7 @@ #error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). #endif -#include -#include -#include -#include +#include #include #include #include diff --git a/src/platform/Darwin/BlePlatformDelegate.h b/src/platform/Darwin/BlePlatformDelegate.h index 80b3dfff2d6e73..389a0bf28bce98 100644 --- a/src/platform/Darwin/BlePlatformDelegate.h +++ b/src/platform/Darwin/BlePlatformDelegate.h @@ -17,7 +17,7 @@ #pragma once -#include +#include #include using ::chip::Ble::ChipBleUUID; diff --git a/src/platform/Darwin/BlePlatformDelegateImpl.mm b/src/platform/Darwin/BlePlatformDelegateImpl.mm index 9b30cc7edcc843..210cd872318056 100644 --- a/src/platform/Darwin/BlePlatformDelegateImpl.mm +++ b/src/platform/Darwin/BlePlatformDelegateImpl.mm @@ -25,10 +25,7 @@ #error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). #endif -#include -#include -#include -#include +#include #include #include diff --git a/src/platform/Darwin/BleScannerDelegate.h b/src/platform/Darwin/BleScannerDelegate.h index 7759abbb4ba87c..9c96445145d67f 100644 --- a/src/platform/Darwin/BleScannerDelegate.h +++ b/src/platform/Darwin/BleScannerDelegate.h @@ -18,7 +18,7 @@ #pragma once -#include +#include #include namespace chip { diff --git a/src/platform/Darwin/DnssdImpl.cpp b/src/platform/Darwin/DnssdImpl.cpp index 4156c7a4bf0924..b80e5958310e68 100644 --- a/src/platform/Darwin/DnssdImpl.cpp +++ b/src/platform/Darwin/DnssdImpl.cpp @@ -17,6 +17,7 @@ #include "DnssdImpl.h" #include "DnssdType.h" #include "MdnsError.h" +#include "UserDefaults.h" #include @@ -29,6 +30,7 @@ using namespace chip::Dnssd; using namespace chip::Dnssd::Internal; +using namespace chip::Platform; namespace { @@ -76,8 +78,14 @@ void LogOnFailure(const char * name, DNSServiceErrorType err) */ CHIP_ERROR StartSRPTimer(uint16_t timeoutInMSecs, ResolveContext * ctx) { + // Check to see if a user default value exists for the SRP timeout. If it does, override the timeoutInMSecs with user default + // value. To override the timeout value, use ` defaults write org.csa-iot.matter.darwin SRPTimeoutInMSecsOverride + // ` See UserDefaults.mm for details. + timeoutInMSecs = GetUserDefaultDnssdSRPTimeoutInMSecs().value_or(timeoutInMSecs); + VerifyOrReturnValue(ctx != nullptr, CHIP_ERROR_INCORRECT_STATE); - ChipLogProgress(Discovery, "Starting timer to wait for possible SRP resolve results for %s", ctx->instanceName.c_str()); + ChipLogProgress(Discovery, "Starting timer to wait for %d milliseconds for possible SRP resolve results for %s", timeoutInMSecs, + ctx->instanceName.c_str()); return chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Milliseconds16(timeoutInMSecs), ResolveContext::SRPTimerExpiredCallback, static_cast(ctx)); } diff --git a/src/platform/Darwin/DnssdImpl.h b/src/platform/Darwin/DnssdImpl.h index 42ae55fdd9d4c0..3bf78fac6cb2bd 100644 --- a/src/platform/Darwin/DnssdImpl.h +++ b/src/platform/Darwin/DnssdImpl.h @@ -262,8 +262,8 @@ struct ResolveContext : public GenericContext std::shared_ptr consumerCounter; BrowseContext * const browseThatCausedResolve; // Can be null - // Indicates whether the timer for 250 msecs should be started - // to give the resolve on SRP domain some extra time to complete. + // Indicates whether the timer should be started to give the resolve + // on SRP domain some extra time to complete. bool shouldStartSRPTimerForResolve = false; bool isSRPTimerRunning = false; diff --git a/src/platform/Darwin/UUIDHelper.h b/src/platform/Darwin/UUIDHelper.h index 40ff15b927a04f..bf12cf9a92375e 100644 --- a/src/platform/Darwin/UUIDHelper.h +++ b/src/platform/Darwin/UUIDHelper.h @@ -17,7 +17,7 @@ #pragma once -#include +#include #import diff --git a/src/platform/Darwin/UserDefaults.h b/src/platform/Darwin/UserDefaults.h new file mode 100644 index 00000000000000..5df5d2064256b9 --- /dev/null +++ b/src/platform/Darwin/UserDefaults.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +namespace chip { +namespace Platform { + +std::optional GetUserDefaultDnssdSRPTimeoutInMSecs(); + +} // namespace Platform +} // namespace chip diff --git a/src/platform/Darwin/UserDefaults.mm b/src/platform/Darwin/UserDefaults.mm new file mode 100644 index 00000000000000..d24b0a4ee20f37 --- /dev/null +++ b/src/platform/Darwin/UserDefaults.mm @@ -0,0 +1,43 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UserDefaults.h" +#include +#include + +#import + +static NSString * const kUserDefaultDomain = @"org.csa-iot.matter.darwin"; +static NSString * const kSRPTimeoutInMsecsUserDefaultKey = @"SRPTimeoutInMSecsOverride"; + +namespace chip { +namespace Platform { + + std::optional GetUserDefaultDnssdSRPTimeoutInMSecs() + { + NSUserDefaults * defaults = [[NSUserDefaults alloc] initWithSuiteName:kUserDefaultDomain]; + NSInteger srpTimeoutValue = [defaults integerForKey:kSRPTimeoutInMsecsUserDefaultKey]; + if (CanCastTo(srpTimeoutValue)) { + uint16_t timeoutinMsecs = static_cast(srpTimeoutValue); + ChipLogProgress(Discovery, "Got a user default value for Dnssd SRP timeout - %d msecs", timeoutinMsecs); + return std::make_optional(timeoutinMsecs); + } + return std::nullopt; + } + +} // namespace Platform +} // namespace chip diff --git a/src/platform/ESP32/BLEManagerImpl.h b/src/platform/ESP32/BLEManagerImpl.h index aa740295d03eed..39cde57dc0c262 100644 --- a/src/platform/ESP32/BLEManagerImpl.h +++ b/src/platform/ESP32/BLEManagerImpl.h @@ -68,8 +68,7 @@ struct ble_gatt_char_context #include "ble/Ble.h" #if CONFIG_ENABLE_ESP32_BLE_CONTROLLER -#include -#include +#include #include #endif diff --git a/src/platform/ESP32/BUILD.gn b/src/platform/ESP32/BUILD.gn index b1d3650769c468..167d0eb6bc139c 100644 --- a/src/platform/ESP32/BUILD.gn +++ b/src/platform/ESP32/BUILD.gn @@ -185,6 +185,8 @@ static_library("ESP32") { sources += [ "ESP32DeviceInfoProvider.cpp", "ESP32DeviceInfoProvider.h", + "StaticESP32DeviceInfoProvider.cpp", + "StaticESP32DeviceInfoProvider.h", ] } diff --git a/src/platform/ESP32/ChipDeviceScanner.h b/src/platform/ESP32/ChipDeviceScanner.h index a7718d09a8188f..601e1ac6bab0b0 100644 --- a/src/platform/ESP32/ChipDeviceScanner.h +++ b/src/platform/ESP32/ChipDeviceScanner.h @@ -17,7 +17,6 @@ #pragma once -#include #include #include @@ -32,7 +31,7 @@ #include "esp_gattc_api.h" #include "esp_log.h" #include "freertos/FreeRTOS.h" -#include +#include #include #include #endif diff --git a/src/platform/ESP32/StaticESP32DeviceInfoProvider.cpp b/src/platform/ESP32/StaticESP32DeviceInfoProvider.cpp new file mode 100644 index 00000000000000..d65bdf8fc280fe --- /dev/null +++ b/src/platform/ESP32/StaticESP32DeviceInfoProvider.cpp @@ -0,0 +1,122 @@ +/* + + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include + +namespace chip { +namespace DeviceLayer { + +StaticESP32DeviceInfoProvider & StaticESP32DeviceInfoProvider::GetDefaultInstance(void) +{ + static StaticESP32DeviceInfoProvider sInstance; + return sInstance; +} + +DeviceInfoProvider::FixedLabelIterator * StaticESP32DeviceInfoProvider::IterateFixedLabel(EndpointId endpoint) +{ + return chip::Platform::New(endpoint, mFixedLabels); +} + +StaticESP32DeviceInfoProvider::StaticFixedLabelIteratorImpl::StaticFixedLabelIteratorImpl(EndpointId endpoint, + const Span & labels) +{ + mEndpoint = endpoint; + mLabels = labels; + mIndex = 0; +} + +size_t StaticESP32DeviceInfoProvider::StaticFixedLabelIteratorImpl::Count() +{ + size_t count = 0; + for (size_t i = 0; i < mLabels.size(); i++) + { + const FixedLabelEntry & entry = mLabels.data()[i]; + + if (entry.endpointId == mEndpoint) + { + count++; + } + } + return count; +} + +bool StaticESP32DeviceInfoProvider::StaticFixedLabelIteratorImpl::Next(FixedLabelType & output) +{ + ChipLogDetail(DeviceLayer, "Get the fixed label with index:%u at endpoint:%d", static_cast(mIndex), mEndpoint); + + while (mIndex < mLabels.size()) + { + const FixedLabelEntry & entry = mLabels.data()[mIndex++]; + if (entry.endpointId == mEndpoint) + { + output.label = entry.label; + output.value = entry.value; + return true; + } + } + + return false; +} + +DeviceInfoProvider::SupportedLocalesIterator * StaticESP32DeviceInfoProvider::IterateSupportedLocales() +{ + return chip::Platform::New(mSupportedLocales); +} + +StaticESP32DeviceInfoProvider::StaticSupportedLocalesIteratorImpl::StaticSupportedLocalesIteratorImpl( + const Span & locales) +{ + mLocales = locales; +} + +size_t StaticESP32DeviceInfoProvider::StaticSupportedLocalesIteratorImpl::Count() +{ + return mLocales.empty() ? 0 : mLocales.size(); +} + +bool StaticESP32DeviceInfoProvider::StaticSupportedLocalesIteratorImpl::Next(CharSpan & output) +{ + VerifyOrReturnValue(mIndex < mLocales.size(), false); + output = mLocales.data()[mIndex++]; + return true; +} + +DeviceInfoProvider::SupportedCalendarTypesIterator * StaticESP32DeviceInfoProvider::IterateSupportedCalendarTypes() +{ + return chip::Platform::New(mSupportedCalendarTypes); +} + +StaticESP32DeviceInfoProvider::StaticSupportedCalendarTypesIteratorImpl::StaticSupportedCalendarTypesIteratorImpl( + const Span & calendarTypes) +{ + mCalendarTypes = calendarTypes; +} + +size_t StaticESP32DeviceInfoProvider::StaticSupportedCalendarTypesIteratorImpl::Count() +{ + return mCalendarTypes.empty() ? 0 : mCalendarTypes.size(); +} + +bool StaticESP32DeviceInfoProvider::StaticSupportedCalendarTypesIteratorImpl::Next(CalendarType & output) +{ + VerifyOrReturnValue(mIndex < mCalendarTypes.size(), false); + output = mCalendarTypes.data()[mIndex++]; + return true; +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/ESP32/StaticESP32DeviceInfoProvider.h b/src/platform/ESP32/StaticESP32DeviceInfoProvider.h new file mode 100644 index 00000000000000..860110cc0ac9a2 --- /dev/null +++ b/src/platform/ESP32/StaticESP32DeviceInfoProvider.h @@ -0,0 +1,141 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include + +namespace chip { +namespace DeviceLayer { + +class StaticESP32DeviceInfoProvider : public ESP32DeviceInfoProvider +{ +public: + StaticESP32DeviceInfoProvider() = default; + ~StaticESP32DeviceInfoProvider() override {} + + // Iterators + FixedLabelIterator * IterateFixedLabel(EndpointId endpoint); + SupportedLocalesIterator * IterateSupportedLocales(); + SupportedCalendarTypesIterator * IterateSupportedCalendarTypes(); + + static StaticESP32DeviceInfoProvider & GetDefaultInstance(); + + struct FixedLabelEntry + { + EndpointId endpointId; + CharSpan label; + CharSpan value; + }; + + /** + * @brief API to set the supported calendar types + * + * @param[in] supportedCalendarTypes Span of type chip::app::Clusters::TimeFormatLocalization::CalendarTypeEnum + * containing the supported calendar types. The underlying data must remain allocated throughout + * the lifetime of the device, as the API does not make a copy. + * + * @return CHIP_ERROR indicating the success or failure of the operation. + */ + CHIP_ERROR SetSupportedCalendarTypes(const Span & supportedCalendarTypes) + { + VerifyOrReturnError(!supportedCalendarTypes.empty(), CHIP_ERROR_INVALID_ARGUMENT); + mSupportedCalendarTypes = supportedCalendarTypes; + return CHIP_NO_ERROR; + } + + /** + * @brief API to set the supported Locales + * + * @param[in] supportedLocales Span of type chip::CharSpan containing the supported locales. + * The underlying data must remain allocated throughout the lifetime of the device, + * as the API does not make a copy. + * + * @return CHIP_ERROR indicating the success or failure of the operation. + */ + CHIP_ERROR SetSupportedLocales(const Span & supportedLocales) + { + VerifyOrReturnError(!supportedLocales.empty(), CHIP_ERROR_INVALID_ARGUMENT); + mSupportedLocales = supportedLocales; + return CHIP_NO_ERROR; + } + + /** + * @brief API to set the fixed labels + * + * @param[in] fixedLabels Span of type chip::DeviceLayer::StaticESP32DeviceInfoProvider::FixedLabelEntry + * containing the fixed labels for supported endpoints. + * The underlying data must remain allocated throughout the lifetime of the device, + * as the API does not make a copy. + * + * @return CHIP_ERROR indicating the success or failure of the operation. + */ + CHIP_ERROR SetFixedLabels(const Span & supportedFixedLabels) + { + VerifyOrReturnError(!supportedFixedLabels.empty(), CHIP_ERROR_INVALID_ARGUMENT); + mFixedLabels = supportedFixedLabels; + return CHIP_NO_ERROR; + } + +protected: + class StaticFixedLabelIteratorImpl : public FixedLabelIterator + { + public: + StaticFixedLabelIteratorImpl(EndpointId endpoint, const Span & labels); + size_t Count(); + bool Next(FixedLabelType & output); + void Release() { chip::Platform::Delete(this); } + + private: + EndpointId mEndpoint = 0; + size_t mIndex = 0; + Span mLabels; + }; + + class StaticSupportedLocalesIteratorImpl : public SupportedLocalesIterator + { + public: + StaticSupportedLocalesIteratorImpl(const Span & locales); + size_t Count(); + bool Next(CharSpan & output); + void Release() { chip::Platform::Delete(this); } + + private: + size_t mIndex = 0; + Span mLocales; + }; + + class StaticSupportedCalendarTypesIteratorImpl : public SupportedCalendarTypesIterator + { + public: + StaticSupportedCalendarTypesIteratorImpl(const Span & calendarTypes); + size_t Count(); + bool Next(CalendarType & output); + void Release() { chip::Platform::Delete(this); } + + private: + size_t mIndex = 0; + Span mCalendarTypes; + }; + +private: + Span mSupportedCalendarTypes; + Span mSupportedLocales; + Span mFixedLabels; +}; + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp b/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp index 06c95b3b45f153..e5d9077ee63ae2 100644 --- a/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp +++ b/src/platform/ESP32/bluedroid/BLEManagerImpl.cpp @@ -35,9 +35,8 @@ #if CONFIG_BT_BLUEDROID_ENABLED #if CONFIG_ENABLE_ESP32_BLE_CONTROLLER -#include +#include #endif -#include #include #include #include diff --git a/src/platform/ESP32/nimble/BLEManagerImpl.cpp b/src/platform/ESP32/nimble/BLEManagerImpl.cpp index 5407e9969b50e3..edff1666e6311a 100644 --- a/src/platform/ESP32/nimble/BLEManagerImpl.cpp +++ b/src/platform/ESP32/nimble/BLEManagerImpl.cpp @@ -31,9 +31,8 @@ #if CONFIG_BT_NIMBLE_ENABLED #if CONFIG_ENABLE_ESP32_BLE_CONTROLLER -#include +#include #endif -#include #include #include #include diff --git a/src/platform/ESP32/route_hook/ESP32RouteHook.c b/src/platform/ESP32/route_hook/ESP32RouteHook.c index d02c3d6eec0db0..bf1ad3284604b4 100644 --- a/src/platform/ESP32/route_hook/ESP32RouteHook.c +++ b/src/platform/ESP32/route_hook/ESP32RouteHook.c @@ -65,6 +65,11 @@ static void ra_recv_handler(struct netif * netif, const uint8_t * icmp_payload, { uint8_t opt_type = icmp_payload[0]; uint8_t opt_len = (uint8_t) (icmp_payload[1] << 3); + if (opt_len == 0 || opt_len > payload_len) + { + ESP_LOGE(TAG, "Invalid ND6 option length"); + break; + } if (opt_type == ND6_OPTION_TYPE_ROUTE_INFO && opt_len >= sizeof(route_option_t) - sizeof(ip6_addr_p_t) && !is_self_address(netif, src_addr) && payload_len >= opt_len) diff --git a/src/platform/Infineon/CYW30739/BLEManagerImpl.cpp b/src/platform/Infineon/CYW30739/BLEManagerImpl.cpp index 40428c16ba2853..ab4deef1f91924 100644 --- a/src/platform/Infineon/CYW30739/BLEManagerImpl.cpp +++ b/src/platform/Infineon/CYW30739/BLEManagerImpl.cpp @@ -28,7 +28,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #include #include #include diff --git a/src/platform/Infineon/PSOC6/BLEManagerImpl.cpp b/src/platform/Infineon/PSOC6/BLEManagerImpl.cpp index 917cdc267e4d24..cb2b01197669e7 100644 --- a/src/platform/Infineon/PSOC6/BLEManagerImpl.cpp +++ b/src/platform/Infineon/PSOC6/BLEManagerImpl.cpp @@ -28,7 +28,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #include #include #include diff --git a/src/platform/Linux/BLEManagerImpl.cpp b/src/platform/Linux/BLEManagerImpl.cpp index 714b55d07ec20b..a3781c483a887c 100644 --- a/src/platform/Linux/BLEManagerImpl.cpp +++ b/src/platform/Linux/BLEManagerImpl.cpp @@ -35,8 +35,7 @@ #include #include -#include -#include +#include #include #include #include @@ -78,13 +77,6 @@ const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0 const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, 0x9D, 0x12 } }; -void HandleConnectTimeout(chip::System::Layer *, void * apEndpoint) -{ - VerifyOrDie(apEndpoint != nullptr); - static_cast(apEndpoint)->CancelConnect(); - BLEManagerImpl::HandleConnectFailed(CHIP_ERROR_TIMEOUT); -} - } // namespace BLEManagerImpl BLEManagerImpl::sInstance; @@ -117,16 +109,17 @@ CHIP_ERROR BLEManagerImpl::_Init() void BLEManagerImpl::_Shutdown() { - // Ensure scan resources are cleared (e.g. timeout timers). + // Make sure that timers are stopped before shutting down the BLE layer. + DeviceLayer::SystemLayer().CancelTimer(HandleScanTimer, this); + DeviceLayer::SystemLayer().CancelTimer(HandleAdvertisingTimer, this); + DeviceLayer::SystemLayer().CancelTimer(HandleConnectTimer, this); + mDeviceScanner.Shutdown(); - // Stop advertising and free resources. mBLEAdvertisement.Shutdown(); - // Make sure that the endpoint is not used by the timer. - DeviceLayer::SystemLayer().CancelTimer(HandleConnectTimeout, &mEndpoint); - // Release BLE connection resources (unregister from BlueZ). mEndpoint.Shutdown(); + mBluezObjectManager.Shutdown(); - mFlags.Clear(Flags::kBluezBLELayerInitialized); + mFlags.Clear(Flags::kBluezManagerInitialized); } CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) @@ -262,7 +255,8 @@ void BLEManagerImpl::HandlePlatformSpecificBLEEvent(const ChipDeviceEvent * apEv apEvent->Platform.BLEAdapter.mAdapterAddress); if (apEvent->Platform.BLEAdapter.mAdapterId == mAdapterId) { - // TODO: Handle adapter added + mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; + DriveBLEState(); } break; case DeviceEventType::kPlatformLinuxBLEAdapterRemoved: @@ -270,7 +264,21 @@ void BLEManagerImpl::HandlePlatformSpecificBLEEvent(const ChipDeviceEvent * apEv apEvent->Platform.BLEAdapter.mAdapterAddress); if (apEvent->Platform.BLEAdapter.mAdapterId == mAdapterId) { - // TODO: Handle adapter removed + // Shutdown all BLE operations and release resources + mDeviceScanner.Shutdown(); + mBLEAdvertisement.Shutdown(); + mEndpoint.Shutdown(); + // Drop reference to the adapter + mAdapter.reset(); + // Clear all flags related to BlueZ BLE operations + mFlags.Clear(Flags::kBluezAdapterAvailable); + mFlags.Clear(Flags::kBluezBLELayerInitialized); + mFlags.Clear(Flags::kAdvertisingConfigured); + mFlags.Clear(Flags::kAppRegistered); + mFlags.Clear(Flags::kAdvertising); + CleanScanConfig(); + // Indicate that the adapter is no longer available + err = BLE_ERROR_ADAPTER_UNAVAILABLE; } break; case DeviceEventType::kPlatformLinuxBLECentralConnected: @@ -344,9 +352,7 @@ void BLEManagerImpl::HandlePlatformSpecificBLEEvent(const ChipDeviceEvent * apEv exit: if (err != CHIP_NO_ERROR) { - ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err)); - mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; - DeviceLayer::SystemLayer().CancelTimer(HandleAdvertisingTimer, this); + DisableBLEService(err); mFlags.Clear(Flags::kControlOpInProgress); } } @@ -669,9 +675,23 @@ void BLEManagerImpl::DriveBLEState() exit: if (err != CHIP_NO_ERROR) { - ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err)); + DisableBLEService(err); + } +} + +void BLEManagerImpl::DisableBLEService(CHIP_ERROR err) +{ + ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %" CHIP_ERROR_FORMAT, err.Format()); + mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; + // Stop all timers if the error is other than BLE adapter unavailable. In case of BLE adapter + // beeing unavailable, we will keep timers running, as the adapter might become available in + // the nearest future (e.g. BlueZ restart due to crash). By doing that we will ensure that BLE + // adapter reappearance will not extend timeouts for the ongoing operations. + if (err != BLE_ERROR_ADAPTER_UNAVAILABLE) + { + DeviceLayer::SystemLayer().CancelTimer(HandleScanTimer, this); DeviceLayer::SystemLayer().CancelTimer(HandleAdvertisingTimer, this); - mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; + DeviceLayer::SystemLayer().CancelTimer(HandleConnectTimer, this); } } @@ -757,7 +777,7 @@ void BLEManagerImpl::InitiateScan(BleScanState scanType) ChipLogError(Ble, "Failed to start BLE scan: %" CHIP_ERROR_FORMAT, err.Format()); }); - err = DeviceLayer::SystemLayer().StartTimer(kNewConnectionScanTimeout, HandleScannerTimer, this); + err = DeviceLayer::SystemLayer().StartTimer(kNewConnectionScanTimeout, HandleScanTimer, this); VerifyOrExit(err == CHIP_NO_ERROR, { mBLEScanConfig.mBleScanState = BleScanState::kNotScanning; mDeviceScanner.StopScan(); @@ -771,7 +791,7 @@ void BLEManagerImpl::InitiateScan(BleScanState scanType) } } -void BLEManagerImpl::HandleScannerTimer(chip::System::Layer *, void * appState) +void BLEManagerImpl::HandleScanTimer(chip::System::Layer *, void * appState) { auto * manager = static_cast(appState); manager->OnScanError(CHIP_ERROR_TIMEOUT); @@ -781,7 +801,7 @@ void BLEManagerImpl::HandleScannerTimer(chip::System::Layer *, void * appState) void BLEManagerImpl::CleanScanConfig() { if (mBLEScanConfig.mBleScanState == BleScanState::kConnecting) - DeviceLayer::SystemLayer().CancelTimer(HandleConnectTimeout, &mEndpoint); + DeviceLayer::SystemLayer().CancelTimer(HandleConnectTimer, this); mBLEScanConfig.mBleScanState = BleScanState::kNotScanning; } @@ -802,7 +822,7 @@ CHIP_ERROR BLEManagerImpl::CancelConnection() // If in discovery mode, stop scan. else if (mBLEScanConfig.mBleScanState != BleScanState::kNotScanning) { - DeviceLayer::SystemLayer().CancelTimer(HandleScannerTimer, this); + DeviceLayer::SystemLayer().CancelTimer(HandleScanTimer, this); mDeviceScanner.StopScan(); } return CHIP_NO_ERROR; @@ -887,10 +907,10 @@ void BLEManagerImpl::OnDeviceScanned(BluezDevice1 & device, const chip::Ble::Chi // We StartScan in the ChipStack thread. // StopScan should also be performed in the ChipStack thread. // At the same time, the scan timer also needs to be canceled in the ChipStack thread. - DeviceLayer::SystemLayer().CancelTimer(HandleScannerTimer, this); + DeviceLayer::SystemLayer().CancelTimer(HandleScanTimer, this); mDeviceScanner.StopScan(); // Stop scanning and then start connecting timer - DeviceLayer::SystemLayer().StartTimer(kConnectTimeout, HandleConnectTimeout, &mEndpoint); + DeviceLayer::SystemLayer().StartTimer(kConnectTimeout, HandleConnectTimer, this); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); CHIP_ERROR err = mEndpoint.ConnectDevice(device); @@ -899,6 +919,13 @@ void BLEManagerImpl::OnDeviceScanned(BluezDevice1 & device, const chip::Ble::Chi ChipLogProgress(Ble, "New device connected: %s", address); } +void BLEManagerImpl::HandleConnectTimer(chip::System::Layer *, void * appState) +{ + auto * manager = static_cast(appState); + manager->mEndpoint.CancelConnect(); + BLEManagerImpl::HandleConnectFailed(CHIP_ERROR_TIMEOUT); +} + void BLEManagerImpl::OnScanComplete() { switch (mBLEScanConfig.mBleScanState) diff --git a/src/platform/Linux/BLEManagerImpl.h b/src/platform/Linux/BLEManagerImpl.h index 4432c106b3bc35..e3f3e4186abb7e 100644 --- a/src/platform/Linux/BLEManagerImpl.h +++ b/src/platform/Linux/BLEManagerImpl.h @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include "bluez/BluezAdvertisement.h" @@ -184,12 +184,15 @@ class BLEManagerImpl final : public BLEManager, }; void DriveBLEState(); + void DisableBLEService(CHIP_ERROR err); BluezAdvertisement::AdvertisingIntervals GetAdvertisingIntervals() const; - static void HandleAdvertisingTimer(chip::System::Layer *, void * appState); void InitiateScan(BleScanState scanType); - static void HandleScannerTimer(chip::System::Layer *, void * appState); void CleanScanConfig(); + static void HandleAdvertisingTimer(chip::System::Layer *, void * appState); + static void HandleScanTimer(chip::System::Layer *, void * appState); + static void HandleConnectTimer(chip::System::Layer *, void * appState); + CHIPoBLEServiceMode mServiceMode; BitFlags mFlags; diff --git a/src/platform/Linux/bluez/BluezAdvertisement.cpp b/src/platform/Linux/bluez/BluezAdvertisement.cpp index f2855b24629290..c68d601d241cd0 100644 --- a/src/platform/Linux/bluez/BluezAdvertisement.cpp +++ b/src/platform/Linux/bluez/BluezAdvertisement.cpp @@ -24,7 +24,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/platform/Linux/bluez/BluezAdvertisement.h b/src/platform/Linux/bluez/BluezAdvertisement.h index f1ee9aee21e15d..fcae7713a43efc 100644 --- a/src/platform/Linux/bluez/BluezAdvertisement.h +++ b/src/platform/Linux/bluez/BluezAdvertisement.h @@ -24,7 +24,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/platform/Linux/bluez/BluezEndpoint.cpp b/src/platform/Linux/bluez/BluezEndpoint.cpp index f7b7bc66f85a0b..151c09e09f662d 100644 --- a/src/platform/Linux/bluez/BluezEndpoint.cpp +++ b/src/platform/Linux/bluez/BluezEndpoint.cpp @@ -57,7 +57,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/platform/Linux/bluez/BluezEndpoint.h b/src/platform/Linux/bluez/BluezEndpoint.h index 938e558198384d..01821bf11c6507 100644 --- a/src/platform/Linux/bluez/BluezEndpoint.h +++ b/src/platform/Linux/bluez/BluezEndpoint.h @@ -52,7 +52,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/platform/Linux/bluez/BluezObjectManager.cpp b/src/platform/Linux/bluez/BluezObjectManager.cpp index 91a2ffb2bcd929..2d555edc562be8 100644 --- a/src/platform/Linux/bluez/BluezObjectManager.cpp +++ b/src/platform/Linux/bluez/BluezObjectManager.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -188,16 +188,25 @@ BluezObjectManager::NotificationsDelegates BluezObjectManager::GetDeviceNotifica return delegates; } -void BluezObjectManager::OnObjectAdded(GDBusObjectManager * aMgr, GDBusObject * aObj) +void BluezObjectManager::OnObjectAdded(GDBusObjectManager * aMgr, BluezObject * aObj) { - GAutoPtr adapter(bluez_object_get_adapter1(reinterpret_cast(aObj))); - if (adapter) + GAutoPtr adapter(bluez_object_get_adapter1(aObj)); + // Verify that the adapter is properly initialized - the class property must be set. + // BlueZ can export adapter objects on the bus before it is fully initialized. Such + // adapter objects are not usable and must be ignored. + // + // TODO: Find a better way to determine whether the adapter interface exposed by + // BlueZ D-Bus service is fully functional. The current approach is based on + // the assumption that the class property is non-zero, which is true only + // for BR/EDR + LE adapters. LE-only adapters do not have HCI command to read + // the class property and BlueZ sets it to 0 as a default value. + if (adapter && bluez_adapter1_get_class(adapter.get()) != 0) { NotifyAdapterAdded(adapter.get()); return; } - GAutoPtr device(bluez_object_get_device1(reinterpret_cast(aObj))); + GAutoPtr device(bluez_object_get_device1(aObj)); if (device) { for (auto delegate : GetDeviceNotificationsDelegates(device.get())) @@ -207,9 +216,9 @@ void BluezObjectManager::OnObjectAdded(GDBusObjectManager * aMgr, GDBusObject * } } -void BluezObjectManager::OnObjectRemoved(GDBusObjectManager * aMgr, GDBusObject * aObj) +void BluezObjectManager::OnObjectRemoved(GDBusObjectManager * aMgr, BluezObject * aObj) { - GAutoPtr adapter(bluez_object_get_adapter1(reinterpret_cast(aObj))); + GAutoPtr adapter(bluez_object_get_adapter1(aObj)); if (adapter) { RemoveAdapterSubscriptions(adapter.get()); @@ -217,7 +226,7 @@ void BluezObjectManager::OnObjectRemoved(GDBusObjectManager * aMgr, GDBusObject return; } - GAutoPtr device(bluez_object_get_device1(reinterpret_cast(aObj))); + GAutoPtr device(bluez_object_get_device1(aObj)); if (device) { for (auto delegate : GetDeviceNotificationsDelegates(device.get())) @@ -227,10 +236,22 @@ void BluezObjectManager::OnObjectRemoved(GDBusObjectManager * aMgr, GDBusObject } } -void BluezObjectManager::OnInterfacePropertiesChanged(GDBusObjectManagerClient * aMgr, GDBusObjectProxy * aObj, GDBusProxy * aIface, +void BluezObjectManager::OnInterfacePropertiesChanged(GDBusObjectManagerClient * aMgr, BluezObject * aObj, GDBusProxy * aIface, GVariant * aChangedProps, const char * const * aInvalidatedProps) { - GAutoPtr device(bluez_object_get_device1(reinterpret_cast(aObj))); + uint32_t classValue = 0; + GAutoPtr adapter(bluez_object_get_adapter1(aObj)); + // When the adapter's readonly class property is set, it means that the adapter has been + // fully initialized and is ready to be used. It's most likely that the adapter has been + // previously ignored in the OnObjectAdded callback, so now we can notify the application + // about the new adapter. + if (adapter && g_variant_lookup(aChangedProps, "Class", "u", &classValue) && classValue != 0) + { + NotifyAdapterAdded(adapter.get()); + return; + } + + GAutoPtr device(bluez_object_get_device1(aObj)); if (device) { for (auto delegate : GetDeviceNotificationsDelegates(device.get())) @@ -256,18 +277,19 @@ CHIP_ERROR BluezObjectManager::SetupObjectManager() g_signal_connect(mObjectManager.get(), "object-added", G_CALLBACK(+[](GDBusObjectManager * mgr, GDBusObject * obj, BluezObjectManager * self) { - return self->OnObjectAdded(mgr, obj); + return self->OnObjectAdded(mgr, reinterpret_cast(obj)); }), this); g_signal_connect(mObjectManager.get(), "object-removed", G_CALLBACK(+[](GDBusObjectManager * mgr, GDBusObject * obj, BluezObjectManager * self) { - return self->OnObjectRemoved(mgr, obj); + return self->OnObjectRemoved(mgr, reinterpret_cast(obj)); }), this); g_signal_connect(mObjectManager.get(), "interface-proxy-properties-changed", G_CALLBACK(+[](GDBusObjectManagerClient * mgr, GDBusObjectProxy * obj, GDBusProxy * iface, GVariant * changed, const char * const * invalidated, BluezObjectManager * self) { - return self->OnInterfacePropertiesChanged(mgr, obj, iface, changed, invalidated); + return self->OnInterfacePropertiesChanged(mgr, reinterpret_cast(obj), iface, changed, + invalidated); }), this); diff --git a/src/platform/Linux/bluez/BluezObjectManager.h b/src/platform/Linux/bluez/BluezObjectManager.h index 4943451ac60ad7..6514141c10d609 100644 --- a/src/platform/Linux/bluez/BluezObjectManager.h +++ b/src/platform/Linux/bluez/BluezObjectManager.h @@ -89,9 +89,9 @@ class BluezObjectManager using NotificationsDelegates = std::vector; NotificationsDelegates GetDeviceNotificationsDelegates(BluezDevice1 * device); - void OnObjectAdded(GDBusObjectManager * aMgr, GDBusObject * aObj); - void OnObjectRemoved(GDBusObjectManager * aMgr, GDBusObject * aObj); - void OnInterfacePropertiesChanged(GDBusObjectManagerClient * aMgr, GDBusObjectProxy * aObj, GDBusProxy * aIface, + void OnObjectAdded(GDBusObjectManager * aMgr, BluezObject * aObj); + void OnObjectRemoved(GDBusObjectManager * aMgr, BluezObject * aObj); + void OnInterfacePropertiesChanged(GDBusObjectManagerClient * aMgr, BluezObject * aObj, GDBusProxy * aIface, GVariant * aChangedProps, const char * const * aInvalidatedProps); GAutoPtr mConnection; diff --git a/src/platform/Linux/bluez/ChipDeviceScanner.cpp b/src/platform/Linux/bluez/ChipDeviceScanner.cpp index 28a9baa358b33f..dcb113b7f479c9 100644 --- a/src/platform/Linux/bluez/ChipDeviceScanner.cpp +++ b/src/platform/Linux/bluez/ChipDeviceScanner.cpp @@ -23,7 +23,7 @@ #include -#include +#include #include #include #include diff --git a/src/platform/Linux/bluez/ChipDeviceScanner.h b/src/platform/Linux/bluez/ChipDeviceScanner.h index ead9467fdc29ef..274af60d32d442 100644 --- a/src/platform/Linux/bluez/ChipDeviceScanner.h +++ b/src/platform/Linux/bluez/ChipDeviceScanner.h @@ -21,7 +21,7 @@ #include -#include +#include #include #include #include diff --git a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h index 896c5ef0f54f22..6b9e1f7432612c 100644 --- a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h +++ b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h @@ -40,6 +40,7 @@ #include #include #include +#include #include namespace chip { @@ -229,6 +230,7 @@ class GenericThreadStackManagerImpl_OpenThread DnsBrowseCallback mDnsBrowseCallback; DnsResolveCallback mDnsResolveCallback; + GeneralFaults mNetworkFaults; struct DnsServiceTxtEntries { diff --git a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp index e0fb3df5ef7336..f4548e67829582 100644 --- a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp +++ b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp @@ -52,6 +52,7 @@ #include #include #include +#include #include #include #include @@ -223,6 +224,22 @@ void GenericThreadStackManagerImpl_OpenThread::_OnPlatformEvent(const { ChipLogError(DeviceLayer, "Failed to post Thread connectivity change: %" CHIP_ERROR_FORMAT, status.Format()); } + + ThreadDiagnosticsDelegate * delegate = GetDiagnosticDataProvider().GetThreadDiagnosticsDelegate(); + + if (mIsAttached) + { + delegate->OnConnectionStatusChanged(app::Clusters::ThreadNetworkDiagnostics::ConnectionStatusEnum::kConnected); + } + else + { + delegate->OnConnectionStatusChanged(app::Clusters::ThreadNetworkDiagnostics::ConnectionStatusEnum::kNotConnected); + + GeneralFaults current; + current.add(to_underlying(chip::app::Clusters::ThreadNetworkDiagnostics::NetworkFaultEnum::kLinkDown)); + delegate->OnNetworkFaultChanged(mNetworkFaults, current); + mNetworkFaults = current; + } } #if CHIP_DETAIL_LOGGING diff --git a/src/platform/Tizen/BLEManagerImpl.cpp b/src/platform/Tizen/BLEManagerImpl.cpp index 4d4c3e77316fc7..a78efd9c944cce 100644 --- a/src/platform/Tizen/BLEManagerImpl.cpp +++ b/src/platform/Tizen/BLEManagerImpl.cpp @@ -47,7 +47,6 @@ #include #include -#include #include #include #include diff --git a/src/platform/Tizen/BLEManagerImpl.h b/src/platform/Tizen/BLEManagerImpl.h index 1a49b9dae6c33f..ed30b92aa958b7 100644 --- a/src/platform/Tizen/BLEManagerImpl.h +++ b/src/platform/Tizen/BLEManagerImpl.h @@ -33,7 +33,6 @@ #include #include -#include #include #include #include diff --git a/src/platform/Tizen/ChipDeviceScanner.h b/src/platform/Tizen/ChipDeviceScanner.h index 09b5a6d5f39e15..c8ecc5bfa8e81a 100644 --- a/src/platform/Tizen/ChipDeviceScanner.h +++ b/src/platform/Tizen/ChipDeviceScanner.h @@ -28,7 +28,7 @@ #include #include -#include +#include #include #include diff --git a/src/platform/Zephyr/BLEManagerImpl.cpp b/src/platform/Zephyr/BLEManagerImpl.cpp index d4e83332452a06..4eba52756d1368 100644 --- a/src/platform/Zephyr/BLEManagerImpl.cpp +++ b/src/platform/Zephyr/BLEManagerImpl.cpp @@ -27,7 +27,7 @@ #include -#include +#include #include #include #include diff --git a/src/platform/android/BLEManagerImpl.cpp b/src/platform/android/BLEManagerImpl.cpp index 05dfb5f560fbb5..d729ba5134573c 100644 --- a/src/platform/android/BLEManagerImpl.cpp +++ b/src/platform/android/BLEManagerImpl.cpp @@ -23,7 +23,7 @@ */ #include -#include +#include #include #include #include diff --git a/src/platform/android/BLEManagerImpl.h b/src/platform/android/BLEManagerImpl.h index effa75db4ce3b4..1b25d6b11b44c1 100644 --- a/src/platform/android/BLEManagerImpl.h +++ b/src/platform/android/BLEManagerImpl.h @@ -23,7 +23,7 @@ #pragma once -#include +#include #include #include #include diff --git a/src/platform/android/java/chip/platform/AndroidBleManager.java b/src/platform/android/java/chip/platform/AndroidBleManager.java index 1d440b67b18da3..52b0052d409ef8 100644 --- a/src/platform/android/java/chip/platform/AndroidBleManager.java +++ b/src/platform/android/java/chip/platform/AndroidBleManager.java @@ -584,12 +584,19 @@ private void connectBLE(Object bluetoothDeviceObj) { } class ConnectionGattCallback extends AndroidBluetoothGattCallback { + private static final int STATE_INIT = 1; + private static final int STATE_DISCOVER_SERVICE = 2; + private static final int STATE_REQUEST_MTU = 3; + + private int mState = STATE_INIT; + @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { Log.i(TAG, "onConnectionStateChange status = " + status + ", newState= + " + newState); super.onConnectionStateChange(gatt, status, newState); if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) { Log.i(TAG, "Discovering Services..."); + mState = STATE_DISCOVER_SERVICE; gatt.discoverServices(); return; } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { @@ -602,14 +609,23 @@ public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState public void onServicesDiscovered(BluetoothGatt gatt, int status) { Log.d(TAG, "onServicesDiscovered status = " + status); super.onServicesDiscovered(gatt, status); + if (mState != STATE_DISCOVER_SERVICE) { + Log.d(TAG, "Invalid state : " + mState); + return; + } Log.i(TAG, "Services Discovered"); + mState = STATE_REQUEST_MTU; gatt.requestMtu(247); } @Override public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) { super.onMtuChanged(gatt, mtu, status); + if (mState != STATE_REQUEST_MTU) { + Log.d(TAG, "Invalid state : " + mState); + return; + } String deviceName = ""; if (gatt != null && gatt.getDevice() != null) { deviceName = gatt.getDevice().getName(); diff --git a/src/platform/bouffalolab/common/BLEManagerImpl.cpp b/src/platform/bouffalolab/common/BLEManagerImpl.cpp index 1612f080d03575..b2f2c82f60716e 100644 --- a/src/platform/bouffalolab/common/BLEManagerImpl.cpp +++ b/src/platform/bouffalolab/common/BLEManagerImpl.cpp @@ -21,7 +21,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #include #include #include diff --git a/src/platform/bouffalolab/common/BLEManagerImpl.h b/src/platform/bouffalolab/common/BLEManagerImpl.h index a0c69fe242372b..b0682b80e11b19 100644 --- a/src/platform/bouffalolab/common/BLEManagerImpl.h +++ b/src/platform/bouffalolab/common/BLEManagerImpl.h @@ -20,7 +20,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #include #include diff --git a/src/platform/cc13xx_26xx/BLEManagerImpl.cpp b/src/platform/cc13xx_26xx/BLEManagerImpl.cpp index 4d0c009eef1f39..e733184a9314f0 100644 --- a/src/platform/cc13xx_26xx/BLEManagerImpl.cpp +++ b/src/platform/cc13xx_26xx/BLEManagerImpl.cpp @@ -29,7 +29,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #include #include "FreeRTOS.h" diff --git a/src/platform/cc13xx_26xx/TI_heap_wrapper.c b/src/platform/cc13xx_26xx/TI_heap_wrapper.c new file mode 100644 index 00000000000000..a7498846603993 --- /dev/null +++ b/src/platform/cc13xx_26xx/TI_heap_wrapper.c @@ -0,0 +1,75 @@ +#include "bget.h" +#include +#include + +typedef unsigned int dpl_CSState; + +typedef union _dpl_cs_state_union_t +{ + /** critical section variable as declared in the interface */ + dpl_CSState state; + /** @internal field used to access internal data */ + struct _dpl_cs_state_aggr_t + { + /** field to store Swi_disable() return value */ + uint_least16_t swikey; + /** field to store Hwi_disable() return value */ + uint_least16_t hwikey; + } each; +} dpl_CSStateUnion; + +/* This is enter critical section for DPL supported devices */ +dpl_CSState dpl_enterCSImpl(void) +{ + + dpl_CSStateUnion cu; + cu.each.swikey = (uint_least16_t) SwiP_disable(); + cu.each.hwikey = (uint_least16_t) HwiP_disable(); + return cu.state; +} + +/* This is exit critical section for DPL supported devices */ +void dpl_leaveCSImpl(dpl_CSState key) +{ + dpl_CSStateUnion * cu = (dpl_CSStateUnion *) &key; + HwiP_restore((uint32_t) cu->each.hwikey); + SwiP_restore((uint32_t) cu->each.swikey); +} + +/* Protected allocation */ +void * pvPortMalloc(size_t xWantedSize) +{ + void * retVal = NULL; + + dpl_CSState state; + state = dpl_enterCSImpl(); + + retVal = bget(xWantedSize); + + dpl_leaveCSImpl(state); + return retVal; +} + +/* Protected Deallocation */ +void vPortFree(void * pv) +{ + dpl_CSState state; + state = dpl_enterCSImpl(); + + brel(pv); + + dpl_leaveCSImpl(state); +} + +void * pvPortRealloc(void * pv, size_t size) +{ + void * retVal = NULL; + + dpl_CSState state; + state = dpl_enterCSImpl(); + + retVal = bgetr(pv, size); + + dpl_leaveCSImpl(state); + return retVal; +} diff --git a/src/platform/cc13xx_26xx/TI_heap_wrapper.h b/src/platform/cc13xx_26xx/TI_heap_wrapper.h new file mode 100644 index 00000000000000..11df56fddbd3e8 --- /dev/null +++ b/src/platform/cc13xx_26xx/TI_heap_wrapper.h @@ -0,0 +1,10 @@ +/* Protected allocation + malloc/ICall_heapMalloc --> ti_heap_wrapper --> bget protected by critical section +*/ +void * pvPortMalloc(size_t xWantedSize); + +/* Protected Deallocation + Free/ICall_heapFree --> ti_heap_wrapper --> brel protected by critical section + */ +void vPortFree(void * pv); +void * pvPortRealloc(void * pv, size_t size); diff --git a/src/platform/cc13xx_26xx/chipOBleProfile.h b/src/platform/cc13xx_26xx/chipOBleProfile.h index d208733928bb52..e04b70eba80402 100644 --- a/src/platform/cc13xx_26xx/chipOBleProfile.h +++ b/src/platform/cc13xx_26xx/chipOBleProfile.h @@ -26,7 +26,7 @@ #define CHIPOBLEPROFILE_H #ifdef __cplusplus -#include +#include #include #include diff --git a/src/platform/cc13xx_26xx/memory.c b/src/platform/cc13xx_26xx/memory.c new file mode 100644 index 00000000000000..2bd85363e76454 --- /dev/null +++ b/src/platform/cc13xx_26xx/memory.c @@ -0,0 +1,398 @@ +/* + * Copyright (c) 2016-2022 Texas Instruments Incorporated - http://www.ti.com + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of Texas Instruments Incorporated nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/* + * ======== memory.c ======== + */ + +#if defined(__ti__) && !defined(__clang__) + +#pragma FUNC_EXT_CALLED(malloc); +#pragma FUNC_EXT_CALLED(memalign); +#pragma FUNC_EXT_CALLED(free); +#pragma FUNC_EXT_CALLED(calloc); +#pragma FUNC_EXT_CALLED(realloc); +#pragma FUNC_EXT_CALLED(aligned_alloc); + +#define ATTRIBUTE + +#elif defined(__IAR_SYSTEMS_ICC__) + +#define ATTRIBUTE + +#else + +#define ATTRIBUTE __attribute__((used)) + +#endif + +#include +#include +#include +#include + +#include +#include + +#if defined(__GNUC__) && !defined(__ti__) + +#include + +#endif + +extern void * pvPortRealloc(void * pv, size_t size); + +/* + * This Header is only needed to support advanced memory services - namely + * realloc() and memalign(). If the user doesn't require those features, they + * can remove the overhead and save both code and data. + */ +#if defined(TI_POSIX_FREERTOS_MEMORY_ENABLEADV) +/* + * Header is a union to make sure that the size is a power of 2. + * + * On the MSP430 small model (MSP430X), size_t is 2 bytes, which makes + * the size of this struct 6 bytes. + */ +typedef union Header +{ + struct + { + void * actualBuf; + size_t size; + } header; + int pad[2]; /* 4 words on 28L, 8 bytes on most others */ +} Header; +#endif + +/* + * ======== malloc ======== + */ +void ATTRIBUTE * malloc(size_t size) +{ +#if defined(TI_POSIX_FREERTOS_MEMORY_ENABLEADV) + Header * packet; + size_t allocSize; + + allocSize = size + sizeof(Header); + + /* + * If size is very large and allocSize overflows, the result will be + * smaller than size. In this case, don't try to allocate. + */ + if ((size == 0) || (allocSize < size)) + { + errno = EINVAL; + return (NULL); + } + + packet = (Header *) pvPortMalloc(allocSize); + + if (packet == NULL) + { + errno = ENOMEM; + return (NULL); + } + + packet->header.actualBuf = (void *) packet; + packet->header.size = allocSize; + + return (packet + 1); +#else + void * packet; + + if (size == 0) + { + errno = EINVAL; + return (NULL); + } + + packet = pvPortMalloc(size); + + if (packet == NULL) + { + errno = ENOMEM; + return (NULL); + } + + return (packet); +#endif +} + +/* + * ======== calloc ======== + */ +void ATTRIBUTE * calloc(size_t nmemb, size_t size) +{ + size_t nbytes; + void * retval; + + /* guard against divide by zero exception below */ + if (nmemb == 0) + { + errno = EINVAL; + return (NULL); + } + + nbytes = nmemb * size; + + /* return NULL if there's an overflow */ + if (nmemb && size != (nbytes / nmemb)) + { + errno = EOVERFLOW; + return (NULL); + } + + retval = malloc(nbytes); + if (retval != NULL) + { + (void) memset(retval, (int) '\0', nbytes); + } + + return (retval); +} +#ifndef DeviceFamily_CC3220 +/* + * ======== realloc ======== + */ +void ATTRIBUTE * realloc(void * ptr, size_t size) +{ +#if defined(TI_POSIX_FREERTOS_MEMORY_ENABLEADV) + void * retval; + Header * packet; + size_t oldSize; + + if (ptr == NULL) + { + retval = malloc(size); + } + else if (size == 0) + { + errno = EINVAL; + retval = NULL; + } + else + { + packet = (Header *) ptr - 1; + retval = malloc(size); + if (retval != NULL) + { + oldSize = packet->header.size - sizeof(Header); + (void) memcpy(retval, ptr, (size < oldSize) ? size : oldSize); + free(ptr); + } + } + + return (retval); +#else + void * packet; + + if (size == 0) + { + errno = EINVAL; + return (NULL); + } + + packet = pvPortRealloc(ptr, size); + + if (packet == NULL) + { + errno = ENOMEM; + return (NULL); + } + + return (packet); +#endif +} + +#else +/* + * ======== realloc ======== + */ +void ATTRIBUTE * realloc(void * ptr, size_t size) +{ +#if defined(TI_POSIX_FREERTOS_MEMORY_ENABLEADV) + void * retval; + Header * packet; + size_t oldSize; + + if (ptr == NULL) + { + retval = malloc(size); + } + else if (size == 0) + { + errno = EINVAL; + retval = NULL; + } + else + { + packet = (Header *) ptr - 1; + retval = malloc(size); + if (retval != NULL) + { + oldSize = packet->header.size - sizeof(Header); + (void) memcpy(retval, ptr, (size < oldSize) ? size : oldSize); + free(ptr); + } + } + + return (retval); +#else + /* Unsupported implementation */ + return (NULL); +#endif +} +#endif + +/* + * ======== free ======== + */ +void ATTRIBUTE free(void * ptr) +{ +#if defined(TI_POSIX_FREERTOS_MEMORY_ENABLEADV) + Header * packet; + + if (ptr != NULL) + { + packet = ((Header *) ptr) - 1; + vPortFree(packet->header.actualBuf); + } +#else + vPortFree(ptr); +#endif +} + +/* + * ======== memalign ======== + */ +void ATTRIBUTE * memalign(size_t boundary, size_t size) +{ +#if defined(TI_POSIX_FREERTOS_MEMORY_ENABLEADV) + Header * packet; + void * tmp; + + /* return NULL if size is 0, or alignment is not a power-of-2 */ + if (size == 0 || (boundary & (boundary - 1))) + { + errno = EINVAL; + return (NULL); + } + + if (boundary < sizeof(Header)) + { + boundary = sizeof(Header); + } + + /* + * Allocate 'align + size + sizeof(Header)' so that we have room for + * the 'packet' and can return an aligned buffer. + */ + tmp = pvPortMalloc(boundary + size + sizeof(Header)); + + if (tmp == NULL) + { + errno = ENOMEM; + return (NULL); + } + + if ((unsigned int) tmp & (boundary - 1)) + { + /* tmp is not already aligned */ + packet = (Header *) (((unsigned int) tmp + boundary) & ~(boundary - 1)) - 1; + if (packet < (Header *) tmp) + { + /* don't have room for Header before aligned address */ + packet = (Header *) ((unsigned int) packet + boundary); + } + } + else + { + /* tmp is already aligned to boundary (by chance) */ + packet = ((Header *) (((unsigned int) tmp + boundary))) - 1; + } + + packet->header.actualBuf = tmp; + packet->header.size = size + sizeof(Header); + + return (packet + 1); +#else + /* user called an unsupported function */ + return (NULL); +#endif +} + +/* + * ======== aligned_alloc ======== + */ +void ATTRIBUTE * aligned_alloc(size_t alignment, size_t size) +{ + /* use existing implementation to allocate buffer */ + return (memalign(alignment, size)); +} + +#if defined(__GNUC__) && !defined(__ti__) + +/* + * ======== _malloc_r ======== + */ +void ATTRIBUTE * _malloc_r(struct _reent * rptr, size_t size) +{ + return malloc(size); +} + +/* + * ======== _calloc_r ======== + */ +void ATTRIBUTE * _calloc_r(struct _reent * rptr, size_t nmemb, size_t size) +{ + return calloc(nmemb, size); +} + +/* + * ======== _free_r ======== + */ +void ATTRIBUTE _free_r(struct _reent * rptr, void * ptr) +{ + free(ptr); +} + +/* + * ======== _realloc_r ======== + */ +void ATTRIBUTE * _realloc_r(struct _reent * rptr, void * ptr, size_t size) +{ + return realloc(ptr, size); +} + +#endif diff --git a/src/platform/mbed/BLEManagerImpl.cpp b/src/platform/mbed/BLEManagerImpl.cpp index aa797ff95f6f4c..75c749f3f145f5 100644 --- a/src/platform/mbed/BLEManagerImpl.cpp +++ b/src/platform/mbed/BLEManagerImpl.cpp @@ -30,7 +30,7 @@ #include -#include +#include #include #include #include diff --git a/src/platform/mbed/BLEManagerImpl.h b/src/platform/mbed/BLEManagerImpl.h index 6dfb1d56e2097b..91675e08ab13c4 100644 --- a/src/platform/mbed/BLEManagerImpl.h +++ b/src/platform/mbed/BLEManagerImpl.h @@ -27,7 +27,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/mt793x/BLEManagerImpl.cpp b/src/platform/mt793x/BLEManagerImpl.cpp index f1ac9bfa707b88..0a90f2e2a733ba 100644 --- a/src/platform/mt793x/BLEManagerImpl.cpp +++ b/src/platform/mt793x/BLEManagerImpl.cpp @@ -34,7 +34,7 @@ #include "FreeRTOS.h" #include "event_groups.h" #include "timers.h" -#include +#include #include #include diff --git a/src/platform/nxp/common/ConnectivityManagerImpl.cpp b/src/platform/nxp/common/ConnectivityManagerImpl.cpp index 2753451c5308ff..c9d2861686b143 100644 --- a/src/platform/nxp/common/ConnectivityManagerImpl.cpp +++ b/src/platform/nxp/common/ConnectivityManagerImpl.cpp @@ -590,6 +590,34 @@ void ConnectivityManagerImpl::ConnectNetworkTimerHandler(::chip::System::Layer * PlatformMgr().UnlockChipStack(); } } + +/* Can be used to disconnect from WiFi network. + */ +CHIP_ERROR ConnectivityManagerImpl::_DisconnectNetwork(void) +{ + int ret = 0; + CHIP_ERROR err = CHIP_NO_ERROR; + + if (ConnectivityMgrImpl().IsWiFiStationConnected()) + { + ChipLogProgress(NetworkProvisioning, "Disconnecting from WiFi network."); + + ret = wlan_disconnect(); + + if (ret != WM_SUCCESS) + { + ChipLogError(NetworkProvisioning, "Failed to disconnect from network with error: %u", (uint8_t) ret); + err = CHIP_ERROR_UNEXPECTED_EVENT; + } + } + else + { + ChipLogError(NetworkProvisioning, "Error: WiFi not connected!"); + err = CHIP_ERROR_INCORRECT_STATE; + } + + return err; +} #endif } // namespace DeviceLayer diff --git a/src/platform/nxp/common/ConnectivityManagerImpl.h b/src/platform/nxp/common/ConnectivityManagerImpl.h index 806826daf0f7d3..49e4f66a13197b 100644 --- a/src/platform/nxp/common/ConnectivityManagerImpl.h +++ b/src/platform/nxp/common/ConnectivityManagerImpl.h @@ -115,6 +115,7 @@ class ConnectivityManagerImpl final : public ConnectivityManager, bool _IsWiFiStationEnabled(); bool _IsWiFiStationConnected(); bool _IsWiFiStationApplicationControlled(); + CHIP_ERROR _DisconnectNetwork(void); #endif /* CHIP_DEVICE_CONFIG_ENABLE_WPA */ // ===== Members for internal use by the following friends. diff --git a/src/platform/nxp/common/NetworkCommissioningDriver.h b/src/platform/nxp/common/NetworkCommissioningDriver.h index 5757771476e057..33d7d5bc1ed3af 100644 --- a/src/platform/nxp/common/NetworkCommissioningDriver.h +++ b/src/platform/nxp/common/NetworkCommissioningDriver.h @@ -72,10 +72,6 @@ class NXPWiFiDriver final : public WiFiDriver Status ReorderNetwork(ByteSpan networkId, uint8_t index, MutableCharSpan & outDebugText) override; void ConnectNetwork(ByteSpan networkId, ConnectCallback * callback) override; - /* Can be used to disconnect from WiFi network. - */ - int DisconnectNetwork(); - /* Returns the network SSID. User needs to allocate a buffer of size >= DeviceLayer::Internal::kMaxWiFiSSIDLength. * ssid - pointer to the returned SSID */ diff --git a/src/platform/nxp/common/NetworkCommissioningWiFiDriver.cpp b/src/platform/nxp/common/NetworkCommissioningWiFiDriver.cpp index d697c75d1042d7..c201dad7a6661c 100644 --- a/src/platform/nxp/common/NetworkCommissioningWiFiDriver.cpp +++ b/src/platform/nxp/common/NetworkCommissioningWiFiDriver.cpp @@ -142,14 +142,39 @@ Status NXPWiFiDriver::AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials, Mu Status NXPWiFiDriver::RemoveNetwork(ByteSpan networkId, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex) { + int err_code = 0; + outDebugText.reduce_size(0); outNetworkIndex = 0; VerifyOrReturnError(NetworkMatch(mStagingNetwork, networkId), Status::kNetworkIDNotFound); - // Use empty ssid for representing invalid network - mStagingNetwork.ssidLen = 0; - memset(mStagingNetwork.ssid, 0, DeviceLayer::Internal::kMaxWiFiSSIDLength); - memset(mStagingNetwork.credentials, 0, DeviceLayer::Internal::kMaxWiFiKeyLength); + err_code = wlan_remove_network((char *) networkId.data()); + + switch (err_code) + { + case -WM_E_INVAL: + ChipLogError(DeviceLayer, "Error: Network not found"); + break; + + case WM_SUCCESS: + /* Use empty ssid for representing invalid network */ + mStagingNetwork.ssidLen = 0; + memset(mStagingNetwork.ssid, 0, DeviceLayer::Internal::kMaxWiFiSSIDLength); + memset(mStagingNetwork.credentials, 0, DeviceLayer::Internal::kMaxWiFiKeyLength); + /* Save to persistent memory */ + CommitConfiguration(); + ChipLogProgress(DeviceLayer, "Successfully removed network"); + break; + + case WLAN_ERROR_STATE: + ChipLogError(DeviceLayer, "Error: Can't remove network in this state"); + break; + + default: + ChipLogError(DeviceLayer, "Error: Unable to remove network"); + break; + } + return Status::kSuccess; } @@ -238,29 +263,6 @@ void NXPWiFiDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * callbac } } -int NXPWiFiDriver::DisconnectNetwork(void) -{ - int ret = 0; - - if (ConnectivityMgrImpl().IsWiFiStationConnected()) - { - ChipLogProgress(NetworkProvisioning, "Disconnecting from WiFi network."); - - ret = wlan_disconnect(); - - if (ret != WM_SUCCESS) - { - ChipLogError(NetworkProvisioning, "Failed to disconnect from network with error: %u", (uint8_t) ret); - } - } - else - { - ChipLogError(NetworkProvisioning, "Error: WiFi not connected!"); - } - - return ret; -} - CHIP_ERROR NXPWiFiDriver::StartScanWiFiNetworks(ByteSpan ssid) { wlan_scan_params_v2_t wlan_scan_param; diff --git a/src/platform/nxp/k32w/common/BLEManagerCommon.cpp b/src/platform/nxp/k32w/common/BLEManagerCommon.cpp index b532ddef7f207e..12b32b8e4b71b2 100644 --- a/src/platform/nxp/k32w/common/BLEManagerCommon.cpp +++ b/src/platform/nxp/k32w/common/BLEManagerCommon.cpp @@ -32,7 +32,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #include "board.h" #include "gatt_db_app_interface.h" diff --git a/src/platform/qpg/BLEManagerImpl.cpp b/src/platform/qpg/BLEManagerImpl.cpp index 44fbf9367282d4..271c9b02e10d9f 100644 --- a/src/platform/qpg/BLEManagerImpl.cpp +++ b/src/platform/qpg/BLEManagerImpl.cpp @@ -25,8 +25,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include -#include +#include #include #include diff --git a/src/platform/silabs/SilabsConfig.h b/src/platform/silabs/SilabsConfig.h index 92a879177530c7..ccb14beeb8f177 100644 --- a/src/platform/silabs/SilabsConfig.h +++ b/src/platform/silabs/SilabsConfig.h @@ -112,6 +112,11 @@ class SilabsConfig static constexpr Key KConfigKey_ProductLabel = SilabsConfigKey(kMatterFactory_KeyBase, 0x10); static constexpr Key kConfigKey_ProductURL = SilabsConfigKey(kMatterFactory_KeyBase, 0x11); static constexpr Key kConfigKey_PartNumber = SilabsConfigKey(kMatterFactory_KeyBase, 0x12); + static constexpr Key kConfigKey_CACerts = SilabsConfigKey(kMatterFactory_KeyBase, 0x13); + static constexpr Key kConfigKey_DeviceCerts = SilabsConfigKey(kMatterFactory_KeyBase, 0x14); + static constexpr Key kConfigKey_hostname = SilabsConfigKey(kMatterFactory_KeyBase, 0x15); + static constexpr Key kConfigKey_clientid = SilabsConfigKey(kMatterFactory_KeyBase, 0x16); + static constexpr Key kConfigKey_Test_Event_Trigger_Key = SilabsConfigKey(kMatterFactory_KeyBase, 0x17); static constexpr Key kConfigKey_UniqueId = SilabsConfigKey(kMatterFactory_KeyBase, 0x1F); static constexpr Key kConfigKey_Creds_KeyId = SilabsConfigKey(kMatterFactory_KeyBase, 0x20); static constexpr Key kConfigKey_Creds_Base_Addr = SilabsConfigKey(kMatterFactory_KeyBase, 0x21); @@ -121,7 +126,11 @@ class SilabsConfig static constexpr Key kConfigKey_Creds_PAI_Size = SilabsConfigKey(kMatterFactory_KeyBase, 0x25); static constexpr Key kConfigKey_Creds_CD_Offset = SilabsConfigKey(kMatterFactory_KeyBase, 0x26); static constexpr Key kConfigKey_Creds_CD_Size = SilabsConfigKey(kMatterFactory_KeyBase, 0x27); - static constexpr Key kConfigKey_Test_Event_Trigger_Key = SilabsConfigKey(kMatterFactory_KeyBase, 0x28); + static constexpr Key kConfigKey_Provision_Request = SilabsConfigKey(kMatterFactory_KeyBase, 0x28); + static constexpr Key kConfigKey_Provision_Version = SilabsConfigKey(kMatterFactory_KeyBase, 0x29); + + static constexpr Key kOtaTlvEncryption_KeyId = SilabsConfigKey(kMatterFactory_KeyBase, 0x30); + // Matter Config Keys static constexpr Key kConfigKey_ServiceConfig = SilabsConfigKey(kMatterConfig_KeyBase, 0x01); static constexpr Key kConfigKey_PairedAccountId = SilabsConfigKey(kMatterConfig_KeyBase, 0x02); @@ -162,7 +171,7 @@ class SilabsConfig // Set key id limits for each group. static constexpr Key kMinConfigKey_MatterFactory = SilabsConfigKey(kMatterFactory_KeyBase, 0x00); - static constexpr Key kMaxConfigKey_MatterFactory = SilabsConfigKey(kMatterFactory_KeyBase, 0x2F); + static constexpr Key kMaxConfigKey_MatterFactory = SilabsConfigKey(kMatterFactory_KeyBase, 0x30); static constexpr Key kMinConfigKey_MatterConfig = SilabsConfigKey(kMatterConfig_KeyBase, 0x00); static constexpr Key kMaxConfigKey_MatterConfig = SilabsConfigKey(kMatterConfig_KeyBase, 0x22); diff --git a/src/platform/silabs/efr32/BLEManagerImpl.cpp b/src/platform/silabs/efr32/BLEManagerImpl.cpp index 64bab16f2e249a..4a6d78574005c1 100644 --- a/src/platform/silabs/efr32/BLEManagerImpl.cpp +++ b/src/platform/silabs/efr32/BLEManagerImpl.cpp @@ -39,7 +39,9 @@ extern "C" { #include "sl_bt_stack_config.h" #include "sl_bt_stack_init.h" #include "timers.h" -#include +#include +#include +#include #include #include #include @@ -106,17 +108,16 @@ const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0 const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, 0x9D, 0x12 } }; +bd_addr randomizedAddr = { 0 }; + } // namespace BLEManagerImpl BLEManagerImpl::sInstance; CHIP_ERROR BLEManagerImpl::_Init() { - CHIP_ERROR err; - // Initialize the CHIP BleLayer. - err = BleLayer::Init(this, this, &DeviceLayer::SystemLayer()); - SuccessOrExit(err); + ReturnErrorOnFailure(BleLayer::Init(this, this, &DeviceLayer::SystemLayer())); memset(mBleConnections, 0, sizeof(mBleConnections)); memset(mIndConfId, kUnusedIndex, sizeof(mIndConfId)); @@ -132,10 +133,23 @@ CHIP_ERROR BLEManagerImpl::_Init() mFlags.ClearAll().Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART); mFlags.Set(Flags::kFastAdvertisingEnabled, true); - PlatformMgr().ScheduleWork(DriveBLEState, 0); -exit: - return err; + // Check that an address was not already configured at boot. + // This covers the init-shutdown-init case to comply with the BLE address change at boot only requirement + bd_addr temp = { 0 }; + if (memcmp(&randomizedAddr, &temp, sizeof(bd_addr)) == 0) + { + // Since a random address is not configured, configure one + uint64_t random = Crypto::GetRandU64(); + // Copy random value to address. We don't care of the ordering since it's a random value. + memcpy(&randomizedAddr, &random, sizeof(randomizedAddr)); + + // Set two MSBs to 11 to properly the address - BLE Static Device Address requirement + randomizedAddr.addr[5] |= 0xC0; + } + + PlatformMgr().ScheduleWork(DriveBLEState, 0); + return CHIP_NO_ERROR; } uint16_t BLEManagerImpl::_NumConnections(void) @@ -484,14 +498,13 @@ CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) ChipLogError(DeviceLayer, "sl_bt_advertiser_create_set() failed: %s", ErrorStr(err)); }); - bd_addr randomizedAddr = {}; - ret = sl_bt_advertiser_set_random_address(advertising_set_handle, sl_bt_gap_random_resolvable_address, randomizedAddr, - &randomizedAddr); + ret = + sl_bt_advertiser_set_random_address(advertising_set_handle, sl_bt_gap_static_address, randomizedAddr, &randomizedAddr); VerifyOrExit(ret == SL_STATUS_OK, { err = MapBLEError(ret); ChipLogError(DeviceLayer, "sl_bt_advertiser_set_random_address() failed: %s", ErrorStr(err)); }); - ChipLogDetail(DeviceLayer, "BLE Resolvable private random address %02X:%02X:%02X:%02X:%02X:%02X", randomizedAddr.addr[5], + ChipLogDetail(DeviceLayer, "BLE Static Device Address %02X:%02X:%02X:%02X:%02X:%02X", randomizedAddr.addr[5], randomizedAddr.addr[4], randomizedAddr.addr[3], randomizedAddr.addr[2], randomizedAddr.addr[1], randomizedAddr.addr[0]); } @@ -625,6 +638,8 @@ CHIP_ERROR BLEManagerImpl::StopAdvertising(void) mFlags.Set(Flags::kFastAdvertisingEnabled, true); ret = sl_bt_advertiser_stop(advertising_set_handle); + sl_bt_advertiser_clear_random_address(advertising_set_handle); + sl_bt_advertiser_delete_set(advertising_set_handle); advertising_set_handle = 0xff; err = MapBLEError(ret); diff --git a/src/platform/silabs/rs911x/BLEManagerImpl.cpp b/src/platform/silabs/rs911x/BLEManagerImpl.cpp index 4ce7ef6973b553..e7495322018170 100644 --- a/src/platform/silabs/rs911x/BLEManagerImpl.cpp +++ b/src/platform/silabs/rs911x/BLEManagerImpl.cpp @@ -51,7 +51,7 @@ extern "C" { } #endif -#include +#include #include #include #include diff --git a/src/platform/stm32/BLEManagerImpl.cpp b/src/platform/stm32/BLEManagerImpl.cpp index 60863a2da6a698..fc24ebc64ac006 100644 --- a/src/platform/stm32/BLEManagerImpl.cpp +++ b/src/platform/stm32/BLEManagerImpl.cpp @@ -24,8 +24,7 @@ /* this file behaves like a config.h, comes first */ #include -#include -#include +#include #include #include diff --git a/src/platform/stm32/BLEManagerImpl.h b/src/platform/stm32/BLEManagerImpl.h index 98812500eac0b0..36b6c39d4b74ec 100644 --- a/src/platform/stm32/BLEManagerImpl.h +++ b/src/platform/stm32/BLEManagerImpl.h @@ -25,7 +25,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include +#include #include #include "FreeRTOS.h" diff --git a/src/platform/telink/BLEManagerImpl.cpp b/src/platform/telink/BLEManagerImpl.cpp index 220501a84f673a..69252b66a0ecef 100644 --- a/src/platform/telink/BLEManagerImpl.cpp +++ b/src/platform/telink/BLEManagerImpl.cpp @@ -27,7 +27,7 @@ #include -#include +#include #include #include #include diff --git a/src/platform/tests/BUILD.gn b/src/platform/tests/BUILD.gn index 9bf03229eb2b68..11e8bd5c746029 100644 --- a/src/platform/tests/BUILD.gn +++ b/src/platform/tests/BUILD.gn @@ -14,7 +14,6 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/src/platform/device.gni") @@ -27,7 +26,7 @@ declare_args() { if (chip_device_platform != "none" && chip_device_platform != "fake") { import("${chip_root}/build/chip/chip_test_suite.gni") - chip_test_suite_using_nltest("tests") { + chip_test_suite("tests") { output_name = "libPlatformTests" test_sources = [] @@ -41,10 +40,8 @@ if (chip_device_platform != "none" && chip_device_platform != "fake") { public_deps = [ "${chip_root}/src/lib/support", "${chip_root}/src/lib/support:test_utils", - "${chip_root}/src/lib/support:testing_nlunit", "${chip_root}/src/platform", "${chip_root}/src/system", - "${nlunit_test_root}:nlunit-test", ] if (chip_mdns != "none" && chip_enable_dnssd_tests && @@ -67,6 +64,7 @@ if (chip_device_platform != "none" && chip_device_platform != "fake") { if (chip_enable_openthread) { # FIXME: TestThreadStackMgr requires ot-br-posix daemon to be running # test_sources += [ "TestThreadStackMgr.cpp" ] + # configs = [ "//${chip_root}/third_party/ot-br-posix:dbus_config" ] } if (chip_enable_ble && diff --git a/src/platform/tests/TestCHIPoBLEStackMgr.cpp b/src/platform/tests/TestCHIPoBLEStackMgr.cpp index 168301c4285c53..2ec392849c7eca 100644 --- a/src/platform/tests/TestCHIPoBLEStackMgr.cpp +++ b/src/platform/tests/TestCHIPoBLEStackMgr.cpp @@ -17,25 +17,23 @@ #include "platform/internal/CHIPDeviceLayerInternal.h" #include +#include #include #include -#include #include #include "platform/PlatformManager.h" #include "platform/internal/BLEManager.h" -void EventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg) +void EventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t) { - (void) arg; if (event->Type == chip::DeviceLayer::DeviceEventType::kCHIPoBLEConnectionEstablished) { ChipLogProgress(DeviceLayer, "Receive kCHIPoBLEConnectionEstablished"); - // exit(0); } } -int TestCHIPoBLEStackManager() +TEST(TestCHIPoBLEStackManager, TestCHIPoBLEStackManager) { chip::Platform::MemoryInit(); @@ -54,7 +52,4 @@ int TestCHIPoBLEStackManager() chip::DeviceLayer::PlatformMgrImpl().RunEventLoop(); ChipLogProgress(DeviceLayer, "RunEventLoop completed"); chip::Platform::MemoryShutdown(); - return 0; } - -CHIP_REGISTER_TEST_SUITE(TestCHIPoBLEStackManager); diff --git a/src/platform/tests/TestCHIPoBLEStackMgrDriver.cpp b/src/platform/tests/TestCHIPoBLEStackMgrDriver.cpp index 1d85fdcca4d1b2..2635ebe81eb273 100644 --- a/src/platform/tests/TestCHIPoBLEStackMgrDriver.cpp +++ b/src/platform/tests/TestCHIPoBLEStackMgrDriver.cpp @@ -16,6 +16,7 @@ */ #include "TestCHIPoBLEStackMgr.h" +#include #include #include @@ -24,7 +25,8 @@ int main(int argc, char * argv[]) #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE if (argc == 2 && atoi(argv[1]) == 1) { - return TestCHIPoBLEStackManager(); + testing::InitGoogleTest(nullptr, nullptr); + return RUN_ALL_TESTS(); } return 0; #endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/tests/TestConfigurationMgr.cpp b/src/platform/tests/TestConfigurationMgr.cpp index 07cbec3c357c94..ad60d44583250f 100644 --- a/src/platform/tests/TestConfigurationMgr.cpp +++ b/src/platform/tests/TestConfigurationMgr.cpp @@ -28,10 +28,9 @@ #include #include +#include #include #include -#include -#include #include #include @@ -48,14 +47,25 @@ namespace { // Unit tests // ================================= -static void TestPlatformMgr_Init(nlTestSuite * inSuite, void * inContext) +struct TestConfigurationMgr : ::testing::Test { - // ConfigurationManager is initialized from PlatformManager indirectly - CHIP_ERROR err = PlatformMgr().InitChipStack(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); -} + static void SetUpTestSuite() + { + // ConfigurationManager is initialized from PlatformManager indirectly + CHIP_ERROR err = chip::Platform::MemoryInit(); + EXPECT_EQ(err, CHIP_NO_ERROR); + err = PlatformMgr().InitChipStack(); + EXPECT_EQ(err, CHIP_NO_ERROR); + } + + static void TearDownTestSuite() + { + PlatformMgr().Shutdown(); + chip::Platform::MemoryShutdown(); + } +}; -static void TestPlatformMgr_RunUnitTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConfigurationMgr, RunUnitTest) { #if CHIP_DEVICE_LAYER_TARGET_OPEN_IOT_SDK // TODO: Fix RunUnitTests() for Open IOT SDK. @@ -67,7 +77,7 @@ static void TestPlatformMgr_RunUnitTest(nlTestSuite * inSuite, void * inContext) ConfigurationMgr().RunUnitTests(); } -static void TestConfigurationMgr_SerialNumber(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConfigurationMgr, SerialNumber) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -75,25 +85,25 @@ static void TestConfigurationMgr_SerialNumber(nlTestSuite * inSuite, void * inCo const char * serialNumber = "89051AAZZ236"; err = ConfigurationMgr().StoreSerialNumber(serialNumber, strlen(serialNumber)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = GetDeviceInstanceInfoProvider()->GetSerialNumber(buf, 64); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, strlen(buf) == 12); - NL_TEST_ASSERT(inSuite, strcmp(buf, serialNumber) == 0); + EXPECT_EQ(strlen(buf), 12u); + EXPECT_STREQ(buf, serialNumber); err = ConfigurationMgr().StoreSerialNumber(serialNumber, 5); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = GetDeviceInstanceInfoProvider()->GetSerialNumber(buf, 64); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, strlen(buf) == 5); - NL_TEST_ASSERT(inSuite, strcmp(buf, "89051") == 0); + EXPECT_EQ(strlen(buf), 5u); + EXPECT_STREQ(buf, "89051"); } -static void TestConfigurationMgr_UniqueId(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConfigurationMgr, UniqueId) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -101,25 +111,25 @@ static void TestConfigurationMgr_UniqueId(nlTestSuite * inSuite, void * inContex const char * uniqueId = "67MXAZ012RT8UE"; err = ConfigurationMgr().StoreUniqueId(uniqueId, strlen(uniqueId)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = ConfigurationMgr().GetUniqueId(buf, 64); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, strlen(buf) == 14); - NL_TEST_ASSERT(inSuite, strcmp(buf, uniqueId) == 0); + EXPECT_EQ(strlen(buf), 14u); + EXPECT_STREQ(buf, uniqueId); err = ConfigurationMgr().StoreUniqueId(uniqueId, 7); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = ConfigurationMgr().GetUniqueId(buf, 64); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, strlen(buf) == 7); - NL_TEST_ASSERT(inSuite, strcmp(buf, "67MXAZ0") == 0); + EXPECT_EQ(strlen(buf), 7u); + EXPECT_STREQ(buf, "67MXAZ0"); } -static void TestConfigurationMgr_ManufacturingDate(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConfigurationMgr, ManufacturingDate) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -129,28 +139,28 @@ static void TestConfigurationMgr_ManufacturingDate(nlTestSuite * inSuite, void * uint8_t dayOfMonth; err = ConfigurationMgr().StoreManufacturingDate(mfgDate, strlen(mfgDate)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = GetDeviceInstanceInfoProvider()->GetManufacturingDate(year, month, dayOfMonth); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, year == 2008); - NL_TEST_ASSERT(inSuite, month == 9); - NL_TEST_ASSERT(inSuite, dayOfMonth == 20); + EXPECT_EQ(year, 2008); + EXPECT_EQ(month, 9); + EXPECT_EQ(dayOfMonth, 20); } -static void TestConfigurationMgr_HardwareVersion(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConfigurationMgr, HardwareVersion) { CHIP_ERROR err = CHIP_NO_ERROR; uint16_t hardwareVer; err = ConfigurationMgr().StoreHardwareVersion(1234); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = GetDeviceInstanceInfoProvider()->GetHardwareVersion(hardwareVer); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, hardwareVer == 1234); + EXPECT_EQ(hardwareVer, 1234); } static int SnprintfBuildDate(char * s, size_t n, uint16_t year, uint8_t month, uint8_t day) @@ -237,18 +247,18 @@ static int SnprintfBuildTimeOfDay(char * s, size_t n, System::Clock::Seconds32 c return SnprintfBuildTimeOfDay(s, n, hour, minute, second); } -static void TestConfigurationMgr_FirmwareBuildTime(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConfigurationMgr, FirmwareBuildTime) { // Read the firmware build time from the configuration manager. // This is referenced to the CHIP epoch. System::Clock::Seconds32 chipEpochTime; - NL_TEST_ASSERT(inSuite, ConfigurationMgr().GetFirmwareBuildChipEpochTime(chipEpochTime) == CHIP_NO_ERROR); + EXPECT_EQ(ConfigurationMgr().GetFirmwareBuildChipEpochTime(chipEpochTime), CHIP_NO_ERROR); // Override the hard-coded build time with the setter and verify operation. System::Clock::Seconds32 overrideValue = System::Clock::Seconds32(rand()); - NL_TEST_ASSERT(inSuite, ConfigurationMgr().SetFirmwareBuildChipEpochTime(overrideValue) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, ConfigurationMgr().GetFirmwareBuildChipEpochTime(chipEpochTime) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, overrideValue == chipEpochTime); + EXPECT_EQ(ConfigurationMgr().SetFirmwareBuildChipEpochTime(overrideValue), CHIP_NO_ERROR); + EXPECT_EQ(ConfigurationMgr().GetFirmwareBuildChipEpochTime(chipEpochTime), CHIP_NO_ERROR); + EXPECT_EQ(overrideValue, chipEpochTime); // Verify that the BuildTime.h parser can parse current CHIP_DEVICE_CONFIG_FIRMWARE_BUILD_DATE / TIME. do @@ -257,8 +267,8 @@ static void TestConfigurationMgr_FirmwareBuildTime(nlTestSuite * inSuite, void * const char * timeOfDay = CHIP_DEVICE_CONFIG_FIRMWARE_BUILD_TIME; // Check that strings look good. - NL_TEST_ASSERT(inSuite, !BUILD_DATE_IS_BAD(date)); - NL_TEST_ASSERT(inSuite, !BUILD_TIME_IS_BAD(timeOfDay)); + EXPECT_FALSE(BUILD_DATE_IS_BAD(date)); + EXPECT_FALSE(BUILD_TIME_IS_BAD(timeOfDay)); if (BUILD_DATE_IS_BAD(date) || BUILD_TIME_IS_BAD(timeOfDay)) { break; @@ -277,7 +287,8 @@ static void TestConfigurationMgr_FirmwareBuildTime(nlTestSuite * inSuite, void * { int printed; printed = SnprintfBuildDate(parsedDate, sizeof(parsedDate), year, month, day); - NL_TEST_ASSERT(inSuite, printed > 0 && printed < static_cast(sizeof(parsedDate))); + EXPECT_GT(printed, 0); + EXPECT_LT(printed, static_cast(sizeof(parsedDate))); } // Print the time of day to a straing as would be given by the __TIME__ macro. @@ -285,12 +296,13 @@ static void TestConfigurationMgr_FirmwareBuildTime(nlTestSuite * inSuite, void * { int printed; printed = SnprintfBuildTimeOfDay(parsedTimeOfDay, sizeof(parsedTimeOfDay), hour, minute, second); - NL_TEST_ASSERT(inSuite, printed > 0 && printed < static_cast(sizeof(parsedTimeOfDay))); + EXPECT_GT(printed, 0); + EXPECT_LT(printed, static_cast(sizeof(parsedTimeOfDay))); } // Verify match. - NL_TEST_ASSERT(inSuite, strcmp(date, parsedDate) == 0); - NL_TEST_ASSERT(inSuite, strcmp(timeOfDay, parsedTimeOfDay) == 0); + EXPECT_STREQ(date, parsedDate); + EXPECT_STREQ(timeOfDay, parsedTimeOfDay); } while (false); // Generate random chip epoch times and verify that our BuildTime.h parser @@ -310,19 +322,21 @@ static void TestConfigurationMgr_FirmwareBuildTime(nlTestSuite * inSuite, void * { int printed; printed = SnprintfBuildDate(date, sizeof(date), chipEpochTime); - NL_TEST_ASSERT(inSuite, printed > 0 && printed < static_cast(sizeof(date))); + EXPECT_GT(printed, 0); + EXPECT_LT(printed, static_cast(sizeof(date))); } // Print the time of day to a straing as would be given by the __TIME__ macro. { int printed; printed = SnprintfBuildTimeOfDay(timeOfDay, sizeof(timeOfDay), chipEpochTime); - NL_TEST_ASSERT(inSuite, printed > 0 && printed < static_cast(sizeof(timeOfDay))); + EXPECT_GT(printed, 0); + EXPECT_LT(printed, static_cast(sizeof(timeOfDay))); } // Check that strings look good. - NL_TEST_ASSERT(inSuite, !BUILD_DATE_IS_BAD(date)); - NL_TEST_ASSERT(inSuite, !BUILD_TIME_IS_BAD(timeOfDay)); + EXPECT_FALSE(BUILD_DATE_IS_BAD(date)); + EXPECT_FALSE(BUILD_TIME_IS_BAD(timeOfDay)); if (BUILD_DATE_IS_BAD(date) || BUILD_TIME_IS_BAD(timeOfDay)) { continue; @@ -338,16 +352,16 @@ static void TestConfigurationMgr_FirmwareBuildTime(nlTestSuite * inSuite, void * ChipEpochToCalendarTime(chipEpochTime.count(), year, month, day, hour, minute, second); // Verify that our BuildTime.h macros can correctly parse the date / time strings. - NL_TEST_ASSERT(inSuite, year == COMPUTE_BUILD_YEAR(date)); - NL_TEST_ASSERT(inSuite, month == COMPUTE_BUILD_MONTH(date)); - NL_TEST_ASSERT(inSuite, day == COMPUTE_BUILD_DAY(date)); - NL_TEST_ASSERT(inSuite, hour == COMPUTE_BUILD_HOUR(timeOfDay)); - NL_TEST_ASSERT(inSuite, minute == COMPUTE_BUILD_MIN(timeOfDay)); - NL_TEST_ASSERT(inSuite, second == COMPUTE_BUILD_SEC(timeOfDay)); + EXPECT_EQ(year, COMPUTE_BUILD_YEAR(date)); + EXPECT_EQ(month, COMPUTE_BUILD_MONTH(date)); + EXPECT_EQ(day, COMPUTE_BUILD_DAY(date)); + EXPECT_EQ(hour, COMPUTE_BUILD_HOUR(timeOfDay)); + EXPECT_EQ(minute, COMPUTE_BUILD_MIN(timeOfDay)); + EXPECT_EQ(second, COMPUTE_BUILD_SEC(timeOfDay)); } } -static void TestConfigurationMgr_CountryCode(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConfigurationMgr, CountryCode) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -356,16 +370,16 @@ static void TestConfigurationMgr_CountryCode(nlTestSuite * inSuite, void * inCon const char * countryCode = "US"; err = ConfigurationMgr().StoreCountryCode(countryCode, strlen(countryCode)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = ConfigurationMgr().GetCountryCode(buf, 8, countryCodeLen); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, countryCodeLen == strlen(countryCode)); - NL_TEST_ASSERT(inSuite, strcmp(buf, countryCode) == 0); + EXPECT_EQ(countryCodeLen, strlen(countryCode)); + EXPECT_STREQ(buf, countryCode); } -static void TestConfigurationMgr_GetPrimaryMACAddress(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConfigurationMgr, GetPrimaryMACAddress) { CHIP_ERROR err = CHIP_NO_ERROR; uint8_t macBuffer8Bytes[8]; @@ -376,13 +390,13 @@ static void TestConfigurationMgr_GetPrimaryMACAddress(nlTestSuite * inSuite, voi err = ConfigurationMgr().GetPrimaryMACAddress(mac8Bytes); if (mac8Bytes.size() != ConfigurationManager::kPrimaryMACAddressLength) { - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(err, CHIP_ERROR_INVALID_ARGUMENT); } err = ConfigurationMgr().GetPrimaryMACAddress(mac6Bytes); if (mac6Bytes.size() != ConfigurationManager::kPrimaryMACAddressLength) { - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(err, CHIP_ERROR_INVALID_ARGUMENT); } // NOTICE for above: @@ -391,116 +405,64 @@ static void TestConfigurationMgr_GetPrimaryMACAddress(nlTestSuite * inSuite, voi // expecially if running in emulators (zephyr and qemu) } -static void TestConfigurationMgr_GetFailSafeArmed(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConfigurationMgr, GetFailSafeArmed) { CHIP_ERROR err = CHIP_NO_ERROR; bool failSafeArmed = false; err = ConfigurationMgr().SetFailSafeArmed(true); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = ConfigurationMgr().GetFailSafeArmed(failSafeArmed); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, failSafeArmed == true); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(failSafeArmed, true); err = ConfigurationMgr().SetFailSafeArmed(false); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -static void TestConfigurationMgr_GetVendorName(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConfigurationMgr, GetVendorName) { CHIP_ERROR err = CHIP_NO_ERROR; char buf[64]; err = GetDeviceInstanceInfoProvider()->GetVendorName(buf, 64); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, strlen(buf) > 0 && strlen(buf) <= ConfigurationManager::kMaxVendorNameLength); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_GT(strlen(buf), 0u); + EXPECT_LE(strlen(buf), ConfigurationManager::kMaxVendorNameLength); } -static void TestConfigurationMgr_GetVendorId(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConfigurationMgr, GetVendorId) { CHIP_ERROR err = CHIP_NO_ERROR; uint16_t vendorId; err = GetDeviceInstanceInfoProvider()->GetVendorId(vendorId); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, vendorId >= 0 && vendorId <= 0xfff4); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_GE(vendorId, 0u); + EXPECT_LE(vendorId, 0xfff4); } -static void TestConfigurationMgr_GetProductName(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConfigurationMgr, GetProductName) { CHIP_ERROR err = CHIP_NO_ERROR; char buf[64]; err = GetDeviceInstanceInfoProvider()->GetProductName(buf, 64); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, strlen(buf) > 0 && strlen(buf) <= ConfigurationManager::kMaxProductNameLength); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_GT(strlen(buf), 0u); + EXPECT_LE(strlen(buf), ConfigurationManager::kMaxProductNameLength); } -static void TestConfigurationMgr_GetProductId(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConfigurationMgr, GetProductId) { CHIP_ERROR err = CHIP_NO_ERROR; uint16_t productId; err = GetDeviceInstanceInfoProvider()->GetProductId(productId); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, productId >= 1 && productId <= 0xffff); -} - -/** - * Test Suite. It lists all the test functions. - */ -static const nlTest sTests[] = { - NL_TEST_DEF("Test PlatformMgr::Init", TestPlatformMgr_Init), - NL_TEST_DEF("Test PlatformMgr::RunUnitTest", TestPlatformMgr_RunUnitTest), - NL_TEST_DEF("Test ConfigurationMgr::SerialNumber", TestConfigurationMgr_SerialNumber), - NL_TEST_DEF("Test ConfigurationMgr::UniqueId", TestConfigurationMgr_UniqueId), - NL_TEST_DEF("Test ConfigurationMgr::ManufacturingDate", TestConfigurationMgr_ManufacturingDate), - NL_TEST_DEF("Test ConfigurationMgr::HardwareVersion", TestConfigurationMgr_HardwareVersion), - NL_TEST_DEF("Test ConfigurationMgr::FirmwareBuildTime", TestConfigurationMgr_FirmwareBuildTime), - NL_TEST_DEF("Test ConfigurationMgr::CountryCode", TestConfigurationMgr_CountryCode), - NL_TEST_DEF("Test ConfigurationMgr::GetPrimaryMACAddress", TestConfigurationMgr_GetPrimaryMACAddress), - NL_TEST_DEF("Test ConfigurationMgr::GetFailSafeArmed", TestConfigurationMgr_GetFailSafeArmed), - NL_TEST_DEF("Test ConfigurationMgr::GetVendorName", TestConfigurationMgr_GetVendorName), - NL_TEST_DEF("Test ConfigurationMgr::GetVendorId", TestConfigurationMgr_GetVendorId), - NL_TEST_DEF("Test ConfigurationMgr::GetProductName", TestConfigurationMgr_GetProductName), - NL_TEST_DEF("Test ConfigurationMgr::GetProductId", TestConfigurationMgr_GetProductId), - NL_TEST_SENTINEL(), -}; - -/** - * Set up the test suite. - */ -int TestConfigurationMgr_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int TestConfigurationMgr_Teardown(void * inContext) -{ - PlatformMgr().Shutdown(); - chip::Platform::MemoryShutdown(); - return SUCCESS; + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_GE(productId, 1u); + EXPECT_LE(productId, 0xffff); } } // namespace - -/** - * Main - */ -int TestConfigurationMgr() -{ - nlTestSuite theSuite = { "ConfigurationMgr tests", &sTests[0], TestConfigurationMgr_Setup, TestConfigurationMgr_Teardown }; - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestConfigurationMgr) diff --git a/src/platform/tests/TestConnectivityMgr.cpp b/src/platform/tests/TestConnectivityMgr.cpp index 3a4548c43ef2a7..0699f971dfc493 100644 --- a/src/platform/tests/TestConnectivityMgr.cpp +++ b/src/platform/tests/TestConnectivityMgr.cpp @@ -30,8 +30,8 @@ #include #include -#include -#include + +#include #include #include @@ -45,63 +45,39 @@ using namespace chip::DeviceLayer; // Unit tests // ================================= -static void TestPlatformMgr_Init(nlTestSuite * inSuite, void * inContext) +struct TestConnectivityMgr : public ::testing::Test +{ + + static void SetUpTestSuite() + { + auto err = chip::Platform::MemoryInit(); + EXPECT_EQ(err, CHIP_NO_ERROR); + // TODO: Move initialization of the platform manager from Init test to here + } + + static void TearDownTestSuite() + { + chip::Platform::MemoryShutdown(); + chip::DeviceLayer::PlatformMgr().Shutdown(); + } +}; + +TEST_F(TestConnectivityMgr, Init) { // ConfigurationManager is initialized from PlatformManager indirectly CHIP_ERROR err = PlatformMgr().InitChipStack(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -static void TestConnectivityMgr_GetNetworkInterfaces(nlTestSuite * inSuite, void * inContext) +TEST_F(TestConnectivityMgr, GetNetworkInterfaces) { CHIP_ERROR err = CHIP_NO_ERROR; NetworkInterface * netifs = nullptr; err = GetDiagnosticDataProvider().GetNetworkInterfaces(&netifs); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, netifs != nullptr); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_NE(netifs, nullptr); GetDiagnosticDataProvider().ReleaseNetworkInterfaces(netifs); } - -/** - * Test Suite. It lists all the test functions. - */ -static const nlTest sTests[] = { - - NL_TEST_DEF("Test PlatformMgr::Init", TestPlatformMgr_Init), - NL_TEST_DEF("Test ConfigurationMgr::GetNetworkInterfaces", TestConnectivityMgr_GetNetworkInterfaces), NL_TEST_SENTINEL() -}; - -/** - * Set up the test suite. - */ -int TestConnectivityMgr_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int TestConnectivityMgr_Teardown(void * inContext) -{ - PlatformMgr().Shutdown(); - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -int TestConnectivityMgr() -{ - nlTestSuite theSuite = { "ConfigurationMgr tests", &sTests[0], TestConnectivityMgr_Setup, TestConnectivityMgr_Teardown }; - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestConnectivityMgr) diff --git a/src/platform/tests/TestDnssd.cpp b/src/platform/tests/TestDnssd.cpp index 09929068731bf7..43a3d62d61dc9a 100644 --- a/src/platform/tests/TestDnssd.cpp +++ b/src/platform/tests/TestDnssd.cpp @@ -17,7 +17,7 @@ #include -#include +#include #include "lib/dnssd/platform/Dnssd.h" #include "platform/CHIPDeviceLayer.h" @@ -34,8 +34,6 @@ #include #include #include -#include -#include using chip::Dnssd::DnssdService; using chip::Dnssd::DnssdServiceProtocol; @@ -43,19 +41,6 @@ using chip::Dnssd::TextEntry; namespace { -struct DnssdContext -{ - nlTestSuite * mTestSuite; - - std::atomic mTimeoutExpired{ false }; - - intptr_t mBrowseIdentifier = 0; - - unsigned int mBrowsedServicesCount = 0; - unsigned int mResolvedServicesCount = 0; - bool mEndOfInput = false; -}; - class TestDnssdResolveServerDelegate : public mdns::Minimal::ServerDelegate, public mdns::Minimal::ParserDelegate { public: @@ -87,9 +72,32 @@ class TestDnssdResolveServerDelegate : public mdns::Minimal::ServerDelegate, pub } // namespace +class TestDnssd : public ::testing::Test +{ +public: // protected + static void SetUpTestSuite() + { + EXPECT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); + EXPECT_EQ(chip::DeviceLayer::PlatformMgr().InitChipStack(), CHIP_NO_ERROR); + } + static void TearDownTestSuite() + { + chip::DeviceLayer::PlatformMgr().Shutdown(); + chip::Platform::MemoryShutdown(); + } + + std::atomic mTimeoutExpired{ false }; + + intptr_t mBrowseIdentifier = 0; + + unsigned int mBrowsedServicesCount = 0; + unsigned int mResolvedServicesCount = 0; + bool mEndOfInput = false; +}; + static void Timeout(chip::System::Layer * systemLayer, void * context) { - auto * ctx = static_cast(context); + auto * ctx = static_cast(context); ChipLogError(DeviceLayer, "mDNS test timeout, is avahi daemon running?"); ctx->mTimeoutExpired = true; chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); @@ -98,16 +106,11 @@ static void Timeout(chip::System::Layer * systemLayer, void * context) static void HandleResolve(void * context, DnssdService * result, const chip::Span & addresses, CHIP_ERROR error) { - auto * ctx = static_cast(context); - auto * suite = ctx->mTestSuite; + auto * ctx = static_cast(context); char addrBuf[100]; - NL_TEST_EXIT_ON_FAILED_ASSERT(suite, result != nullptr); - NL_TEST_ASSERT(suite, error == CHIP_NO_ERROR); - - // The NL_TEST_ASSERT above will not abort the test, so we need to - // explicitly abort it here to avoid dereferencing a null pointer. - VerifyOrReturn(result != nullptr, ); + EXPECT_NE(result, nullptr); + EXPECT_EQ(error, CHIP_NO_ERROR); if (!addresses.empty()) { @@ -115,9 +118,9 @@ static void HandleResolve(void * context, DnssdService * result, const chip::Spa printf("Service[%u] at [%s]:%u\n", ctx->mResolvedServicesCount, addrBuf, result->mPort); } - NL_TEST_ASSERT(suite, result->mTextEntrySize == 1); - NL_TEST_ASSERT(suite, strcmp(result->mTextEntries[0].mKey, "key") == 0); - NL_TEST_ASSERT(suite, strcmp(reinterpret_cast(result->mTextEntries[0].mData), "val") == 0); + EXPECT_EQ(result->mTextEntrySize, 1u); + EXPECT_STREQ(result->mTextEntries[0].mKey, "key"); + EXPECT_STREQ(reinterpret_cast(result->mTextEntries[0].mData), "val"); if (ctx->mBrowsedServicesCount == ++ctx->mResolvedServicesCount) { @@ -137,14 +140,13 @@ static void HandleResolve(void * context, DnssdService * result, const chip::Spa static void HandleBrowse(void * context, DnssdService * services, size_t servicesSize, bool finalBrowse, CHIP_ERROR error) { - auto * ctx = static_cast(context); - auto * suite = ctx->mTestSuite; + auto * ctx = static_cast(context); // Make sure that we will not be called again after end-of-input is set - NL_TEST_ASSERT(suite, ctx->mEndOfInput == false); + EXPECT_FALSE(ctx->mEndOfInput); // Cancelled error is expected when the browse is stopped with // ChipDnssdStopBrowse(), so we will not assert on it. - NL_TEST_ASSERT(suite, error == CHIP_NO_ERROR || error == CHIP_ERROR_CANCELLED); + EXPECT_TRUE(error == CHIP_NO_ERROR || error == CHIP_ERROR_CANCELLED); ctx->mBrowsedServicesCount += servicesSize; ctx->mEndOfInput = finalBrowse; @@ -156,27 +158,24 @@ static void HandleBrowse(void * context, DnssdService * services, size_t service { printf("Service[%u] name %s\n", i, services[i].mName); printf("Service[%u] type %s\n", i, services[i].mType); - NL_TEST_ASSERT(suite, ChipDnssdResolve(&services[i], services[i].mInterface, HandleResolve, context) == CHIP_NO_ERROR); + EXPECT_EQ(ChipDnssdResolve(&services[i], services[i].mInterface, HandleResolve, context), CHIP_NO_ERROR); } } } static void DnssdErrorCallback(void * context, CHIP_ERROR error) { - auto * ctx = static_cast(context); - NL_TEST_ASSERT(ctx->mTestSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); } void TestDnssdBrowse_DnssdInitCallback(void * context, CHIP_ERROR error) { - auto * ctx = static_cast(context); - NL_TEST_ASSERT(ctx->mTestSuite, error == CHIP_NO_ERROR); - auto * suite = ctx->mTestSuite; - - NL_TEST_ASSERT(suite, - ChipDnssdBrowse("_mock", DnssdServiceProtocol::kDnssdProtocolUdp, chip::Inet::IPAddressType::kAny, - chip::Inet::InterfaceId::Null(), HandleBrowse, context, - &ctx->mBrowseIdentifier) == CHIP_NO_ERROR); + auto * ctx = static_cast(context); + EXPECT_EQ(error, CHIP_NO_ERROR); + + EXPECT_EQ(ChipDnssdBrowse("_mock", DnssdServiceProtocol::kDnssdProtocolUdp, chip::Inet::IPAddressType::kAny, + chip::Inet::InterfaceId::Null(), HandleBrowse, context, &ctx->mBrowseIdentifier), + CHIP_NO_ERROR); } // Verify that platform DNS-SD implementation can browse and resolve services. @@ -186,11 +185,8 @@ void TestDnssdBrowse_DnssdInitCallback(void * context, CHIP_ERROR error) // A and AAAA queries without additional records. In order to pass this test, // the platform DNS-SD client implementation must be able to browse and resolve // services by querying for all of these records separately. -void TestDnssdBrowse(nlTestSuite * inSuite, void * inContext) +TEST_F(TestDnssd, TestDnssdBrowse) { - DnssdContext context; - context.mTestSuite = inSuite; - mdns::Minimal::SetDefaultAddressPolicy(); mdns::Minimal::Server<10> server; @@ -229,38 +225,33 @@ void TestDnssdBrowse(nlTestSuite * inSuite, void * inContext) server.SetDelegate(&delegate); auto endpoints = mdns::Minimal::GetAddressPolicy()->GetListenEndpoints(); - NL_TEST_ASSERT(inSuite, server.Listen(chip::DeviceLayer::UDPEndPointManager(), endpoints.get(), 5353) == CHIP_NO_ERROR); + EXPECT_EQ(server.Listen(chip::DeviceLayer::UDPEndPointManager(), endpoints.get(), 5353), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - chip::Dnssd::ChipDnssdInit(TestDnssdBrowse_DnssdInitCallback, DnssdErrorCallback, &context) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(5), Timeout, &context) == - CHIP_NO_ERROR); + EXPECT_EQ(chip::Dnssd::ChipDnssdInit(TestDnssdBrowse_DnssdInitCallback, DnssdErrorCallback, this), CHIP_NO_ERROR); + EXPECT_EQ(chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(5), Timeout, this), CHIP_NO_ERROR); ChipLogProgress(DeviceLayer, "Start EventLoop"); chip::DeviceLayer::PlatformMgr().RunEventLoop(); ChipLogProgress(DeviceLayer, "End EventLoop"); - NL_TEST_ASSERT(inSuite, context.mResolvedServicesCount > 0); - NL_TEST_ASSERT(inSuite, !context.mTimeoutExpired); + EXPECT_GT(mResolvedServicesCount, 0u); + EXPECT_FALSE(mTimeoutExpired); // Stop browsing so we can safely shutdown DNS-SD - chip::Dnssd::ChipDnssdStopBrowse(context.mBrowseIdentifier); + chip::Dnssd::ChipDnssdStopBrowse(mBrowseIdentifier); chip::Dnssd::ChipDnssdShutdown(); } static void HandlePublish(void * context, const char * type, const char * instanceName, CHIP_ERROR error) { - auto * ctx = static_cast(context); - NL_TEST_ASSERT(ctx->mTestSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); } static void TestDnssdPublishService_DnssdInitCallback(void * context, CHIP_ERROR error) { - auto * ctx = static_cast(context); - NL_TEST_ASSERT(ctx->mTestSuite, error == CHIP_NO_ERROR); - auto * suite = ctx->mTestSuite; + auto * ctx = static_cast(context); + EXPECT_EQ(error, CHIP_NO_ERROR); DnssdService service{}; TextEntry entry{ "key", reinterpret_cast("val"), 3 }; @@ -277,12 +268,11 @@ static void TestDnssdPublishService_DnssdInitCallback(void * context, CHIP_ERROR service.mSubTypes = nullptr; service.mSubTypeSize = 0; - NL_TEST_ASSERT(suite, ChipDnssdPublishService(&service, HandlePublish, context) == CHIP_NO_ERROR); + EXPECT_EQ(ChipDnssdPublishService(&service, HandlePublish, nullptr), CHIP_NO_ERROR); - NL_TEST_ASSERT(suite, - ChipDnssdBrowse("_mock", DnssdServiceProtocol::kDnssdProtocolTcp, chip::Inet::IPAddressType::kAny, - chip::Inet::InterfaceId::Null(), HandleBrowse, context, - &ctx->mBrowseIdentifier) == CHIP_NO_ERROR); + EXPECT_EQ(ChipDnssdBrowse("_mock", DnssdServiceProtocol::kDnssdProtocolTcp, chip::Inet::IPAddressType::kAny, + chip::Inet::InterfaceId::Null(), HandleBrowse, context, &ctx->mBrowseIdentifier), + CHIP_NO_ERROR); } // Verify that the platform DNS-SD implementation can publish services. @@ -290,58 +280,20 @@ static void TestDnssdPublishService_DnssdInitCallback(void * context, CHIP_ERROR // This test uses platform implementation of DNS-SD server and client. Since // client implementation should be verified by the TestDnssdBrowse test case, // here we only verify that the server implementation can publish services. -void TestDnssdPublishService(nlTestSuite * inSuite, void * inContext) +TEST_F(TestDnssd, TestDnssdPublishService) { - DnssdContext context; - context.mTestSuite = inSuite; - - NL_TEST_ASSERT(inSuite, - chip::Dnssd::ChipDnssdInit(TestDnssdPublishService_DnssdInitCallback, DnssdErrorCallback, &context) == - CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(5), Timeout, &context) == - CHIP_NO_ERROR); + EXPECT_EQ(chip::Dnssd::ChipDnssdInit(TestDnssdPublishService_DnssdInitCallback, DnssdErrorCallback, this), CHIP_NO_ERROR); + EXPECT_EQ(chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds32(5), Timeout, this), CHIP_NO_ERROR); ChipLogProgress(DeviceLayer, "Start EventLoop"); chip::DeviceLayer::PlatformMgr().RunEventLoop(); ChipLogProgress(DeviceLayer, "End EventLoop"); - NL_TEST_ASSERT(inSuite, context.mResolvedServicesCount > 0); - NL_TEST_ASSERT(inSuite, !context.mTimeoutExpired); + EXPECT_GT(mResolvedServicesCount, 0u); + EXPECT_FALSE(mTimeoutExpired); // Stop browsing so we can safely shutdown DNS-SD - chip::Dnssd::ChipDnssdStopBrowse(context.mBrowseIdentifier); + chip::Dnssd::ChipDnssdStopBrowse(mBrowseIdentifier); chip::Dnssd::ChipDnssdShutdown(); } - -static const nlTest sTests[] = { - NL_TEST_DEF("Test ChipDnssdBrowse", TestDnssdBrowse), - NL_TEST_DEF("Test ChipDnssdPublishService", TestDnssdPublishService), - NL_TEST_SENTINEL(), -}; - -int TestDnssd_Setup(void * inContext) -{ - VerifyOrReturnError(chip::Platform::MemoryInit() == CHIP_NO_ERROR, FAILURE); - VerifyOrReturnError(chip::DeviceLayer::PlatformMgr().InitChipStack() == CHIP_NO_ERROR, FAILURE); - return SUCCESS; -} - -int TestDnssd_Teardown(void * inContext) -{ - chip::DeviceLayer::PlatformMgr().Shutdown(); - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -int TestDnssd() -{ - nlTestSuite theSuite = { "CHIP DeviceLayer mDNS tests", &sTests[0], TestDnssd_Setup, TestDnssd_Teardown }; - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestDnssd); diff --git a/src/platform/tests/TestKeyValueStoreMgr.cpp b/src/platform/tests/TestKeyValueStoreMgr.cpp index 846de5bb2deb5b..49ddcb99752492 100644 --- a/src/platform/tests/TestKeyValueStoreMgr.cpp +++ b/src/platform/tests/TestKeyValueStoreMgr.cpp @@ -22,10 +22,9 @@ * */ -#include +#include #include -#include #include #include @@ -34,7 +33,19 @@ using namespace chip; using namespace chip::DeviceLayer; using namespace chip::DeviceLayer::PersistedStorage; -static void TestKeyValueStoreMgr_EmptyString(nlTestSuite * inSuite, void * inContext) +struct TestKeyValueStoreMgr : public ::testing::Test +{ + + static void SetUpTestSuite() + { + CHIP_ERROR err = chip::Platform::MemoryInit(); + EXPECT_EQ(err, CHIP_NO_ERROR); + } + + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestKeyValueStoreMgr, EmptyString) { static constexpr char kTestKey[] = "str_key"; static constexpr char kTestValue[] = ""; @@ -44,32 +55,32 @@ static void TestKeyValueStoreMgr_EmptyString(nlTestSuite * inSuite, void * inCon size_t readSize; CHIP_ERROR err = KeyValueStoreMgr().Put(kTestKey, kTestValue, kTestValueLen); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Verify if read value is the same as wrote one err = KeyValueStoreMgr().Get(kTestKey, readValue, sizeof(readValue), &readSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, readSize == kTestValueLen); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(readSize, kTestValueLen); // Verify that read succeeds even if 0-length buffer is provided err = KeyValueStoreMgr().Get(kTestKey, readValue, 0, &readSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, readSize == kTestValueLen); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(readSize, kTestValueLen); err = KeyValueStoreMgr().Get(kTestKey, nullptr, 0, &readSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, readSize == kTestValueLen); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(readSize, kTestValueLen); // Verify deletion err = KeyValueStoreMgr().Delete(kTestKey); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Try to get deleted key and verify if CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND is returned err = KeyValueStoreMgr().Get(kTestKey, readValue, sizeof(readValue), &readSize); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(err, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } -static void TestKeyValueStoreMgr_String(nlTestSuite * inSuite, void * inContext) +TEST_F(TestKeyValueStoreMgr, String) { static constexpr char kTestKey[] = "str_key"; static constexpr char kTestValue[] = "test_value"; @@ -78,24 +89,24 @@ static void TestKeyValueStoreMgr_String(nlTestSuite * inSuite, void * inContext) size_t readSize; CHIP_ERROR err = KeyValueStoreMgr().Put(kTestKey, kTestValue); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Verify if read value is the same as wrote one err = KeyValueStoreMgr().Get(kTestKey, readValue, sizeof(readValue), &readSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, strcmp(kTestValue, readValue) == 0); - NL_TEST_ASSERT(inSuite, readSize == sizeof(kTestValue)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_STREQ(kTestValue, readValue); + EXPECT_EQ(readSize, sizeof(kTestValue)); // Verify deletion err = KeyValueStoreMgr().Delete(kTestKey); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Try to get deleted key and verify if CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND is returned err = KeyValueStoreMgr().Get(kTestKey, readValue, sizeof(readValue), &readSize); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(err, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } -static void TestKeyValueStoreMgr_Uint32(nlTestSuite * inSuite, void * inContext) +TEST_F(TestKeyValueStoreMgr, Uint32) { static constexpr char kTestKey[] = "uint32_key"; constexpr const uint32_t kTestValue = 5; @@ -103,23 +114,23 @@ static void TestKeyValueStoreMgr_Uint32(nlTestSuite * inSuite, void * inContext) uint32_t readValue = UINT32_MAX; CHIP_ERROR err = KeyValueStoreMgr().Put(kTestKey, kTestValue); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Verify if read value is the same as wrote one err = KeyValueStoreMgr().Get(kTestKey, &readValue); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, kTestValue == readValue); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(kTestValue, readValue); // Verify deletion err = KeyValueStoreMgr().Delete(kTestKey); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Try to get deleted key and verify if CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND is returned err = KeyValueStoreMgr().Get(kTestKey, &readValue); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(err, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } -static void TestKeyValueStoreMgr_Array(nlTestSuite * inSuite, void * inContext) +TEST_F(TestKeyValueStoreMgr, Array) { static constexpr char kTestKey[] = "array_key"; constexpr uint32_t kTestValue[5] = { 1, 2, 3, 4, 5 }; @@ -128,24 +139,24 @@ static void TestKeyValueStoreMgr_Array(nlTestSuite * inSuite, void * inContext) size_t readSize; CHIP_ERROR err = KeyValueStoreMgr().Put(kTestKey, kTestValue); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Verify if read value is the same as wrote one err = KeyValueStoreMgr().Get(kTestKey, readValue, sizeof(readValue), &readSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(kTestValue, readValue, sizeof(kTestValue)) == 0); - NL_TEST_ASSERT(inSuite, readSize == sizeof(kTestValue)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(memcmp(kTestValue, readValue, sizeof(kTestValue)), 0); + EXPECT_EQ(readSize, sizeof(kTestValue)); // Verify deletion err = KeyValueStoreMgr().Delete(kTestKey); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Try to get deleted key and verify if CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND is returned err = KeyValueStoreMgr().Get(kTestKey, readValue, sizeof(readValue), &readSize); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(err, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } -static void TestKeyValueStoreMgr_Struct(nlTestSuite * inSuite, void * inContext) +TEST_F(TestKeyValueStoreMgr, Struct) { struct TestStruct { @@ -160,25 +171,25 @@ static void TestKeyValueStoreMgr_Struct(nlTestSuite * inSuite, void * inContext) size_t readSize; CHIP_ERROR err = KeyValueStoreMgr().Put(kTestKey, kTestValue); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Verify if read value is the same as wrote one err = KeyValueStoreMgr().Get(kTestKey, &readValue, sizeof(readValue), &readSize); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, kTestValue.value1 == readValue.value1); - NL_TEST_ASSERT(inSuite, kTestValue.value2 == readValue.value2); - NL_TEST_ASSERT(inSuite, readSize == sizeof(kTestValue)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(kTestValue.value1, readValue.value1); + EXPECT_EQ(kTestValue.value2, readValue.value2); + EXPECT_EQ(readSize, sizeof(kTestValue)); // Verify deletion err = KeyValueStoreMgr().Delete(kTestKey); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Try to get deleted key and verify if CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND is returned err = KeyValueStoreMgr().Get(kTestKey, &readValue, sizeof(readValue), &readSize); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(err, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } -static void TestKeyValueStoreMgr_UpdateValue(nlTestSuite * inSuite, void * inContext) +TEST_F(TestKeyValueStoreMgr, UpdateValue) { static constexpr char kTestKey[] = "update_key"; @@ -188,18 +199,18 @@ static void TestKeyValueStoreMgr_UpdateValue(nlTestSuite * inSuite, void * inCon for (uint32_t i = 0; i < 10; i++) { err = KeyValueStoreMgr().Put(kTestKey, i); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = KeyValueStoreMgr().Get(kTestKey, &readValue); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, i == readValue); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(i, readValue); } err = KeyValueStoreMgr().Delete(kTestKey); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -static void TestKeyValueStoreMgr_TooSmallBufferRead(nlTestSuite * inSuite, void * inContext) +TEST_F(TestKeyValueStoreMgr, TooSmallBufferRead) { static constexpr char kTestKey[] = "too_small_buffer_read_key"; constexpr uint8_t kTestValue[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; @@ -208,19 +219,19 @@ static void TestKeyValueStoreMgr_TooSmallBufferRead(nlTestSuite * inSuite, void size_t readSize; CHIP_ERROR err = KeyValueStoreMgr().Put(kTestKey, kTestValue); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Returns buffer too small and should read as many bytes as possible err = KeyValueStoreMgr().Get(kTestKey, &readValue, sizeof(readValue), &readSize, 0); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); - NL_TEST_ASSERT(inSuite, readSize == sizeof(readValue)); - NL_TEST_ASSERT(inSuite, memcmp(kTestValue, readValue, readSize) == 0); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(readSize, sizeof(readValue)); + EXPECT_EQ(memcmp(kTestValue, readValue, readSize), 0); err = KeyValueStoreMgr().Delete(kTestKey); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -static void TestKeyValueStoreMgr_AllCharactersKey(nlTestSuite * inSuite, void * inContext) +TEST_F(TestKeyValueStoreMgr, AllCharactersKey) { // Test that all printable characters [0x20 - 0x7f) can be part of the key constexpr size_t kKeyLength = 32; @@ -241,33 +252,33 @@ static void TestKeyValueStoreMgr_AllCharactersKey(nlTestSuite * inSuite, void * memcpy(testKey, &allChars[charId], chip::min(sizeof(allChars) - charId, kKeyLength)); CHIP_ERROR err = KeyValueStoreMgr().Put(testKey, kTestValue); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t readValue = UINT32_MAX; err = KeyValueStoreMgr().Get(testKey, &readValue); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = KeyValueStoreMgr().Delete(testKey); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } } -static void TestKeyValueStoreMgr_NonExistentDelete(nlTestSuite * inSuite, void * inContext) +TEST_F(TestKeyValueStoreMgr, NonExistentDelete) { static constexpr char kTestKey[] = "non_existent"; CHIP_ERROR err = KeyValueStoreMgr().Delete(kTestKey); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(err, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } #if !defined(__ZEPHYR__) && !defined(__MBED__) -static void TestKeyValueStoreMgr_MultiRead(nlTestSuite * inSuite, void * inContext) +TEST_F(TestKeyValueStoreMgr, MultiRead) { static constexpr char kTestKey[] = "multi_key"; constexpr uint32_t kTestValue[5] = { 1, 2, 3, 4, 5 }; CHIP_ERROR err = KeyValueStoreMgr().Put(kTestKey, kTestValue); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); for (uint32_t i = 0; i < 5; i++) { @@ -276,86 +287,33 @@ static void TestKeyValueStoreMgr_MultiRead(nlTestSuite * inSuite, void * inConte // Returns buffer too small for all but the last read. err = KeyValueStoreMgr().Get(kTestKey, &readValue, sizeof(readValue), &readSize, i * sizeof(uint32_t)); - NL_TEST_ASSERT(inSuite, err == (i < 4 ? CHIP_ERROR_BUFFER_TOO_SMALL : CHIP_NO_ERROR)); - NL_TEST_ASSERT(inSuite, readSize == sizeof(readValue)); - NL_TEST_ASSERT(inSuite, kTestValue[i] == readValue); + EXPECT_EQ(err, (i < 4 ? CHIP_ERROR_BUFFER_TOO_SMALL : CHIP_NO_ERROR)); + EXPECT_EQ(readSize, sizeof(readValue)); + EXPECT_EQ(kTestValue[i], readValue); } err = KeyValueStoreMgr().Delete(kTestKey); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } #endif #ifdef __ZEPHYR__ -static void TestKeyValueStoreMgr_DoFactoryReset(nlTestSuite * inSuite, void * inContext) +TEST_F(TestKeyValueStoreMgr, DoFactoryReset) { static constexpr char kStrKey[] = "string_with_weird_chars\\=_key"; static constexpr char kUintKey[] = "some_uint_key"; - NL_TEST_ASSERT(inSuite, KeyValueStoreMgr().Put(kStrKey, "some_string") == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, KeyValueStoreMgr().Put(kUintKey, uint32_t(1234)) == CHIP_NO_ERROR); + EXPECT_EQ(KeyValueStoreMgr().Put(kStrKey, "some_string"), CHIP_NO_ERROR); + EXPECT_EQ(KeyValueStoreMgr().Put(kUintKey, uint32_t(1234)), CHIP_NO_ERROR); char readString[16]; uint32_t readValue; - NL_TEST_ASSERT(inSuite, KeyValueStoreMgr().Get(kStrKey, readString, sizeof(readString)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, KeyValueStoreMgr().Get(kUintKey, &readValue) == CHIP_NO_ERROR); + EXPECT_EQ(KeyValueStoreMgr().Get(kStrKey, readString, sizeof(readString)), CHIP_NO_ERROR); + EXPECT_EQ(KeyValueStoreMgr().Get(kUintKey, &readValue), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, KeyValueStoreMgrImpl().DoFactoryReset() == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - KeyValueStoreMgr().Get(kStrKey, readString, sizeof(readString)) == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); - NL_TEST_ASSERT(inSuite, KeyValueStoreMgr().Get(kUintKey, &readValue) == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(KeyValueStoreMgrImpl().DoFactoryReset(), CHIP_NO_ERROR); + EXPECT_EQ(KeyValueStoreMgr().Get(kStrKey, readString, sizeof(readString)), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(KeyValueStoreMgr().Get(kUintKey, &readValue), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } #endif -/** - * Test Suite. It lists all the test functions. - */ -static const nlTest sTests[] = { NL_TEST_DEF("Test KeyValueStoreMgr_EmptyString", TestKeyValueStoreMgr_EmptyString), - NL_TEST_DEF("Test KeyValueStoreMgr_String", TestKeyValueStoreMgr_String), - NL_TEST_DEF("Test KeyValueStoreMgr_Uint32", TestKeyValueStoreMgr_Uint32), - NL_TEST_DEF("Test KeyValueStoreMgr_Array", TestKeyValueStoreMgr_Array), - NL_TEST_DEF("Test KeyValueStoreMgr_Struct", TestKeyValueStoreMgr_Struct), - NL_TEST_DEF("Test KeyValueStoreMgr_UpdateValue", TestKeyValueStoreMgr_UpdateValue), - NL_TEST_DEF("Test KeyValueStoreMgr_TooSmallBufferRead", TestKeyValueStoreMgr_TooSmallBufferRead), - NL_TEST_DEF("Test KeyValueStoreMgr_AllCharactersKey", TestKeyValueStoreMgr_AllCharactersKey), - NL_TEST_DEF("Test KeyValueStoreMgr_NonExistentDelete", TestKeyValueStoreMgr_NonExistentDelete), -#if !defined(__ZEPHYR__) && !defined(__MBED__) - // Zephyr and Mbed platforms do not support partial or offset reads yet. - NL_TEST_DEF("Test KeyValueStoreMgr_MultiRead", TestKeyValueStoreMgr_MultiRead), -#endif -#ifdef __ZEPHYR__ - NL_TEST_DEF("Test TestKeyValueStoreMgr_DoFactoryReset", TestKeyValueStoreMgr_DoFactoryReset), -#endif - NL_TEST_SENTINEL() }; - -/** - * Set up the test suite. - */ -int TestKeyValueStoreMgr_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int TestKeyValueStoreMgr_Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -int TestKeyValueStoreMgr() -{ - nlTestSuite theSuite = { "KeyValueStoreMgr tests", &sTests[0], TestKeyValueStoreMgr_Setup, TestKeyValueStoreMgr_Teardown }; - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestKeyValueStoreMgr); diff --git a/src/platform/tests/TestPlatformMgr.cpp b/src/platform/tests/TestPlatformMgr.cpp index 87c7913ebb7c3b..96c989aa7455b2 100644 --- a/src/platform/tests/TestPlatformMgr.cpp +++ b/src/platform/tests/TestPlatformMgr.cpp @@ -30,12 +30,10 @@ #include +#include #include #include -#include -#include #include -#include #include #include @@ -49,24 +47,41 @@ using namespace chip::DeviceLayer; // Unit tests // ================================= -static void TestPlatformMgr_InitShutdown(nlTestSuite * inSuite, void * inContext) +class TestPlatformMgr : public ::testing::Test +{ +public: + static void SetUpTestSuite() + { + CHIP_ERROR error = chip::Platform::MemoryInit(); + EXPECT_EQ(error, CHIP_NO_ERROR); + + // Set up a fake commissionable data provider since required by internals of several + // Device/SystemLayer components. + static chip::DeviceLayer::TestOnlyCommissionableDataProvider commissionable_data_provider; + chip::DeviceLayer::SetCommissionableDataProvider(&commissionable_data_provider); + } + + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestPlatformMgr, InitShutdown) { CHIP_ERROR err = PlatformMgr().InitChipStack(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); PlatformMgr().Shutdown(); } -static void TestPlatformMgr_BasicEventLoopTask(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPlatformMgr, BasicEventLoopTask) { std::atomic counterRun{ 0 }; - NL_TEST_ASSERT_SUCCESS(inSuite, PlatformMgr().InitChipStack()); + EXPECT_EQ(PlatformMgr().InitChipStack(), CHIP_NO_ERROR); // Start/stop the event loop task a few times. for (size_t i = 0; i < 3; i++) { - NL_TEST_ASSERT_SUCCESS(inSuite, PlatformMgr().StartEventLoopTask()); + EXPECT_EQ(PlatformMgr().StartEventLoopTask(), CHIP_NO_ERROR); std::atomic counterSync{ 2 }; @@ -98,7 +113,7 @@ static void TestPlatformMgr_BasicEventLoopTask(nlTestSuite * inSuite, void * inC for (size_t t = 0; counterSync != 0 && t < 1000; t++) chip::test_utils::SleepMillis(1); - NL_TEST_ASSERT_SUCCESS(inSuite, PlatformMgr().StopEventLoopTask()); + EXPECT_EQ(PlatformMgr().StopEventLoopTask(), CHIP_NO_ERROR); // Sleep for a short time to allow the event loop to stop. // Note, in some platform implementations the event loop thread @@ -107,7 +122,7 @@ static void TestPlatformMgr_BasicEventLoopTask(nlTestSuite * inSuite, void * inC chip::test_utils::SleepMillis(10); } - NL_TEST_ASSERT(inSuite, counterRun == (3 * 2)); + EXPECT_EQ(counterRun, (3 * 2)); PlatformMgr().Shutdown(); } @@ -123,18 +138,18 @@ static void StopTheLoop(intptr_t) stopResult = PlatformMgr().StopEventLoopTask(); } -static void TestPlatformMgr_BasicRunEventLoop(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPlatformMgr, BasicRunEventLoop) { stopRan = false; - NL_TEST_ASSERT_SUCCESS(inSuite, PlatformMgr().InitChipStack()); + EXPECT_EQ(PlatformMgr().InitChipStack(), CHIP_NO_ERROR); PlatformMgr().ScheduleWork(StopTheLoop); - NL_TEST_ASSERT(inSuite, !stopRan); + EXPECT_FALSE(stopRan); PlatformMgr().RunEventLoop(); - NL_TEST_ASSERT(inSuite, stopRan); - NL_TEST_ASSERT_SUCCESS(inSuite, stopResult); + EXPECT_TRUE(stopRan); + EXPECT_EQ(stopResult, CHIP_NO_ERROR); PlatformMgr().Shutdown(); } @@ -147,51 +162,48 @@ static void SleepSome(intptr_t) sleepRan = true; } -static void TestPlatformMgr_RunEventLoopTwoTasks(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPlatformMgr, RunEventLoopTwoTasks) { stopRan = false; sleepRan = false; - NL_TEST_ASSERT_SUCCESS(inSuite, PlatformMgr().InitChipStack()); + EXPECT_EQ(PlatformMgr().InitChipStack(), CHIP_NO_ERROR); PlatformMgr().ScheduleWork(SleepSome); PlatformMgr().ScheduleWork(StopTheLoop); - NL_TEST_ASSERT(inSuite, !stopRan); - NL_TEST_ASSERT(inSuite, !sleepRan); + EXPECT_FALSE(stopRan); + EXPECT_FALSE(sleepRan); PlatformMgr().RunEventLoop(); - NL_TEST_ASSERT(inSuite, stopRan); - NL_TEST_ASSERT(inSuite, sleepRan); + EXPECT_TRUE(stopRan); + EXPECT_TRUE(sleepRan); PlatformMgr().Shutdown(); } -void StopAndSleep(intptr_t arg) -{ - // Ensure that we don't proceed after stopping until the sleep is done too. - StopTheLoop(arg); - SleepSome(arg); -} - -static void TestPlatformMgr_RunEventLoopStopBeforeSleep(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPlatformMgr, RunEventLoopStopBeforeSleep) { stopRan = false; sleepRan = false; - NL_TEST_ASSERT_SUCCESS(inSuite, PlatformMgr().InitChipStack()); + EXPECT_EQ(PlatformMgr().InitChipStack(), CHIP_NO_ERROR); - PlatformMgr().ScheduleWork(StopAndSleep); + PlatformMgr().ScheduleWork([](intptr_t arg) { + // Ensure that we don't proceed after stopping until the sleep is done too. + StopTheLoop(arg); + SleepSome(arg); + }); - NL_TEST_ASSERT(inSuite, !stopRan); - NL_TEST_ASSERT(inSuite, !sleepRan); + EXPECT_FALSE(stopRan); + EXPECT_FALSE(sleepRan); PlatformMgr().RunEventLoop(); - NL_TEST_ASSERT(inSuite, stopRan); - NL_TEST_ASSERT(inSuite, sleepRan); + EXPECT_TRUE(stopRan); + EXPECT_TRUE(sleepRan); PlatformMgr().Shutdown(); } -static void TestPlatformMgr_TryLockChipStack(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPlatformMgr, TryLockChipStack) { bool locked = PlatformMgr().TryLockChipStack(); if (locked) @@ -202,22 +214,14 @@ static int sEventRecieved = 0; void DeviceEventHandler(const ChipDeviceEvent * event, intptr_t arg) { - // NL_TEST_ASSERT(inSuite, arg == 12345); + EXPECT_EQ(arg, 12345); sEventRecieved++; } -static void TestPlatformMgr_AddEventHandler(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPlatformMgr, AddEventHandler) { sEventRecieved = 0; - NL_TEST_ASSERT_SUCCESS(inSuite, PlatformMgr().AddEventHandler(DeviceEventHandler, 12345)); - -#if 0 - while (sEventRecieved == 0) - { - } - - NL_TEST_ASSERT(inSuite, sEventRecieved > 0); -#endif + EXPECT_EQ(PlatformMgr().AddEventHandler(DeviceEventHandler, 12345), CHIP_NO_ERROR); } class MockSystemLayer : public System::LayerImpl @@ -233,76 +237,21 @@ class MockSystemLayer : public System::LayerImpl } }; -static void TestPlatformMgr_MockSystemLayer(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPlatformMgr, MockSystemLayerTest) { MockSystemLayer systemLayer; DeviceLayer::SetSystemLayerForTesting(&systemLayer); - NL_TEST_ASSERT(inSuite, &DeviceLayer::SystemLayer() == static_cast(&systemLayer)); + EXPECT_EQ(&DeviceLayer::SystemLayer(), static_cast(&systemLayer)); CHIP_ERROR err = PlatformMgr().InitChipStack(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, &DeviceLayer::SystemLayer() == static_cast(&systemLayer)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(&DeviceLayer::SystemLayer(), static_cast(&systemLayer)); - NL_TEST_ASSERT( - inSuite, DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::kZero, nullptr, nullptr) == CHIP_APPLICATION_ERROR(1)); - NL_TEST_ASSERT(inSuite, DeviceLayer::SystemLayer().ScheduleWork(nullptr, nullptr) == CHIP_APPLICATION_ERROR(2)); + EXPECT_EQ(DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::kZero, nullptr, nullptr), CHIP_APPLICATION_ERROR(1)); + EXPECT_EQ(DeviceLayer::SystemLayer().ScheduleWork(nullptr, nullptr), CHIP_APPLICATION_ERROR(2)); PlatformMgr().Shutdown(); DeviceLayer::SetSystemLayerForTesting(nullptr); } - -/** - * Test Suite. It lists all the test functions. - */ -static const nlTest sTests[] = { - - NL_TEST_DEF("Test PlatformMgr::Init/Shutdown", TestPlatformMgr_InitShutdown), - NL_TEST_DEF("Test basic PlatformMgr::StartEventLoopTask", TestPlatformMgr_BasicEventLoopTask), - NL_TEST_DEF("Test basic PlatformMgr::RunEventLoop", TestPlatformMgr_BasicRunEventLoop), - NL_TEST_DEF("Test PlatformMgr::RunEventLoop with two tasks", TestPlatformMgr_RunEventLoopTwoTasks), - NL_TEST_DEF("Test PlatformMgr::RunEventLoop with stop before sleep", TestPlatformMgr_RunEventLoopStopBeforeSleep), - NL_TEST_DEF("Test PlatformMgr::TryLockChipStack", TestPlatformMgr_TryLockChipStack), - NL_TEST_DEF("Test PlatformMgr::AddEventHandler", TestPlatformMgr_AddEventHandler), - NL_TEST_DEF("Test mock System::Layer", TestPlatformMgr_MockSystemLayer), - - NL_TEST_SENTINEL() -}; - -/** - * Set up the test suite. - */ -int TestPlatformMgr_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - - // Setup a fake commissionable data provider since required by internals of several - // Device/SystemLayer components. - static chip::DeviceLayer::TestOnlyCommissionableDataProvider commissionable_data_provider; - chip::DeviceLayer::SetCommissionableDataProvider(&commissionable_data_provider); - - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int TestPlatformMgr_Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -int TestPlatformMgr() -{ - nlTestSuite theSuite = { "PlatformMgr tests", &sTests[0], TestPlatformMgr_Setup, TestPlatformMgr_Teardown }; - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestPlatformMgr); diff --git a/src/platform/tests/TestPlatformTime.cpp b/src/platform/tests/TestPlatformTime.cpp index aa7c931dd67782..54cf60202b4440 100644 --- a/src/platform/tests/TestPlatformTime.cpp +++ b/src/platform/tests/TestPlatformTime.cpp @@ -28,10 +28,9 @@ #include #include +#include #include -#include #include -#include #include #include @@ -48,7 +47,7 @@ constexpr Clock::Microseconds64 kTestTimeMarginUs = 500_us64; // Unit tests // ================================= -static void TestDevice_GetMonotonicMicroseconds(nlTestSuite * inSuite, void * inContext) +TEST(TestDevice, GetMonotonicMicroseconds) { static const Clock::Microseconds64 kTestVectorSystemTimeUs[] = { 600_us64, @@ -74,15 +73,15 @@ static void TestDevice_GetMonotonicMicroseconds(nlTestSuite * inSuite, void * in ChipLogValueX64(Tdelay.count())); // verify that timers don't fire early - NL_TEST_ASSERT(inSuite, Tdelta > (Tdelay - margin)); + EXPECT_GT(Tdelta, (Tdelay - margin)); // verify they're not too late - // NL_TEST_ASSERT(inSuite, Tdelta < (Tdelay + margin)); + // EXPECT_LT(Tdelta, (Tdelay + margin)); numOfTestsRan++; } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); + EXPECT_GT(numOfTestsRan, 0); } -static void TestDevice_GetMonotonicMilliseconds(nlTestSuite * inSuite, void * inContext) +TEST(TestDevice, GetMonotonicMilliseconds) { static const System::Clock::Milliseconds64 kTestVectorSystemTimeMs[] = { 10_ms64, @@ -108,32 +107,10 @@ static void TestDevice_GetMonotonicMilliseconds(nlTestSuite * inSuite, void * in ChipLogValueX64(Tdelay.count())); // verify that timers don't fire early - NL_TEST_ASSERT(inSuite, Tdelta > (Tdelay - margin)); + EXPECT_GT(Tdelta, (Tdelay - margin)); // verify they're not too late - // NL_TEST_ASSERT(inSuite, Tdelta < (Tdelay + margin)); + // EXPECT_LT(Tdelta, (Tdelay + margin)); numOfTestsRan++; } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); + EXPECT_GT(numOfTestsRan, 0); } - -/** - * Test Suite. It lists all the test functions. - */ -static const nlTest sTests[] = { - - NL_TEST_DEF("Test DeviceLayer::GetMonotonicMicroseconds", TestDevice_GetMonotonicMicroseconds), - NL_TEST_DEF("Test DeviceLayer::GetMonotonicMilliseconds", TestDevice_GetMonotonicMilliseconds), - - NL_TEST_SENTINEL() -}; - -int TestPlatformTime() -{ - nlTestSuite theSuite = { "PlatformTime tests", &sTests[0], nullptr, nullptr }; - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestPlatformTime) diff --git a/src/platform/tests/TestThreadStackMgr.cpp b/src/platform/tests/TestThreadStackMgr.cpp index b7a320ce4b15bf..143de88587ccd5 100644 --- a/src/platform/tests/TestThreadStackMgr.cpp +++ b/src/platform/tests/TestThreadStackMgr.cpp @@ -18,16 +18,16 @@ #include #include +#include #include #include -#include #include "platform/internal/CHIPDeviceLayerInternal.h" #include "platform/PlatformManager.h" #include "platform/ThreadStackManager.h" -#if CHIP_DEVICE_LAYER_TARGET == LINUX +#if CHIP_DEVICE_LAYER_TARGET_LINUX #include #include @@ -39,20 +39,20 @@ struct DBusConnectionDeleter using UniqueDBusConnection = std::unique_ptr; #endif -void EventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg) +static std::atomic_bool eventReceived{ false }; + +void EventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t) { - (void) arg; if (event->Type == chip::DeviceLayer::DeviceEventType::kThreadConnectivityChange) { if (event->ThreadConnectivityChange.Result == chip::DeviceLayer::ConnectivityChange::kConnectivity_Established) { - chip::Platform::MemoryShutdown(); - exit(0); + eventReceived = true; } } } -int TestThreadStackManager() +TEST(TestThreadStackManager, TestThreadStackManager) { chip::DeviceLayer::ThreadStackManagerImpl impl; chip::Thread::OperationalDataset dataset{}; @@ -79,7 +79,5 @@ int TestThreadStackManager() chip::DeviceLayer::PlatformMgrImpl().RunEventLoop(); chip::Platform::MemoryShutdown(); - return -1; + EXPECT_TRUE(eventReceived); } - -CHIP_REGISTER_TEST_SUITE(TestThreadStackManager); diff --git a/src/platform/webos/BLEManagerImpl.cpp b/src/platform/webos/BLEManagerImpl.cpp index 670c86e8233237..6d9726c9c94742 100644 --- a/src/platform/webos/BLEManagerImpl.cpp +++ b/src/platform/webos/BLEManagerImpl.cpp @@ -23,7 +23,7 @@ */ #include -#include +#include #include #include #include diff --git a/src/platform/webos/BLEManagerImpl.h b/src/platform/webos/BLEManagerImpl.h index cc3f7c3d84ae2a..7336f95c02409c 100644 --- a/src/platform/webos/BLEManagerImpl.h +++ b/src/platform/webos/BLEManagerImpl.h @@ -23,7 +23,7 @@ #pragma once -#include +#include #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/webos/ChipDeviceScanner.h b/src/platform/webos/ChipDeviceScanner.h index ac23c7bd4b68aa..3bc50171ccf99c 100644 --- a/src/platform/webos/ChipDeviceScanner.h +++ b/src/platform/webos/ChipDeviceScanner.h @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include diff --git a/src/setup_payload/SetupPayload.cpp b/src/setup_payload/SetupPayload.cpp index 3b427f3b312473..3d312cd5846e8d 100644 --- a/src/setup_payload/SetupPayload.cpp +++ b/src/setup_payload/SetupPayload.cpp @@ -146,7 +146,7 @@ bool PayloadContents::CheckPayloadCommonConstraints() const return true; } -bool PayloadContents::operator==(PayloadContents & input) const +bool PayloadContents::operator==(const PayloadContents & input) const { return (this->version == input.version && this->vendorID == input.vendorID && this->productID == input.productID && this->commissioningFlow == input.commissioningFlow && this->rendezvousInformation == input.rendezvousInformation && @@ -257,10 +257,11 @@ CHIP_ERROR SetupPayload::addOptionalExtensionData(const OptionalQRCodeInfoExtens return CHIP_NO_ERROR; } -CHIP_ERROR SetupPayload::getOptionalVendorData(uint8_t tag, OptionalQRCodeInfo & info) +CHIP_ERROR SetupPayload::getOptionalVendorData(uint8_t tag, OptionalQRCodeInfo & info) const { - VerifyOrReturnError(optionalVendorData.find(tag) != optionalVendorData.end(), CHIP_ERROR_KEY_NOT_FOUND); - info = optionalVendorData[tag]; + const auto it = optionalVendorData.find(tag); + VerifyOrReturnError(it != optionalVendorData.end(), CHIP_ERROR_KEY_NOT_FOUND); + info = it->second; return CHIP_NO_ERROR; } @@ -273,7 +274,7 @@ CHIP_ERROR SetupPayload::getOptionalExtensionData(uint8_t tag, OptionalQRCodeInf return CHIP_NO_ERROR; } -optionalQRCodeInfoType SetupPayload::getNumericTypeFor(uint8_t tag) +optionalQRCodeInfoType SetupPayload::getNumericTypeFor(uint8_t tag) const { optionalQRCodeInfoType elemType = optionalQRCodeInfoTypeUnknown; @@ -289,7 +290,7 @@ optionalQRCodeInfoType SetupPayload::getNumericTypeFor(uint8_t tag) return elemType; } -std::vector SetupPayload::getAllOptionalExtensionData() +std::vector SetupPayload::getAllOptionalExtensionData() const { std::vector returnedOptionalInfo; for (auto & entry : optionalExtensionData) @@ -299,7 +300,7 @@ std::vector SetupPayload::getAllOptionalExtensionDa return returnedOptionalInfo; } -bool SetupPayload::operator==(SetupPayload & input) +bool SetupPayload::operator==(const SetupPayload & input) const { std::vector inputOptionalVendorData; std::vector inputOptionalExtensionData; diff --git a/src/setup_payload/SetupPayload.h b/src/setup_payload/SetupPayload.h index 0bb21698341279..9b18574480ba6e 100644 --- a/src/setup_payload/SetupPayload.h +++ b/src/setup_payload/SetupPayload.h @@ -130,7 +130,7 @@ struct PayloadContents bool isValidQRCodePayload() const; bool isValidManualCode() const; - bool operator==(PayloadContents & input) const; + bool operator==(const PayloadContents & input) const; static bool IsValidSetupPIN(uint32_t setupPIN); @@ -233,7 +233,7 @@ class SetupPayload : public PayloadContents **/ CHIP_ERROR removeSerialNumber(); - bool operator==(SetupPayload & input); + bool operator==(const SetupPayload & input) const; private: std::map optionalVendorData; @@ -267,14 +267,14 @@ class SetupPayload : public PayloadContents * @brief A function to retrieve the vector of CHIPQRCodeInfo infos * @return Returns a vector of CHIPQRCodeInfos **/ - std::vector getAllOptionalExtensionData(); + std::vector getAllOptionalExtensionData() const; /** @brief A function to retrieve an optional QR Code info vendor object * @param tag 7 bit [0-127] tag number * @param info retrieved OptionalQRCodeInfo object * @return Returns a CHIP_ERROR_KEY_NOT_FOUND on error, CHIP_NO_ERROR otherwise **/ - CHIP_ERROR getOptionalVendorData(uint8_t tag, OptionalQRCodeInfo & info); + CHIP_ERROR getOptionalVendorData(uint8_t tag, OptionalQRCodeInfo & info) const; /** @brief A function to retrieve an optional QR Code info extended object * @param tag 8 bit [128-255] tag number @@ -287,7 +287,7 @@ class SetupPayload : public PayloadContents * @param tag 8 bit [0-255] tag number * @return Returns an optionalQRCodeInfoType value **/ - optionalQRCodeInfoType getNumericTypeFor(uint8_t tag); + optionalQRCodeInfoType getNumericTypeFor(uint8_t tag) const; }; } // namespace chip diff --git a/src/setup_payload/tests/BUILD.gn b/src/setup_payload/tests/BUILD.gn index 4ed7033417352e..0f672c274fc941 100644 --- a/src/setup_payload/tests/BUILD.gn +++ b/src/setup_payload/tests/BUILD.gn @@ -15,16 +15,33 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") import("//build_overrides/nlunit_test.gni") +import("//build_overrides/pigweed.gni") import("${chip_root}/build/chip/chip_test_suite.gni") -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libSetupPayloadTests" test_sources = [ - "TestAdditionalDataPayload.cpp", "TestManualCode.cpp", "TestQRCode.cpp", + ] + + sources = [ "TestHelpers.h" ] + + cflags = [ "-Wconversion" ] + + public_deps = [ + "${chip_root}/src/platform", + "${chip_root}/src/setup_payload", + ] +} + +chip_test_suite_using_nltest("tests_nltest") { + output_name = "libSetupPayloadTestsNL" + + test_sources = [ + "TestAdditionalDataPayload.cpp", "TestQRCodeTLV.cpp", ] diff --git a/src/setup_payload/tests/TestManualCode.cpp b/src/setup_payload/tests/TestManualCode.cpp index cfe7c59c06e8b8..0b9be9a906011e 100644 --- a/src/setup_payload/tests/TestManualCode.cpp +++ b/src/setup_payload/tests/TestManualCode.cpp @@ -22,15 +22,13 @@ * */ -#include +#include #include #include #include #include -#include -#include #include #include @@ -79,26 +77,26 @@ PayloadContents GetDefaultPayload() return payload; } -void TestDecimalRepresentation_PartialPayload(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestDecimalRepresentation_PartialPayload) { PayloadContents payload = GetDefaultPayload(); std::string expectedResult = "2412950753"; - NL_TEST_ASSERT(inSuite, CheckGenerator(payload, expectedResult)); + EXPECT_TRUE(CheckGenerator(payload, expectedResult)); } -void TestDecimalRepresentation_PartialPayload_RequiresCustomFlow(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestDecimalRepresentation_PartialPayload_RequiresCustomFlow) { PayloadContents payload = GetDefaultPayload(); payload.commissioningFlow = CommissioningFlow::kCustom; std::string expectedResult = "64129507530000000000"; - NL_TEST_ASSERT(inSuite, CheckGenerator(payload, expectedResult)); + EXPECT_TRUE(CheckGenerator(payload, expectedResult)); } -void TestDecimalRepresentation_FullPayloadWithZeros(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestDecimalRepresentation_FullPayloadWithZeros) { PayloadContents payload = GetDefaultPayload(); payload.commissioningFlow = CommissioningFlow::kCustom; @@ -107,10 +105,10 @@ void TestDecimalRepresentation_FullPayloadWithZeros(nlTestSuite * inSuite, void std::string expectedResult = "64129507530000100001"; - NL_TEST_ASSERT(inSuite, CheckGenerator(payload, expectedResult)); + EXPECT_TRUE(CheckGenerator(payload, expectedResult)); } -void TestDecimalRepresentation_FullPayloadWithoutZeros_DoesNotRequireCustomFlow(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestDecimalRepresentation_FullPayloadWithoutZeros_DoesNotRequireCustomFlow) { PayloadContents payload = GetDefaultPayload(); payload.vendorID = 45367; @@ -118,10 +116,10 @@ void TestDecimalRepresentation_FullPayloadWithoutZeros_DoesNotRequireCustomFlow( std::string expectedResult = "2412950753"; - NL_TEST_ASSERT(inSuite, CheckGenerator(payload, expectedResult)); + EXPECT_TRUE(CheckGenerator(payload, expectedResult)); } -void TestDecimalRepresentation_FullPayloadWithoutZeros(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestDecimalRepresentation_FullPayloadWithoutZeros) { PayloadContents payload = GetDefaultPayload(); payload.commissioningFlow = CommissioningFlow::kCustom; @@ -130,20 +128,20 @@ void TestDecimalRepresentation_FullPayloadWithoutZeros(nlTestSuite * inSuite, vo std::string expectedResult = "64129507534536714526"; - NL_TEST_ASSERT(inSuite, CheckGenerator(payload, expectedResult)); + EXPECT_TRUE(CheckGenerator(payload, expectedResult)); } -void assertPayloadValues(nlTestSuite * inSuite, CHIP_ERROR actualError, CHIP_ERROR expectedError, const PayloadContents & payload, - uint32_t pinCode, const SetupDiscriminator & discriminator, uint16_t vendorID, uint16_t productID) +void assertPayloadValues(CHIP_ERROR actualError, CHIP_ERROR expectedError, const PayloadContents & payload, uint32_t pinCode, + const SetupDiscriminator & discriminator, uint16_t vendorID, uint16_t productID) { - NL_TEST_ASSERT(inSuite, actualError == expectedError); - NL_TEST_ASSERT(inSuite, payload.setUpPINCode == pinCode); - NL_TEST_ASSERT(inSuite, payload.discriminator == discriminator); - NL_TEST_ASSERT(inSuite, payload.vendorID == vendorID); - NL_TEST_ASSERT(inSuite, payload.productID == productID); + EXPECT_EQ(actualError, expectedError); + EXPECT_EQ(payload.setUpPINCode, pinCode); + EXPECT_EQ(payload.discriminator, discriminator); + EXPECT_EQ(payload.vendorID, vendorID); + EXPECT_EQ(payload.productID, productID); } -void TestGenerateAndParser_ManualSetupCodeWithLongDiscriminator(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestGenerateAndParser_ManualSetupCodeWithLongDiscriminator) { PayloadContents payload = GetDefaultPayload(); payload.discriminator.SetLongValue(0xa1f); @@ -152,15 +150,15 @@ void TestGenerateAndParser_ManualSetupCodeWithLongDiscriminator(nlTestSuite * in // Test short 11 digit code ManualSetupPayloadGenerator generator(payload); std::string result; - NL_TEST_ASSERT(inSuite, generator.payloadDecimalStringRepresentation(result) == CHIP_NO_ERROR); + EXPECT_EQ(generator.payloadDecimalStringRepresentation(result), CHIP_NO_ERROR); SetupPayload outPayload; CHIP_ERROR err = ManualSetupPayloadParser(result).populatePayload(outPayload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); SetupDiscriminator discriminator; discriminator.SetShortValue(0xa); - assertPayloadValues(inSuite, err, CHIP_NO_ERROR, outPayload, payload.setUpPINCode, discriminator, payload.vendorID, + assertPayloadValues(err, CHIP_NO_ERROR, outPayload, payload.setUpPINCode, discriminator, payload.vendorID, payload.productID); } @@ -173,20 +171,20 @@ void TestGenerateAndParser_ManualSetupCodeWithLongDiscriminator(nlTestSuite * in // Test long 21 digit code ManualSetupPayloadGenerator generator(payload); std::string result; - NL_TEST_ASSERT(inSuite, generator.payloadDecimalStringRepresentation(result) == CHIP_NO_ERROR); + EXPECT_EQ(generator.payloadDecimalStringRepresentation(result), CHIP_NO_ERROR); SetupPayload outPayload; CHIP_ERROR err = ManualSetupPayloadParser(result).populatePayload(outPayload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); SetupDiscriminator discriminator; discriminator.SetShortValue(0xb); - assertPayloadValues(inSuite, err, CHIP_NO_ERROR, outPayload, payload.setUpPINCode, discriminator, payload.vendorID, + assertPayloadValues(err, CHIP_NO_ERROR, outPayload, payload.setUpPINCode, discriminator, payload.vendorID, payload.productID); } } -void TestDecimalRepresentation_AllZeros(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestDecimalRepresentation_AllZeros) { PayloadContents payload; payload.setUpPINCode = 0; @@ -194,10 +192,10 @@ void TestDecimalRepresentation_AllZeros(nlTestSuite * inSuite, void * inContext) std::string expectedResult; - NL_TEST_ASSERT(inSuite, CheckGenerator(payload, expectedResult) == false); + EXPECT_EQ(CheckGenerator(payload, expectedResult), false); } -void TestDecimalRepresentation_AllOnes(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestDecimalRepresentation_AllOnes) { PayloadContents payload; payload.setUpPINCode = 0x7FFFFFF; @@ -208,7 +206,7 @@ void TestDecimalRepresentation_AllOnes(nlTestSuite * inSuite, void * inContext) std::string expectedResult = "76553581916553565535"; - NL_TEST_ASSERT(inSuite, CheckGenerator(payload, expectedResult, /*allowInvalidPayload*/ true)); + EXPECT_TRUE(CheckGenerator(payload, expectedResult, /*allowInvalidPayload*/ true)); } char ComputeCheckChar(const std::string & str) @@ -219,7 +217,7 @@ char ComputeCheckChar(const std::string & str) return Verhoeff10::ComputeCheckChar(copy.c_str()); } -void TestPayloadParser_FullPayload(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestPayloadParser_FullPayload) { SetupPayload payload; std::string decimalString; @@ -227,39 +225,39 @@ void TestPayloadParser_FullPayload(nlTestSuite * inSuite, void * inContext) decimalString = "63610875354536714526"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); CHIP_ERROR err = ManualSetupPayloadParser(decimalString).populatePayload(payload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); SetupDiscriminator discriminator; discriminator.SetShortValue(0xa); - assertPayloadValues(inSuite, err, CHIP_NO_ERROR, payload, 123456780, discriminator, 45367, 14526); + assertPayloadValues(err, CHIP_NO_ERROR, payload, 123456780, discriminator, 45367, 14526); // The same thing, but with dashes separating digit groups. decimalString = "6361-0875-3545-3671-4526"; decimalString += ComputeCheckChar(decimalString); err = ManualSetupPayloadParser(decimalString).populatePayload(payload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); discriminator.SetShortValue(0xa); - assertPayloadValues(inSuite, err, CHIP_NO_ERROR, payload, 123456780, discriminator, 45367, 14526); + assertPayloadValues(err, CHIP_NO_ERROR, payload, 123456780, discriminator, 45367, 14526); decimalString = "52927623630456200032"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); err = ManualSetupPayloadParser(decimalString).populatePayload(payload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); discriminator.SetShortValue(0x5); - assertPayloadValues(inSuite, err, CHIP_NO_ERROR, payload, 38728284, discriminator, 4562, 32); + assertPayloadValues(err, CHIP_NO_ERROR, payload, 38728284, discriminator, 4562, 32); decimalString = "40000100000000100001"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); err = ManualSetupPayloadParser(decimalString).populatePayload(payload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); discriminator.SetShortValue(0); - assertPayloadValues(inSuite, err, CHIP_NO_ERROR, payload, 1, discriminator, 1, 1); + assertPayloadValues(err, CHIP_NO_ERROR, payload, 1, discriminator, 1, 1); } -void TestGenerateAndParser_FullPayload(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestGenerateAndParser_FullPayload) { PayloadContents payload = GetDefaultPayload(); payload.vendorID = 1; @@ -268,37 +266,35 @@ void TestGenerateAndParser_FullPayload(nlTestSuite * inSuite, void * inContext) ManualSetupPayloadGenerator generator(payload); std::string result; - NL_TEST_ASSERT(inSuite, generator.payloadDecimalStringRepresentation(result) == CHIP_NO_ERROR); + EXPECT_EQ(generator.payloadDecimalStringRepresentation(result), CHIP_NO_ERROR); SetupPayload outPayload; CHIP_ERROR err = ManualSetupPayloadParser(result).populatePayload(outPayload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); SetupDiscriminator discriminator; discriminator.SetShortValue(payload.discriminator.GetShortValue()); - assertPayloadValues(inSuite, err, CHIP_NO_ERROR, outPayload, payload.setUpPINCode, discriminator, payload.vendorID, - payload.productID); + assertPayloadValues(err, CHIP_NO_ERROR, outPayload, payload.setUpPINCode, discriminator, payload.vendorID, payload.productID); } -void TestGenerateAndParser_PartialPayload(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestGenerateAndParser_PartialPayload) { PayloadContents payload = GetDefaultPayload(); ManualSetupPayloadGenerator generator(payload); std::string result; - NL_TEST_ASSERT(inSuite, generator.payloadDecimalStringRepresentation(result) == CHIP_NO_ERROR); + EXPECT_EQ(generator.payloadDecimalStringRepresentation(result), CHIP_NO_ERROR); SetupPayload outPayload; CHIP_ERROR err = ManualSetupPayloadParser(result).populatePayload(outPayload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); SetupDiscriminator discriminator; discriminator.SetShortValue(payload.discriminator.GetShortValue()); - assertPayloadValues(inSuite, err, CHIP_NO_ERROR, outPayload, payload.setUpPINCode, discriminator, payload.vendorID, - payload.productID); + assertPayloadValues(err, CHIP_NO_ERROR, outPayload, payload.setUpPINCode, discriminator, payload.vendorID, payload.productID); } -void TestPayloadParser_PartialPayload(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestPayloadParser_PartialPayload) { CHIP_ERROR err; SetupPayload payload; @@ -306,65 +302,65 @@ void TestPayloadParser_PartialPayload(nlTestSuite * inSuite, void * inContext) decimalString = "2361087535"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); - NL_TEST_ASSERT(inSuite, decimalString.length() == 11); + EXPECT_EQ(decimalString.length(), 11u); err = ManualSetupPayloadParser(decimalString).populatePayload(payload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); SetupDiscriminator discriminator; discriminator.SetShortValue(0xa); - assertPayloadValues(inSuite, err, CHIP_NO_ERROR, payload, 123456780, discriminator, 0, 0); + assertPayloadValues(err, CHIP_NO_ERROR, payload, 123456780, discriminator, 0, 0); // The same thing, but with dashes separating digit groups. decimalString = "236-108753-5"; decimalString += ComputeCheckChar(decimalString); - NL_TEST_ASSERT(inSuite, decimalString.length() == 13); + EXPECT_EQ(decimalString.length(), 13u); err = ManualSetupPayloadParser(decimalString).populatePayload(payload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); discriminator.SetShortValue(0xa); - assertPayloadValues(inSuite, err, CHIP_NO_ERROR, payload, 123456780, discriminator, 0, 0); + assertPayloadValues(err, CHIP_NO_ERROR, payload, 123456780, discriminator, 0, 0); decimalString = "0000010000"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); - NL_TEST_ASSERT(inSuite, decimalString.length() == 11); + EXPECT_EQ(decimalString.length(), 11u); err = ManualSetupPayloadParser(decimalString).populatePayload(payload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); discriminator.SetShortValue(0); - assertPayloadValues(inSuite, err, CHIP_NO_ERROR, payload, 1, discriminator, 0, 0); + assertPayloadValues(err, CHIP_NO_ERROR, payload, 1, discriminator, 0, 0); decimalString = "63610875350000000000"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); - NL_TEST_ASSERT(inSuite, decimalString.length() == 21); + EXPECT_EQ(decimalString.length(), 21u); err = ManualSetupPayloadParser(decimalString).populatePayload(payload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); discriminator.SetShortValue(0xa); - assertPayloadValues(inSuite, err, CHIP_NO_ERROR, payload, 123456780, discriminator, 0, 0); + assertPayloadValues(err, CHIP_NO_ERROR, payload, 123456780, discriminator, 0, 0); // no discriminator (= 0) decimalString = "0033407535"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); - NL_TEST_ASSERT(inSuite, decimalString.length() == 11); + EXPECT_EQ(decimalString.length(), 11u); err = ManualSetupPayloadParser(decimalString).populatePayload(payload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // no vid (= 0) decimalString = "63610875350000014526"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); - NL_TEST_ASSERT(inSuite, decimalString.length() == 21); + EXPECT_EQ(decimalString.length(), 21u); err = ManualSetupPayloadParser(decimalString).populatePayload(payload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // no pid (= 0) decimalString = "63610875354536700000"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); - NL_TEST_ASSERT(inSuite, decimalString.length() == 21); + EXPECT_EQ(decimalString.length(), 21u); err = ManualSetupPayloadParser(decimalString).populatePayload(payload); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void TestShortCodeReadWrite(nlTestSuite * inSuite, void * context) +TEST(TestManualCode, TestShortCodeReadWrite) { PayloadContents inPayload = GetDefaultPayload(); @@ -378,10 +374,10 @@ void TestShortCodeReadWrite(nlTestSuite * inSuite, void * context) // Override the discriminator in the input payload with the short version, // since that's what we will produce. inPayload.discriminator.SetShortValue(inPayload.discriminator.GetShortValue()); - NL_TEST_ASSERT(inSuite, inPayload == outPayload); + EXPECT_TRUE(inPayload == outPayload); } -void TestLongCodeReadWrite(nlTestSuite * inSuite, void * context) +TEST(TestManualCode, TestLongCodeReadWrite) { PayloadContents inPayload = GetDefaultPayload(); inPayload.commissioningFlow = CommissioningFlow::kCustom; @@ -398,19 +394,17 @@ void TestLongCodeReadWrite(nlTestSuite * inSuite, void * context) // Override the discriminator in the input payload with the short version, // since that's what we will produce. inPayload.discriminator.SetShortValue(inPayload.discriminator.GetShortValue()); - NL_TEST_ASSERT(inSuite, inPayload == outPayload); + EXPECT_TRUE(inPayload == outPayload); } -void assertEmptyPayloadWithError(nlTestSuite * inSuite, CHIP_ERROR actualError, CHIP_ERROR expectedError, - const SetupPayload & payload) +void assertEmptyPayloadWithError(CHIP_ERROR actualError, CHIP_ERROR expectedError, const SetupPayload & payload) { - NL_TEST_ASSERT(inSuite, actualError == expectedError); - NL_TEST_ASSERT(inSuite, - payload.setUpPINCode == 0 && payload.discriminator.GetLongValue() == 0 && payload.productID == 0 && - payload.vendorID == 0); + EXPECT_EQ(actualError, expectedError); + EXPECT_TRUE(payload.setUpPINCode == 0 && payload.discriminator.GetLongValue() == 0 && payload.productID == 0 && + payload.vendorID == 0); } -void TestPayloadParser_InvalidEntry(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestPayloadParser_InvalidEntry) { SetupPayload payload; std::string decimalString; @@ -418,50 +412,50 @@ void TestPayloadParser_InvalidEntry(nlTestSuite * inSuite, void * inContext) // Empty input decimalString = ""; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); - assertEmptyPayloadWithError(inSuite, ManualSetupPayloadParser(decimalString).populatePayload(payload), - CHIP_ERROR_INVALID_STRING_LENGTH, payload); + assertEmptyPayloadWithError(ManualSetupPayloadParser(decimalString).populatePayload(payload), CHIP_ERROR_INVALID_STRING_LENGTH, + payload); // Invalid character decimalString = "24184.2196"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); - assertEmptyPayloadWithError(inSuite, ManualSetupPayloadParser(decimalString).populatePayload(payload), - CHIP_ERROR_INVALID_INTEGER_VALUE, payload); + assertEmptyPayloadWithError(ManualSetupPayloadParser(decimalString).populatePayload(payload), CHIP_ERROR_INVALID_INTEGER_VALUE, + payload); // too short decimalString = "2456"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); - assertEmptyPayloadWithError(inSuite, ManualSetupPayloadParser(decimalString).populatePayload(payload), - CHIP_ERROR_INVALID_STRING_LENGTH, payload); + assertEmptyPayloadWithError(ManualSetupPayloadParser(decimalString).populatePayload(payload), CHIP_ERROR_INVALID_STRING_LENGTH, + payload); // too long for long code decimalString = "123456789123456785671"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); - assertEmptyPayloadWithError(inSuite, ManualSetupPayloadParser(decimalString).populatePayload(payload), - CHIP_ERROR_INVALID_STRING_LENGTH, payload); + assertEmptyPayloadWithError(ManualSetupPayloadParser(decimalString).populatePayload(payload), CHIP_ERROR_INVALID_STRING_LENGTH, + payload); // too long for short code decimalString = "12749875380"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); - assertEmptyPayloadWithError(inSuite, ManualSetupPayloadParser(decimalString).populatePayload(payload), - CHIP_ERROR_INVALID_STRING_LENGTH, payload); + assertEmptyPayloadWithError(ManualSetupPayloadParser(decimalString).populatePayload(payload), CHIP_ERROR_INVALID_STRING_LENGTH, + payload); // bit to indicate short code but long code length decimalString = "23456789123456785610"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); - assertEmptyPayloadWithError(inSuite, ManualSetupPayloadParser(decimalString).populatePayload(payload), - CHIP_ERROR_INVALID_STRING_LENGTH, payload); + assertEmptyPayloadWithError(ManualSetupPayloadParser(decimalString).populatePayload(payload), CHIP_ERROR_INVALID_STRING_LENGTH, + payload); // no pin code (= 0) decimalString = "2327680000"; decimalString += Verhoeff10::ComputeCheckChar(decimalString.c_str()); - assertEmptyPayloadWithError(inSuite, ManualSetupPayloadParser(decimalString).populatePayload(payload), - CHIP_ERROR_INVALID_ARGUMENT, payload); + assertEmptyPayloadWithError(ManualSetupPayloadParser(decimalString).populatePayload(payload), CHIP_ERROR_INVALID_ARGUMENT, + payload); // wrong check digit decimalString = "02684354589"; - assertEmptyPayloadWithError(inSuite, ManualSetupPayloadParser(decimalString).populatePayload(payload), - CHIP_ERROR_INTEGRITY_CHECK_FAILED, payload); + assertEmptyPayloadWithError(ManualSetupPayloadParser(decimalString).populatePayload(payload), CHIP_ERROR_INTEGRITY_CHECK_FAILED, + payload); } -void TestCheckDecimalStringValidity(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestCheckDecimalStringValidity) { std::string outReprensation; char checkDigit; @@ -469,172 +463,106 @@ void TestCheckDecimalStringValidity(nlTestSuite * inSuite, void * inContext) std::string decimalString; representationWithoutCheckDigit = ""; - NL_TEST_ASSERT(inSuite, - ManualSetupPayloadParser::CheckDecimalStringValidity(representationWithoutCheckDigit, outReprensation) == - CHIP_ERROR_INVALID_STRING_LENGTH); + EXPECT_EQ(ManualSetupPayloadParser::CheckDecimalStringValidity(representationWithoutCheckDigit, outReprensation), + CHIP_ERROR_INVALID_STRING_LENGTH); representationWithoutCheckDigit = "1"; - NL_TEST_ASSERT(inSuite, - ManualSetupPayloadParser::CheckDecimalStringValidity(representationWithoutCheckDigit, outReprensation) == - CHIP_ERROR_INVALID_STRING_LENGTH); + EXPECT_EQ(ManualSetupPayloadParser::CheckDecimalStringValidity(representationWithoutCheckDigit, outReprensation), + CHIP_ERROR_INVALID_STRING_LENGTH); representationWithoutCheckDigit = "10109"; checkDigit = Verhoeff10::ComputeCheckChar(representationWithoutCheckDigit.c_str()); decimalString = representationWithoutCheckDigit + checkDigit; - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::CheckDecimalStringValidity(decimalString, outReprensation) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, outReprensation == representationWithoutCheckDigit); + EXPECT_EQ(ManualSetupPayloadParser::CheckDecimalStringValidity(decimalString, outReprensation), CHIP_NO_ERROR); + EXPECT_EQ(outReprensation, representationWithoutCheckDigit); representationWithoutCheckDigit = "0000"; checkDigit = Verhoeff10::ComputeCheckChar(representationWithoutCheckDigit.c_str()); decimalString = representationWithoutCheckDigit + checkDigit; - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::CheckDecimalStringValidity(decimalString, outReprensation) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, outReprensation == representationWithoutCheckDigit); + EXPECT_EQ(ManualSetupPayloadParser::CheckDecimalStringValidity(decimalString, outReprensation), CHIP_NO_ERROR); + EXPECT_EQ(outReprensation, representationWithoutCheckDigit); } -void TestCheckCodeLengthValidity(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestCheckCodeLengthValidity) { - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::CheckCodeLengthValidity("01234567890123456789", true) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::CheckCodeLengthValidity("0123456789", false) == CHIP_NO_ERROR); - - NL_TEST_ASSERT(inSuite, - ManualSetupPayloadParser::CheckCodeLengthValidity("01234567891", false) == CHIP_ERROR_INVALID_STRING_LENGTH); - NL_TEST_ASSERT(inSuite, - ManualSetupPayloadParser::CheckCodeLengthValidity("012345678", false) == CHIP_ERROR_INVALID_STRING_LENGTH); - NL_TEST_ASSERT(inSuite, - ManualSetupPayloadParser::CheckCodeLengthValidity("012345678901234567891", true) == - CHIP_ERROR_INVALID_STRING_LENGTH); - NL_TEST_ASSERT(inSuite, - ManualSetupPayloadParser::CheckCodeLengthValidity("0123456789012345678", true) == - CHIP_ERROR_INVALID_STRING_LENGTH); + EXPECT_EQ(ManualSetupPayloadParser::CheckCodeLengthValidity("01234567890123456789", true), CHIP_NO_ERROR); + EXPECT_EQ(ManualSetupPayloadParser::CheckCodeLengthValidity("0123456789", false), CHIP_NO_ERROR); + + EXPECT_EQ(ManualSetupPayloadParser::CheckCodeLengthValidity("01234567891", false), CHIP_ERROR_INVALID_STRING_LENGTH); + EXPECT_EQ(ManualSetupPayloadParser::CheckCodeLengthValidity("012345678", false), CHIP_ERROR_INVALID_STRING_LENGTH); + EXPECT_EQ(ManualSetupPayloadParser::CheckCodeLengthValidity("012345678901234567891", true), CHIP_ERROR_INVALID_STRING_LENGTH); + EXPECT_EQ(ManualSetupPayloadParser::CheckCodeLengthValidity("0123456789012345678", true), CHIP_ERROR_INVALID_STRING_LENGTH); } -void TestDecimalStringToNumber(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestDecimalStringToNumber) { uint32_t number; - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::ToNumber("12345", number) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, number == 12345); + EXPECT_EQ(ManualSetupPayloadParser::ToNumber("12345", number), CHIP_NO_ERROR); + EXPECT_EQ(number, 12345u); - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::ToNumber("01234567890", number) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, number == 1234567890); + EXPECT_EQ(ManualSetupPayloadParser::ToNumber("01234567890", number), CHIP_NO_ERROR); + EXPECT_EQ(number, 1234567890u); - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::ToNumber("00000001", number) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, number == 1); + EXPECT_EQ(ManualSetupPayloadParser::ToNumber("00000001", number), CHIP_NO_ERROR); + EXPECT_TRUE(number); - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::ToNumber("0", number) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, number == 0); + EXPECT_EQ(ManualSetupPayloadParser::ToNumber("0", number), CHIP_NO_ERROR); + EXPECT_FALSE(number); - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::ToNumber("012345.123456789", number) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::ToNumber("/", number) == CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(ManualSetupPayloadParser::ToNumber("012345.123456789", number), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(ManualSetupPayloadParser::ToNumber("/", number), CHIP_ERROR_INVALID_INTEGER_VALUE); } -void TestReadCharsFromDecimalString(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestReadCharsFromDecimalString) { uint32_t number; size_t index = 3; - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::ReadDigitsFromDecimalString("12345", index, number, 2) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, number == 45); + EXPECT_EQ(ManualSetupPayloadParser::ReadDigitsFromDecimalString("12345", index, number, 2), CHIP_NO_ERROR); + EXPECT_EQ(number, 45u); index = 2; - NL_TEST_ASSERT(inSuite, - ManualSetupPayloadParser::ReadDigitsFromDecimalString("6256276377282", index, number, 7) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, number == 5627637); + EXPECT_EQ(ManualSetupPayloadParser::ReadDigitsFromDecimalString("6256276377282", index, number, 7), CHIP_NO_ERROR); + EXPECT_EQ(number, 5627637u); index = 0; - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::ReadDigitsFromDecimalString("10", index, number, 2) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, number == 10); + EXPECT_EQ(ManualSetupPayloadParser::ReadDigitsFromDecimalString("10", index, number, 2), CHIP_NO_ERROR); + EXPECT_EQ(number, 10u); index = 0; - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::ReadDigitsFromDecimalString("01", index, number, 2) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, number == 1); + EXPECT_EQ(ManualSetupPayloadParser::ReadDigitsFromDecimalString("01", index, number, 2), CHIP_NO_ERROR); + EXPECT_TRUE(number); index = 1; - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::ReadDigitsFromDecimalString("11", index, number, 1) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, number == 1); + EXPECT_EQ(ManualSetupPayloadParser::ReadDigitsFromDecimalString("11", index, number, 1), CHIP_NO_ERROR); + EXPECT_TRUE(number); index = 2; - NL_TEST_ASSERT(inSuite, ManualSetupPayloadParser::ReadDigitsFromDecimalString("100001", index, number, 3) == CHIP_NO_ERROR); + EXPECT_EQ(ManualSetupPayloadParser::ReadDigitsFromDecimalString("100001", index, number, 3), CHIP_NO_ERROR); index = 1; - NL_TEST_ASSERT(inSuite, - ManualSetupPayloadParser::ReadDigitsFromDecimalString("12345", index, number, 5) == - CHIP_ERROR_INVALID_STRING_LENGTH); - NL_TEST_ASSERT( - inSuite, ManualSetupPayloadParser::ReadDigitsFromDecimalString("12", index, number, 5) == CHIP_ERROR_INVALID_STRING_LENGTH); + EXPECT_EQ(ManualSetupPayloadParser::ReadDigitsFromDecimalString("12345", index, number, 5), CHIP_ERROR_INVALID_STRING_LENGTH); + EXPECT_EQ(ManualSetupPayloadParser::ReadDigitsFromDecimalString("12", index, number, 5), CHIP_ERROR_INVALID_STRING_LENGTH); index = 200; - NL_TEST_ASSERT(inSuite, - ManualSetupPayloadParser::ReadDigitsFromDecimalString("6256276377282", index, number, 1) == - CHIP_ERROR_INVALID_STRING_LENGTH); + EXPECT_EQ(ManualSetupPayloadParser::ReadDigitsFromDecimalString("6256276377282", index, number, 1), + CHIP_ERROR_INVALID_STRING_LENGTH); } -void TestShortCodeCharLengths(nlTestSuite * inSuite, void * inContext) +TEST(TestManualCode, TestShortCodeCharLengths) { size_t numBits = 1 + kSetupPINCodeFieldLengthInBits + kManualSetupDiscriminatorFieldLengthInBits; size_t manualSetupShortCodeCharLength = static_cast(ceil(log10(pow(2, numBits)))); - NL_TEST_ASSERT(inSuite, manualSetupShortCodeCharLength == kManualSetupShortCodeCharLength); + EXPECT_EQ(manualSetupShortCodeCharLength, size_t(kManualSetupShortCodeCharLength)); size_t manualSetupVendorIdCharLength = static_cast(ceil(log10(pow(2, kVendorIDFieldLengthInBits)))); - NL_TEST_ASSERT(inSuite, manualSetupVendorIdCharLength == kManualSetupVendorIdCharLength); + EXPECT_EQ(manualSetupVendorIdCharLength, size_t(kManualSetupVendorIdCharLength)); size_t manualSetupProductIdCharLength = static_cast(ceil(log10(pow(2, kProductIDFieldLengthInBits)))); - NL_TEST_ASSERT(inSuite, manualSetupProductIdCharLength == kManualSetupProductIdCharLength); + EXPECT_EQ(manualSetupProductIdCharLength, size_t(kManualSetupProductIdCharLength)); size_t manualSetupLongCodeCharLength = kManualSetupShortCodeCharLength + kManualSetupVendorIdCharLength + kManualSetupProductIdCharLength; - NL_TEST_ASSERT(inSuite, manualSetupLongCodeCharLength == kManualSetupLongCodeCharLength); + EXPECT_EQ(manualSetupLongCodeCharLength, size_t(kManualSetupLongCodeCharLength)); } -/** - * Test Suite that lists all the Test functions. - */ -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("Generate Decimal Representation from Partial Payload", TestDecimalRepresentation_PartialPayload), - NL_TEST_DEF("Generate Decimal Representation from Partial Payload (Custom Flow)", TestDecimalRepresentation_PartialPayload_RequiresCustomFlow), - NL_TEST_DEF("Generate Decimal Representation from Full Payload with Zeros", TestDecimalRepresentation_FullPayloadWithZeros), - NL_TEST_DEF("Decimal Representation from Full Payload without Zeros", TestDecimalRepresentation_FullPayloadWithoutZeros_DoesNotRequireCustomFlow), - NL_TEST_DEF("Decimal Representation from Full Payload without Zeros (Custom Flow)", TestDecimalRepresentation_FullPayloadWithoutZeros), - NL_TEST_DEF("Test 12 bit discriminator for manual setup code", TestGenerateAndParser_ManualSetupCodeWithLongDiscriminator), - NL_TEST_DEF("Test Decimal Representation - All Zeros", TestDecimalRepresentation_AllZeros), - NL_TEST_DEF("Test Decimal Representation - All Ones", TestDecimalRepresentation_AllOnes), - NL_TEST_DEF("Parse from Partial Payload", TestPayloadParser_PartialPayload), - NL_TEST_DEF("Parse from Full Payload", TestPayloadParser_FullPayload), - NL_TEST_DEF("Test Invalid Entry To QR Code Parser", TestPayloadParser_InvalidEntry), - NL_TEST_DEF("Test Short Read Write", TestShortCodeReadWrite), - NL_TEST_DEF("Test Long Read Write", TestLongCodeReadWrite), - NL_TEST_DEF("Check Decimal String Validity", TestCheckDecimalStringValidity), - NL_TEST_DEF("Check QR Code Length Validity", TestCheckCodeLengthValidity), - NL_TEST_DEF("Test Decimal String to Number", TestDecimalStringToNumber), - NL_TEST_DEF("Test Short Code Character Lengths", TestShortCodeCharLengths), - NL_TEST_DEF("Test Read Characters from Decimal String", TestReadCharsFromDecimalString), - NL_TEST_DEF("Generate Full Payload and Parse it", TestGenerateAndParser_FullPayload), - NL_TEST_DEF("Generate Partial Payload and Parse it", TestGenerateAndParser_PartialPayload), - - NL_TEST_SENTINEL() -}; -// clang-format on - } // namespace - -/** - * Main - */ -int TestManualSetupCode() -{ - // clang-format off - nlTestSuite theSuite = - { - "chip-manual-code-general-Tests", - &sTests[0], - nullptr, - nullptr - }; - // clang-format on - // Generate machine-readable, comma-separated value (CSV) output. - nl_test_set_output_style(OUTPUT_CSV); - - return chip::ExecuteTestsWithoutContext(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestManualSetupCode); diff --git a/src/setup_payload/tests/TestQRCode.cpp b/src/setup_payload/tests/TestQRCode.cpp index 7bedf282ec82e0..1ec508578dec30 100644 --- a/src/setup_payload/tests/TestQRCode.cpp +++ b/src/setup_payload/tests/TestQRCode.cpp @@ -25,62 +25,60 @@ #include "TestHelpers.h" #include -#include +#include #include -#include -#include using namespace chip; using namespace std; namespace { -void TestRendezvousFlags(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestRendezvousFlags) { SetupPayload inPayload = GetDefaultPayload(); // Not having a value in rendezvousInformation is not allowed for a QR code. inPayload.rendezvousInformation.SetValue(RendezvousInformationFlag::kNone); - NL_TEST_ASSERT(inSuite, CheckWriteRead(inPayload)); + EXPECT_TRUE(CheckWriteRead(inPayload)); inPayload.rendezvousInformation.SetValue(RendezvousInformationFlag::kSoftAP); - NL_TEST_ASSERT(inSuite, CheckWriteRead(inPayload)); + EXPECT_TRUE(CheckWriteRead(inPayload)); inPayload.rendezvousInformation.SetValue(RendezvousInformationFlag::kBLE); - NL_TEST_ASSERT(inSuite, CheckWriteRead(inPayload)); + EXPECT_TRUE(CheckWriteRead(inPayload)); inPayload.rendezvousInformation.SetValue(RendezvousInformationFlag::kOnNetwork); - NL_TEST_ASSERT(inSuite, CheckWriteRead(inPayload)); + EXPECT_TRUE(CheckWriteRead(inPayload)); inPayload.rendezvousInformation.SetValue( RendezvousInformationFlags(RendezvousInformationFlag::kSoftAP, RendezvousInformationFlag::kOnNetwork)); - NL_TEST_ASSERT(inSuite, CheckWriteRead(inPayload)); + EXPECT_TRUE(CheckWriteRead(inPayload)); inPayload.rendezvousInformation.SetValue( RendezvousInformationFlags(RendezvousInformationFlag::kBLE, RendezvousInformationFlag::kOnNetwork)); - NL_TEST_ASSERT(inSuite, CheckWriteRead(inPayload)); + EXPECT_TRUE(CheckWriteRead(inPayload)); inPayload.rendezvousInformation.SetValue(RendezvousInformationFlags( RendezvousInformationFlag::kBLE, RendezvousInformationFlag::kSoftAP, RendezvousInformationFlag::kOnNetwork)); - NL_TEST_ASSERT(inSuite, CheckWriteRead(inPayload)); + EXPECT_TRUE(CheckWriteRead(inPayload)); } -void TestCommissioningFlow(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestCommissioningFlow) { SetupPayload inPayload = GetDefaultPayload(); inPayload.commissioningFlow = CommissioningFlow::kStandard; - NL_TEST_ASSERT(inSuite, CheckWriteRead(inPayload)); + EXPECT_TRUE(CheckWriteRead(inPayload)); inPayload.commissioningFlow = CommissioningFlow::kUserActionRequired; - NL_TEST_ASSERT(inSuite, CheckWriteRead(inPayload)); + EXPECT_TRUE(CheckWriteRead(inPayload)); inPayload.commissioningFlow = CommissioningFlow::kCustom; - NL_TEST_ASSERT(inSuite, CheckWriteRead(inPayload)); + EXPECT_TRUE(CheckWriteRead(inPayload)); } -void TestMaximumValues(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestMaximumValues) { SetupPayload inPayload = GetDefaultPayload(); @@ -93,18 +91,18 @@ void TestMaximumValues(nlTestSuite * inSuite, void * inContext) inPayload.discriminator.SetLongValue(static_cast((1 << kPayloadDiscriminatorFieldLengthInBits) - 1)); inPayload.setUpPINCode = static_cast((1 << kSetupPINCodeFieldLengthInBits) - 1); - NL_TEST_ASSERT(inSuite, CheckWriteRead(inPayload, /* allowInvalidPayload */ true)); + EXPECT_TRUE(CheckWriteRead(inPayload, /* allowInvalidPayload */ true)); } -void TestPayloadByteArrayRep(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestPayloadByteArrayRep) { SetupPayload payload = GetDefaultPayload(); string expected = " 0000 000000000000000100000000000 000010000000 00000001 00 0000000000000001 0000000000001100 000"; - NL_TEST_ASSERT(inSuite, CompareBinary(payload, expected)); + EXPECT_TRUE(CompareBinary(payload, expected)); } -void TestPayloadBase38Rep(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestPayloadBase38Rep) { SetupPayload payload = GetDefaultPayload(); @@ -112,12 +110,12 @@ void TestPayloadBase38Rep(nlTestSuite * inSuite, void * inContext) string result; CHIP_ERROR err = generator.payloadBase38Representation(result); bool didSucceed = err == CHIP_NO_ERROR; - NL_TEST_ASSERT(inSuite, didSucceed == true); + EXPECT_EQ(didSucceed, true); - NL_TEST_ASSERT(inSuite, result == kDefaultPayloadQRCode); + EXPECT_EQ(result, kDefaultPayloadQRCode); } -void TestBase38(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestBase38) { uint8_t input[3] = { 10, 10, 10 }; char encodedBuf[64]; @@ -126,181 +124,181 @@ void TestBase38(nlTestSuite * inSuite, void * inContext) // basic stuff base38Encode(inputSpan.SubSpan(0, 0), encodedSpan); - NL_TEST_ASSERT(inSuite, strlen(encodedBuf) == 0); + EXPECT_EQ(strlen(encodedBuf), 0u); encodedSpan = MutableCharSpan(encodedBuf); base38Encode(inputSpan.SubSpan(0, 1), encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "A0") == 0); + EXPECT_STREQ(encodedBuf, "A0"); encodedSpan = MutableCharSpan(encodedBuf); base38Encode(inputSpan.SubSpan(0, 2), encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "OT10") == 0); + EXPECT_STREQ(encodedBuf, "OT10"); encodedSpan = MutableCharSpan(encodedBuf); base38Encode(inputSpan, encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "-N.B0") == 0); + EXPECT_STREQ(encodedBuf, "-N.B0"); // test null termination of output buffer encodedSpan = MutableCharSpan(encodedBuf); MutableCharSpan subSpan = encodedSpan.SubSpan(0, 2); - NL_TEST_ASSERT(inSuite, base38Encode(inputSpan.SubSpan(0, 1), subSpan) == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(base38Encode(inputSpan.SubSpan(0, 1), subSpan), CHIP_ERROR_BUFFER_TOO_SMALL); // Force no nulls in output buffer memset(encodedSpan.data(), '?', encodedSpan.size()); subSpan = encodedSpan.SubSpan(0, 3); base38Encode(inputSpan.SubSpan(0, 1), subSpan); size_t encodedLen = strnlen(encodedSpan.data(), ArraySize(encodedBuf)); - NL_TEST_ASSERT(inSuite, encodedLen == strlen("A0")); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "A0") == 0); + EXPECT_EQ(encodedLen, strlen("A0")); + EXPECT_STREQ(encodedBuf, "A0"); // passing empty parameters MutableCharSpan emptySpan; encodedSpan = MutableCharSpan(encodedBuf); - NL_TEST_ASSERT(inSuite, base38Encode(inputSpan, emptySpan) == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(base38Encode(inputSpan, emptySpan), CHIP_ERROR_BUFFER_TOO_SMALL); base38Encode(MutableByteSpan(), encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "") == 0); - NL_TEST_ASSERT(inSuite, base38Encode(MutableByteSpan(), emptySpan) == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_STREQ(encodedBuf, ""); + EXPECT_EQ(base38Encode(MutableByteSpan(), emptySpan), CHIP_ERROR_BUFFER_TOO_SMALL); // test single odd byte corner conditions encodedSpan = MutableCharSpan(encodedBuf); input[2] = 0; base38Encode(inputSpan, encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "OT100") == 0); + EXPECT_STREQ(encodedBuf, "OT100"); input[2] = 40; encodedSpan = MutableCharSpan(encodedBuf); base38Encode(inputSpan, encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "Y6V91") == 0); + EXPECT_STREQ(encodedBuf, "Y6V91"); input[2] = 41; encodedSpan = MutableCharSpan(encodedBuf); base38Encode(inputSpan, encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "KL0B1") == 0); + EXPECT_STREQ(encodedBuf, "KL0B1"); input[2] = 255; encodedSpan = MutableCharSpan(encodedBuf); base38Encode(inputSpan, encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "Q-M08") == 0); + EXPECT_STREQ(encodedBuf, "Q-M08"); // verify chunks of 1,2 and 3 bytes result in fixed-length strings padded with '0' // for 1 byte we need always 2 characters input[0] = 35; encodedSpan = MutableCharSpan(encodedBuf); base38Encode(inputSpan.SubSpan(0, 1), encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "Z0") == 0); + EXPECT_STREQ(encodedBuf, "Z0"); // for 2 bytes we need always 4 characters input[0] = 255; input[1] = 0; encodedSpan = MutableCharSpan(encodedBuf); base38Encode(inputSpan.SubSpan(0, 2), encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "R600") == 0); + EXPECT_STREQ(encodedBuf, "R600"); // for 3 bytes we need always 5 characters input[0] = 46; input[1] = 0; input[2] = 0; encodedSpan = MutableCharSpan(encodedBuf); base38Encode(inputSpan, encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "81000") == 0); + EXPECT_STREQ(encodedBuf, "81000"); // verify maximum available values for each chunk size to check selecting proper characters number // for 1 byte we need 2 characters input[0] = 255; encodedSpan = MutableCharSpan(encodedBuf); base38Encode(inputSpan.SubSpan(0, 1), encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "R6") == 0); + EXPECT_STREQ(encodedBuf, "R6"); // for 2 bytes we need 4 characters input[0] = 255; input[1] = 255; encodedSpan = MutableCharSpan(encodedBuf); base38Encode(inputSpan.SubSpan(0, 2), encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "NE71") == 0); + EXPECT_STREQ(encodedBuf, "NE71"); // for 3 bytes we need 5 characters input[0] = 255; input[1] = 255; input[2] = 255; encodedSpan = MutableCharSpan(encodedBuf); base38Encode(inputSpan, encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "PLS18") == 0); + EXPECT_STREQ(encodedBuf, "PLS18"); // fun with strings encodedSpan = MutableCharSpan(encodedBuf); base38Encode(ByteSpan((uint8_t *) "Hello World!", sizeof("Hello World!") - 1), encodedSpan); - NL_TEST_ASSERT(inSuite, strcmp(encodedBuf, "KKHF3W2S013OPM3EJX11") == 0); + EXPECT_STREQ(encodedBuf, "KKHF3W2S013OPM3EJX11"); vector decoded = vector(); - NL_TEST_ASSERT(inSuite, base38Decode("KKHF3W2S013OPM3EJX11", decoded) == CHIP_NO_ERROR); + EXPECT_EQ(base38Decode("KKHF3W2S013OPM3EJX11", decoded), CHIP_NO_ERROR); string hello_world; for (uint8_t b : decoded) { hello_world += static_cast(b); } - NL_TEST_ASSERT(inSuite, hello_world == "Hello World!"); + EXPECT_EQ(hello_world, "Hello World!"); // short input - NL_TEST_ASSERT(inSuite, base38Decode("A0", decoded) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, decoded.size() == 1); - NL_TEST_ASSERT(inSuite, decoded[0] == 10); + EXPECT_EQ(base38Decode("A0", decoded), CHIP_NO_ERROR); + EXPECT_TRUE(decoded.size()); + EXPECT_EQ(decoded[0], 10u); // empty == empty - NL_TEST_ASSERT(inSuite, base38Decode("", decoded) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, decoded.empty()); + EXPECT_EQ(base38Decode("", decoded), CHIP_NO_ERROR); + EXPECT_TRUE(decoded.empty()); // test invalid characters - NL_TEST_ASSERT(inSuite, base38Decode("0\001", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("\0010", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("[0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("0[", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode(" 0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("!0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("\"0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("#0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("$0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("%0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("&0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("'0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("(0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode(")0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("*0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("+0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode(",0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode(";0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("<0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("=0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode(">0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); - NL_TEST_ASSERT(inSuite, base38Decode("@0", decoded) == CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("0\001", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("\0010", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("[0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("0[", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode(" 0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("!0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("\"0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("#0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("$0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("%0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("&0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("'0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("(0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode(")0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("*0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("+0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode(",0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode(";0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("<0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("=0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode(">0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); + EXPECT_EQ(base38Decode("@0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE); // test strings that encode maximum values - NL_TEST_ASSERT(inSuite, base38Decode("R6", decoded) == CHIP_NO_ERROR); // this is 0xFF - NL_TEST_ASSERT(inSuite, decoded == std::vector({ 255 })); - NL_TEST_ASSERT(inSuite, base38Decode("S6", decoded) == CHIP_ERROR_INVALID_ARGUMENT); // trying to encode 0xFF + 1 in 2 chars - NL_TEST_ASSERT(inSuite, base38Decode("S600", decoded) == CHIP_NO_ERROR); // this is 0xFF + 1, needs 4 chars - NL_TEST_ASSERT(inSuite, decoded == std::vector({ 0, 1 })); - NL_TEST_ASSERT(inSuite, base38Decode("NE71", decoded) == CHIP_NO_ERROR); // this is 0xFFFF - NL_TEST_ASSERT(inSuite, decoded == std::vector({ 255, 255 })); - NL_TEST_ASSERT(inSuite, base38Decode("OE71", decoded) == CHIP_ERROR_INVALID_ARGUMENT); // trying to encode 0xFFFF + 1 in 4 chars - NL_TEST_ASSERT(inSuite, base38Decode("OE710", decoded) == CHIP_NO_ERROR); // this is 0xFFFF + 1, needs 5 chars - NL_TEST_ASSERT(inSuite, decoded == std::vector({ 0, 0, 1 })); - NL_TEST_ASSERT(inSuite, base38Decode("PLS18", decoded) == CHIP_NO_ERROR); // this is 0xFFFFFF - NL_TEST_ASSERT(inSuite, decoded == std::vector({ 255, 255, 255 })); - NL_TEST_ASSERT(inSuite, base38Decode("QLS18", decoded) == CHIP_ERROR_INVALID_ARGUMENT); // trying to encode 0xFFFFFF + 1 + EXPECT_EQ(base38Decode("R6", decoded), CHIP_NO_ERROR); // this is 0xFF + EXPECT_EQ(decoded, std::vector({ 255 })); + EXPECT_EQ(base38Decode("S6", decoded), CHIP_ERROR_INVALID_ARGUMENT); // trying to encode 0xFF + 1 in 2 chars + EXPECT_EQ(base38Decode("S600", decoded), CHIP_NO_ERROR); // this is 0xFF + 1, needs 4 chars + EXPECT_EQ(decoded, std::vector({ 0, 1 })); + EXPECT_EQ(base38Decode("NE71", decoded), CHIP_NO_ERROR); // this is 0xFFFF + EXPECT_EQ(decoded, std::vector({ 255, 255 })); + EXPECT_EQ(base38Decode("OE71", decoded), CHIP_ERROR_INVALID_ARGUMENT); // trying to encode 0xFFFF + 1 in 4 chars + EXPECT_EQ(base38Decode("OE710", decoded), CHIP_NO_ERROR); // this is 0xFFFF + 1, needs 5 chars + EXPECT_EQ(decoded, std::vector({ 0, 0, 1 })); + EXPECT_EQ(base38Decode("PLS18", decoded), CHIP_NO_ERROR); // this is 0xFFFFFF + EXPECT_EQ(decoded, std::vector({ 255, 255, 255 })); + EXPECT_EQ(base38Decode("QLS18", decoded), CHIP_ERROR_INVALID_ARGUMENT); // trying to encode 0xFFFFFF + 1 } -void TestBitsetLen(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestBitsetLen) { - NL_TEST_ASSERT(inSuite, kTotalPayloadDataSizeInBits % 8 == 0); + EXPECT_FALSE(kTotalPayloadDataSizeInBits % 8); } -void TestSetupPayloadVerify(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestSetupPayloadVerify) { SetupPayload payload = GetDefaultPayload(); - NL_TEST_ASSERT(inSuite, payload.isValidQRCodePayload() == true); + EXPECT_EQ(payload.isValidQRCodePayload(), true); // test invalid commissioning flow SetupPayload test_payload = payload; test_payload.commissioningFlow = CommissioningFlow::kCustom; - NL_TEST_ASSERT(inSuite, test_payload.isValidQRCodePayload()); + EXPECT_TRUE(test_payload.isValidQRCodePayload()); test_payload.commissioningFlow = static_cast(1 << kCommissioningFlowFieldLengthInBits); - NL_TEST_ASSERT(inSuite, test_payload.isValidQRCodePayload() == false); + EXPECT_EQ(test_payload.isValidQRCodePayload(), false); // test invalid version test_payload = payload; test_payload.version = 1 << kVersionFieldLengthInBits; - NL_TEST_ASSERT(inSuite, test_payload.isValidQRCodePayload() == false); + EXPECT_EQ(test_payload.isValidQRCodePayload(), false); // test invalid rendezvousInformation test_payload = payload; @@ -308,15 +306,15 @@ void TestSetupPayloadVerify(nlTestSuite * inSuite, void * inContext) RendezvousInformationFlag::kBLE, RendezvousInformationFlag::kSoftAP, RendezvousInformationFlag::kOnNetwork); invalid.SetRaw(static_cast(invalid.Raw() + 1)); test_payload.rendezvousInformation.SetValue(invalid); - NL_TEST_ASSERT(inSuite, test_payload.isValidQRCodePayload() == false); + EXPECT_EQ(test_payload.isValidQRCodePayload(), false); // test invalid setup PIN test_payload = payload; test_payload.setUpPINCode = 1 << kSetupPINCodeFieldLengthInBits; - NL_TEST_ASSERT(inSuite, test_payload.isValidQRCodePayload() == false); + EXPECT_EQ(test_payload.isValidQRCodePayload(), false); } -void TestInvalidQRCodePayload_WrongCharacterSet(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestInvalidQRCodePayload_WrongCharacterSet) { string invalidString = kDefaultPayloadQRCode; invalidString.back() = ' '; // space is not contained in the base38 alphabet @@ -325,11 +323,11 @@ void TestInvalidQRCodePayload_WrongCharacterSet(nlTestSuite * inSuite, void * in SetupPayload payload; CHIP_ERROR err = parser.populatePayload(payload); bool didFail = err != CHIP_NO_ERROR; - NL_TEST_ASSERT(inSuite, didFail == true); - NL_TEST_ASSERT(inSuite, payload.isValidQRCodePayload() == false); + EXPECT_EQ(didFail, true); + EXPECT_EQ(payload.isValidQRCodePayload(), false); } -void TestInvalidQRCodePayload_WrongLength(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestInvalidQRCodePayload_WrongLength) { string invalidString = kDefaultPayloadQRCode; invalidString.pop_back(); @@ -338,19 +336,19 @@ void TestInvalidQRCodePayload_WrongLength(nlTestSuite * inSuite, void * inContex SetupPayload payload; CHIP_ERROR err = parser.populatePayload(payload); bool didFail = err != CHIP_NO_ERROR; - NL_TEST_ASSERT(inSuite, didFail == true); - NL_TEST_ASSERT(inSuite, payload.isValidQRCodePayload() == false); + EXPECT_EQ(didFail, true); + EXPECT_EQ(payload.isValidQRCodePayload(), false); } -void TestPayloadEquality(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestPayloadEquality) { SetupPayload payload = GetDefaultPayload(); SetupPayload equalPayload = GetDefaultPayload(); - NL_TEST_ASSERT(inSuite, payload == equalPayload); + EXPECT_TRUE(payload == equalPayload); } -void TestPayloadInEquality(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestPayloadInEquality) { SetupPayload payload = GetDefaultPayload(); @@ -358,10 +356,10 @@ void TestPayloadInEquality(nlTestSuite * inSuite, void * inContext) unequalPayload.discriminator.SetLongValue(28); unequalPayload.setUpPINCode = 121233; - NL_TEST_ASSERT(inSuite, !(payload == unequalPayload)); + EXPECT_FALSE(payload == unequalPayload); } -void TestQRCodeToPayloadGeneration(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestQRCodeToPayloadGeneration) { SetupPayload payload = GetDefaultPayload(); @@ -369,89 +367,39 @@ void TestQRCodeToPayloadGeneration(nlTestSuite * inSuite, void * inContext) string base38Rep; CHIP_ERROR err = generator.payloadBase38Representation(base38Rep); bool didSucceed = err == CHIP_NO_ERROR; - NL_TEST_ASSERT(inSuite, didSucceed == true); + EXPECT_EQ(didSucceed, true); SetupPayload resultingPayload; QRCodeSetupPayloadParser parser(base38Rep); err = parser.populatePayload(resultingPayload); didSucceed = err == CHIP_NO_ERROR; - NL_TEST_ASSERT(inSuite, didSucceed == true); - NL_TEST_ASSERT(inSuite, resultingPayload.isValidQRCodePayload() == true); + EXPECT_EQ(didSucceed, true); + EXPECT_EQ(resultingPayload.isValidQRCodePayload(), true); bool result = payload == resultingPayload; - NL_TEST_ASSERT(inSuite, result == true); + EXPECT_EQ(result, true); } -void TestExtractPayload(nlTestSuite * inSuite, void * inContext) +TEST(TestQRCode, TestExtractPayload) { - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("MT:ABC")) == string("ABC")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("MT:")) == string("")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("H:")) == string("")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("ASMT:")) == string("")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("Z%MT:ABC%")) == string("ABC")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("Z%MT:ABC")) == string("ABC")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("%Z%MT:ABC")) == string("ABC")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("%Z%MT:ABC%")) == string("ABC")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("%Z%MT:ABC%DDD")) == string("ABC")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("MT:ABC%DDD")) == string("ABC")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("MT:ABC%")) == string("ABC")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("%MT:")) == string("")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("%MT:%")) == string("")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("A%")) == string("")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("MT:%")) == string("")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("%MT:ABC")) == string("ABC")); - NL_TEST_ASSERT(inSuite, QRCodeSetupPayloadParser::ExtractPayload(string("ABC")) == string("")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("MT:ABC")), string("ABC")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("MT:")), string("")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("H:")), string("")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("ASMT:")), string("")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("Z%MT:ABC%")), string("ABC")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("Z%MT:ABC")), string("ABC")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("%Z%MT:ABC")), string("ABC")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("%Z%MT:ABC%")), string("ABC")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("%Z%MT:ABC%DDD")), string("ABC")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("MT:ABC%DDD")), string("ABC")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("MT:ABC%")), string("ABC")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("%MT:")), string("")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("%MT:%")), string("")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("A%")), string("")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("MT:%")), string("")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("%MT:ABC")), string("ABC")); + EXPECT_EQ(QRCodeSetupPayloadParser::ExtractPayload(string("ABC")), string("")); } -// Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("Test Rendezvous Flags", TestRendezvousFlags), - NL_TEST_DEF("Test Commissioning Flow", TestCommissioningFlow), - NL_TEST_DEF("Test Maximum Values", TestMaximumValues), - NL_TEST_DEF("Test Base 38", TestBase38), - NL_TEST_DEF("Test Bitset Length", TestBitsetLen), - NL_TEST_DEF("Test Payload Byte Array Representation", TestPayloadByteArrayRep), - NL_TEST_DEF("Test Payload Base 38 Representation", TestPayloadBase38Rep), - NL_TEST_DEF("Test Setup Payload Verify", TestSetupPayloadVerify), - NL_TEST_DEF("Test Payload Equality", TestPayloadEquality), - NL_TEST_DEF("Test Payload Inequality", TestPayloadInEquality), - NL_TEST_DEF("Test QRCode to Payload Generation", TestQRCodeToPayloadGeneration), - NL_TEST_DEF("Test Invalid QR Code Payload - Wrong Character Set", TestInvalidQRCodePayload_WrongCharacterSet), - NL_TEST_DEF("Test Invalid QR Code Payload - Wrong Length", TestInvalidQRCodePayload_WrongLength), - NL_TEST_DEF("Test Extract Payload", TestExtractPayload), - - NL_TEST_SENTINEL() -}; -// clang-format on - } // namespace - -/** - * Main - */ -int TestQuickResponseCode() -{ - // clang-format off - nlTestSuite theSuite = - { - "chip-qrcode-general-tests", - &sTests[0], - nullptr, - nullptr - }; - // clang-format on - - // Generate machine-readable, comma-separated value (CSV) output. - nl_test_set_output_style(OUTPUT_CSV); - - return chip::ExecuteTestsWithoutContext(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestQuickResponseCode); diff --git a/src/system/SystemPacketBuffer.h b/src/system/SystemPacketBuffer.h index 88db4196438c1d..513f0b4fbc0cdb 100644 --- a/src/system/SystemPacketBuffer.h +++ b/src/system/SystemPacketBuffer.h @@ -44,8 +44,6 @@ #include #endif // CHIP_SYSTEM_CONFIG_USE_LWIP -class PacketBufferTest; - namespace chip { namespace System { @@ -392,7 +390,7 @@ class DLL_EXPORT PacketBuffer : private pbuf const uint8_t * ReserveStart() const; friend class PacketBufferHandle; - friend class ::PacketBufferTest; + friend class TestSystemPacketBuffer; }; static_assert(sizeof(pbuf) == sizeof(PacketBuffer), "PacketBuffer must not have additional members"); @@ -687,7 +685,7 @@ class DLL_EXPORT PacketBufferHandle PacketBuffer * Get() const { return mBuffer; } - bool operator==(const PacketBufferHandle & aOther) { return mBuffer == aOther.mBuffer; } + bool operator==(const PacketBufferHandle & aOther) const { return mBuffer == aOther.mBuffer; } #if CHIP_SYSTEM_PACKETBUFFER_HAS_RIGHTSIZE void InternalRightSize(); @@ -696,7 +694,7 @@ class DLL_EXPORT PacketBufferHandle PacketBuffer * mBuffer; friend class PacketBuffer; - friend class ::PacketBufferTest; + friend class TestSystemPacketBuffer; }; inline void PacketBuffer::SetDataLength(uint16_t aNewLen, const PacketBufferHandle & aChainHead) diff --git a/src/system/SystemTimer.h b/src/system/SystemTimer.h index c512a0c845ddd6..698be028ce029a 100644 --- a/src/system/SystemTimer.h +++ b/src/system/SystemTimer.h @@ -44,7 +44,6 @@ namespace chip { namespace System { class Layer; -class TestTimer; /** * Basic Timer information: time and callback. @@ -238,7 +237,7 @@ class TimerPool } private: - friend class TestTimer; + friend class TestSystemTimer_CheckTimerPool_Test; ObjectPool mTimerPool; }; diff --git a/src/system/tests/BUILD.gn b/src/system/tests/BUILD.gn index 4e5e129c7351f7..2f2fd4de0a6a6d 100644 --- a/src/system/tests/BUILD.gn +++ b/src/system/tests/BUILD.gn @@ -14,11 +14,10 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libSystemLayerTests" test_sources = [ @@ -47,9 +46,7 @@ chip_test_suite_using_nltest("tests") { public_deps = [ "${chip_root}/src/inet", - "${chip_root}/src/lib/support:testing_nlunit", "${chip_root}/src/platform", "${chip_root}/src/system", - "${nlunit_test_root}:nlunit-test", ] } diff --git a/src/system/tests/TestSystemClock.cpp b/src/system/tests/TestSystemClock.cpp index 63fcfaa3566e5d..84d701a17d3323 100644 --- a/src/system/tests/TestSystemClock.cpp +++ b/src/system/tests/TestSystemClock.cpp @@ -15,14 +15,13 @@ * limitations under the License. */ -#include +#include #include #include #include -#include -#include #include +#include #if !CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_TIME @@ -41,18 +40,18 @@ using namespace chip::System; namespace { -void TestRealClock(nlTestSuite * inSuite, void * inContext) +TEST(TestSystemClock, TestRealClock) { Clock::Milliseconds64 oldMilli = SystemClock().GetMonotonicMilliseconds64(); Clock::Milliseconds64 newMilli = SystemClock().GetMonotonicMilliseconds64(); - NL_TEST_ASSERT(inSuite, newMilli >= oldMilli); + EXPECT_GE(newMilli, oldMilli); Clock::Microseconds64 oldMicro = SystemClock().GetMonotonicMicroseconds64(); Clock::Microseconds64 newMicro = SystemClock().GetMonotonicMicroseconds64(); - NL_TEST_ASSERT(inSuite, newMicro >= oldMicro); + EXPECT_GE(newMicro, oldMicro); Clock::Microseconds64::rep microseconds = newMicro.count(); - NL_TEST_ASSERT(inSuite, (microseconds & 0x8000'0000'0000'0000) == 0); + EXPECT_EQ((microseconds & 0x8000'0000'0000'0000), 0UL); #if !CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_TIME && \ (CHIP_SYSTEM_CONFIG_USE_LWIP_MONOTONIC_TIME || CHIP_SYSTEM_CONFIG_USE_POSIX_TIME_FUNCTS) @@ -65,62 +64,35 @@ void TestRealClock(nlTestSuite * inSuite, void * inContext) #if CHIP_SYSTEM_CONFIG_USE_POSIX_TIME_FUNCTS struct timespec delay = { 0, kDelayMilliseconds * chip::kNanosecondsPerMillisecond }; while (nanosleep(&delay, &delay) == -1 && errno == EINTR) - { - } + continue; #endif // CHIP_SYSTEM_CONFIG_USE_POSIX_TIME_FUNCTS newMilli = SystemClock().GetMonotonicMilliseconds64(); - NL_TEST_ASSERT(inSuite, newMilli > oldMilli); + EXPECT_GT(newMilli, oldMilli); newMicro = SystemClock().GetMonotonicMicroseconds64(); - NL_TEST_ASSERT(inSuite, newMicro > oldMicro); + EXPECT_GT(newMicro, oldMicro); -#endif // !CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_TIME && (CHIP_SYSTEM_CONFIG_USE_LWIP_MONOTONIC_TIME || - // CHIP_SYSTEM_CONFIG_USE_POSIX_TIME_FUNCTS) +#endif // !CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_TIME && + // (CHIP_SYSTEM_CONFIG_USE_LWIP_MONOTONIC_TIME || CHIP_SYSTEM_CONFIG_USE_POSIX_TIME_FUNCTS) } -void TestMockClock(nlTestSuite * inSuite, void * inContext) +TEST(TestSystemClock, TestMockClock) { Clock::Internal::MockClock clock; Clock::ClockBase * savedRealClock = &SystemClock(); Clock::Internal::SetSystemClockForTesting(&clock); - NL_TEST_ASSERT(inSuite, SystemClock().GetMonotonicMilliseconds64() == Clock::kZero); - NL_TEST_ASSERT(inSuite, SystemClock().GetMonotonicMicroseconds64() == Clock::kZero); + EXPECT_EQ(SystemClock().GetMonotonicMilliseconds64(), Clock::kZero); + EXPECT_EQ(SystemClock().GetMonotonicMicroseconds64(), Clock::kZero); constexpr Clock::Milliseconds64 k1234 = Clock::Milliseconds64(1234); clock.SetMonotonic(k1234); - NL_TEST_ASSERT(inSuite, SystemClock().GetMonotonicMilliseconds64() == k1234); - NL_TEST_ASSERT(inSuite, SystemClock().GetMonotonicMicroseconds64() == k1234); + EXPECT_EQ(SystemClock().GetMonotonicMilliseconds64(), k1234); + EXPECT_EQ(SystemClock().GetMonotonicMicroseconds64(), k1234); Clock::Internal::SetSystemClockForTesting(savedRealClock); } } // namespace - -/** - * Test Suite. It lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("TestRealClock", TestRealClock), - NL_TEST_DEF("TestMockClock", TestMockClock), - NL_TEST_SENTINEL() -}; -// clang-format on - -int TestSystemClock() -{ - nlTestSuite theSuite = { - "chip-systemclock", &sTests[0], nullptr /* setup */, nullptr /* teardown */ - }; - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr /* context */); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestSystemClock) diff --git a/src/system/tests/TestSystemErrorStr.cpp b/src/system/tests/TestSystemErrorStr.cpp index 0296eb957c5dea..bf6321fe0a4e9a 100644 --- a/src/system/tests/TestSystemErrorStr.cpp +++ b/src/system/tests/TestSystemErrorStr.cpp @@ -28,34 +28,28 @@ #include #include +#include + #include #include #include -#include - -#include using namespace chip; // Test input data. - -// clang-format off -static const CHIP_ERROR kTestElements[] = -{ +static const CHIP_ERROR kTestElements[] = { CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE, CHIP_ERROR_INVALID_ARGUMENT, CHIP_ERROR_INCORRECT_STATE, CHIP_ERROR_UNEXPECTED_EVENT, CHIP_ERROR_NO_MEMORY, CHIP_ERROR_REAL_TIME_NOT_SYNCED, - CHIP_ERROR_ACCESS_DENIED + CHIP_ERROR_ACCESS_DENIED, }; -// clang-format on -static void CheckSystemErrorStr(nlTestSuite * inSuite, void * inContext) +TEST(TestSystemErrorStr, CheckSystemErrorStr) { // Register the layer error formatter - RegisterCHIPLayerErrorFormatter(); // For each defined error... @@ -66,45 +60,12 @@ static void CheckSystemErrorStr(nlTestSuite * inSuite, void * inContext) // Assert that the error string contains the error number in hex. snprintf(expectedText, sizeof(expectedText), "%08" PRIX32, err.AsInteger()); - NL_TEST_ASSERT(inSuite, (strstr(errStr, expectedText) != nullptr)); + EXPECT_NE(strstr(errStr, expectedText), nullptr); #if !CHIP_CONFIG_SHORT_ERROR_STR // Assert that the error string contains a description, which is signaled // by a presence of a colon proceeding the description. - NL_TEST_ASSERT(inSuite, (strchr(errStr, ':') != nullptr)); + EXPECT_NE(strchr(errStr, ':'), nullptr); #endif // !CHIP_CONFIG_SHORT_ERROR_STR } } - -/** - * Test Suite. It lists all the test functions. - */ - -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("SystemErrorStr", CheckSystemErrorStr), - - NL_TEST_SENTINEL() -}; -// clang-format on - -int TestSystemErrorStr() -{ - // clang-format off - nlTestSuite theSuite = - { - "System-Error-Strings", - &sTests[0], - nullptr, - nullptr - }; - // clang-format on - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestSystemErrorStr) diff --git a/src/system/tests/TestSystemPacketBuffer.cpp b/src/system/tests/TestSystemPacketBuffer.cpp index 527d3a19a32e4b..5b3f709a5bee67 100644 --- a/src/system/tests/TestSystemPacketBuffer.cpp +++ b/src/system/tests/TestSystemPacketBuffer.cpp @@ -30,10 +30,10 @@ #include #include +#include + #include #include -#include -#include #include #include @@ -42,8 +42,6 @@ #include #endif // CHIP_SYSTEM_CONFIG_USE_LWIP -#include - #if CHIP_SYSTEM_CONFIG_USE_LWIP #if (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0) #define PBUF_TYPE(pbuf) (pbuf)->type @@ -73,63 +71,49 @@ void ScrambleData(uint8_t * start, uint16_t length) } } // namespace +namespace chip { +namespace System { + /* - * An instance of this class created for the test suite. - * It is a friend class of `PacketBuffer` and `PacketBufferHandle` because some tests + * This class is a friend class of `PacketBuffer` and `PacketBufferHandle` because some tests * use or check private methods or properties. */ -class PacketBufferTest +class TestSystemPacketBuffer : public ::testing::Test { public: - struct TestContext + static constexpr auto kBlockSize = PacketBuffer::kBlockSize; + static constexpr auto kStructureSize = PacketBuffer::kStructureSize; + + static constexpr uint16_t kReservedSizes[] = { 0, 10, 128, 1536, PacketBuffer::kMaxSizeWithoutReserve, kBlockSize }; + static constexpr uint16_t kLengths[] = { 0, 1, 10, 128, kBlockSize, UINT16_MAX }; + + static void SetUpTestSuite() { - const uint16_t * const reserved_sizes; - size_t reserved_size_count; - const uint16_t * const lengths; - size_t length_count; - PacketBufferTest * test; - }; + ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); + ASSERT_EQ(chip::DeviceLayer::PlatformMgr().InitChipStack(), CHIP_NO_ERROR); + } + + static void TearDownTestSuite() + { + chip::DeviceLayer::PlatformMgr().Shutdown(); + chip::Platform::MemoryShutdown(); + } - static int TestSetup(void * inContext); - static int TestTeardown(void * inContext); - static int TestInitialize(void * inContext); - static int TestTerminate(void * inContext); - - static void CheckNew(nlTestSuite * inSuite, void * inContext); - static void CheckStart(nlTestSuite * inSuite, void * inContext); - static void CheckSetStart(nlTestSuite * inSuite, void * inContext); - static void CheckDataLength(nlTestSuite * inSuite, void * inContext); - static void CheckSetDataLength(nlTestSuite * inSuite, void * inContext); - static void CheckTotalLength(nlTestSuite * inSuite, void * inContext); - static void CheckMaxDataLength(nlTestSuite * inSuite, void * inContext); - static void CheckAvailableDataLength(nlTestSuite * inSuite, void * inContext); - static void CheckReservedSize(nlTestSuite * inSuite, void * inContext); - static void CheckHasChainedBuffer(nlTestSuite * inSuite, void * inContext); - static void CheckAddToEnd(nlTestSuite * inSuite, void * inContext); - static void CheckPopHead(nlTestSuite * inSuite, void * inContext); - static void CheckCompactHead(nlTestSuite * inSuite, void * inContext); - static void CheckConsumeHead(nlTestSuite * inSuite, void * inContext); - static void CheckConsume(nlTestSuite * inSuite, void * inContext); - static void CheckEnsureReservedSize(nlTestSuite * inSuite, void * inContext); - static void CheckAlignPayload(nlTestSuite * inSuite, void * inContext); - static void CheckNext(nlTestSuite * inSuite, void * inContext); - static void CheckLast(nlTestSuite * inSuite, void * inContext); - static void CheckRead(nlTestSuite * inSuite, void * inContext); - static void CheckAddRef(nlTestSuite * inSuite, void * inContext); - static void CheckFree(nlTestSuite * inSuite, void * inContext); - static void CheckFreeHead(nlTestSuite * inSuite, void * inContext); - static void CheckHandleConstruct(nlTestSuite * inSuite, void * inContext); - static void CheckHandleMove(nlTestSuite * inSuite, void * inContext); - static void CheckHandleRelease(nlTestSuite * inSuite, void * inContext); - static void CheckHandleFree(nlTestSuite * inSuite, void * inContext); - static void CheckHandleRetain(nlTestSuite * inSuite, void * inContext); - static void CheckHandleAdopt(nlTestSuite * inSuite, void * inContext); - static void CheckHandleHold(nlTestSuite * inSuite, void * inContext); - static void CheckHandleAdvance(nlTestSuite * inSuite, void * inContext); - static void CheckHandleRightSize(nlTestSuite * inSuite, void * inContext); - static void CheckHandleCloneData(nlTestSuite * inSuite, void * inContext); - static void CheckPacketBufferWriter(nlTestSuite * inSuite, void * inContext); - static void CheckBuildFreeList(nlTestSuite * inSuite, void * inContext); + void SetUp() + { + configurations.resize(0); + // Set up the buffer configuration vector for this suite. + for (auto size : kReservedSizes) + { + configurations.emplace_back(size); + } + } + + void TearDown() + { + ASSERT_TRUE(ResetConfigurations()); + ASSERT_TRUE(ResetHandles()); + } static void PrintHandle(const char * tag, const PacketBuffer * buffer) { @@ -138,9 +122,6 @@ class PacketBufferTest } static void PrintHandle(const char * tag, const PacketBufferHandle & handle) { PrintHandle(tag, handle.mBuffer); } - static constexpr uint16_t kBlockSize = PacketBuffer::kBlockSize; - -private: struct BufferConfiguration { BufferConfiguration(uint16_t aReservedSize = 0) : @@ -164,12 +145,6 @@ class PacketBufferTest PrintHandle("", config.handle); } - PacketBufferTest(TestContext * context); - ~PacketBufferTest(); - - int InitializeTest(TestContext * context); - int TerminateTest(TestContext * context); - /* * Buffers allocated through PrepareTestBuffer with kRecordHandle set will be recorded in `handles` so that their * reference counts can be verified by ResetHandles(). Initially they have two refs: the recorded one and the returned one. @@ -182,103 +157,54 @@ class PacketBufferTest * Checks and clears the recorded handles. Returns true if it detects no leaks or double frees. * Called from `TerminateTest()`, but tests may choose to call it more often to verify reference counts. */ + bool ResetConfigurations(); bool ResetHandles(); - TestContext * mContext; std::vector configurations; std::vector handles; -}; - -const uint16_t sTestReservedSizes[] = { 0, 10, 128, 1536, PacketBuffer::kMaxSizeWithoutReserve, PacketBufferTest::kBlockSize }; -const uint16_t sTestLengths[] = { 0, 1, 10, 128, PacketBufferTest::kBlockSize, UINT16_MAX }; -PacketBufferTest::TestContext sContext = { - sTestReservedSizes, - sizeof(sTestReservedSizes) / sizeof(uint16_t), - sTestLengths, - sizeof(sTestLengths) / sizeof(uint16_t), + void CheckAddRef(); + void CheckAddToEnd(); + void CheckCompactHead(); + void CheckConsume(); + void CheckConsumeHead(); + void CheckDataLength(); + void CheckEnsureReservedSize(); + void CheckFree(); + void CheckFreeHead(); + void CheckHandleAdopt(); + void CheckHandleAdvance(); + void CheckHandleCloneData(); + void CheckHandleConstruct(); + void CheckHandleFree(); + void CheckHandleHold(); + void CheckHandleMove(); + void CheckHandleRelease(); + void CheckHandleRetain(); + void CheckHandleRightSize(); + void CheckLast(); + void CheckNew(); + void CheckNext(); + void CheckPopHead(); + void CheckRead(); + void CheckSetDataLength(); + void CheckSetStart(); }; -PacketBufferTest::PacketBufferTest(TestContext * context) : mContext(context) -{ - // Set up the buffer configuration vector for this suite. - configurations.resize(0); - for (size_t i = 0; i < mContext->reserved_size_count; ++i) - { - configurations.emplace_back(mContext->reserved_sizes[i]); - } -} - -int PacketBufferTest::TestSetup(void * inContext) -{ - chip::Platform::MemoryInit(); - - if (chip::DeviceLayer::PlatformMgr().InitChipStack() != CHIP_NO_ERROR) - return FAILURE; - - TestContext * const theContext = reinterpret_cast(inContext); - theContext->test = new (std::nothrow) PacketBufferTest(theContext); - if (theContext->test == nullptr) - { - return FAILURE; - } - return SUCCESS; -} - -int PacketBufferTest::TestTeardown(void * inContext) -{ - chip::DeviceLayer::PlatformMgr().Shutdown(); - - chip::Platform::MemoryShutdown(); - - return SUCCESS; -} - -int PacketBufferTest::TestInitialize(void * inContext) -{ - TestContext * const theContext = reinterpret_cast(inContext); - if (theContext->test == nullptr) - { - return FAILURE; - } - return theContext->test->InitializeTest(theContext); -} - -int PacketBufferTest::InitializeTest(TestContext * context) -{ - if (context != mContext) - { - return FAILURE; - } - return SUCCESS; -} - -int PacketBufferTest::TestTerminate(void * inContext) -{ - TestContext * const theContext = reinterpret_cast(inContext); - if (theContext->test == nullptr) - { - return FAILURE; - } - return theContext->test->TerminateTest(theContext); -} - -int PacketBufferTest::TerminateTest(TestContext * context) -{ - const bool context_ok = (context == mContext); - // Clear the configurations' bufffer handles. - for (auto & configuration : configurations) - { - configuration.handle = nullptr; - } - const bool handles_ok = ResetHandles(); - return (context_ok && handles_ok) ? SUCCESS : FAILURE; -} +/* + * Run fixture's class function as a test. + */ +#define TEST_F_FROM_FIXTURE(test_fixture, test_name) \ + TEST_F(test_fixture, test_name) \ + { \ + test_name(); \ + } \ + void test_fixture::test_name() /** * Allocate memory for a test buffer and configure according to test buffer configuration. */ -void PacketBufferTest::PrepareTestBuffer(BufferConfiguration * config, int flags) +void TestSystemPacketBuffer::PrepareTestBuffer(BufferConfiguration * config, int flags) { if (config->handle.IsNull()) { @@ -300,11 +226,11 @@ void PacketBufferTest::PrepareTestBuffer(BufferConfiguration * config, int flags exit(EXIT_FAILURE); } - const size_t lInitialSize = PacketBuffer::kStructureSize + config->reserved_size; + const size_t lInitialSize = kStructureSize + config->reserved_size; const size_t lAllocSize = kBlockSize; uint8_t * const raw = reinterpret_cast(config->handle.Get()); - memset(raw + PacketBuffer::kStructureSize, 0, lAllocSize - PacketBuffer::kStructureSize); + memset(raw + kStructureSize, 0, lAllocSize - kStructureSize); config->start_buffer = raw; config->end_buffer = raw + lAllocSize; @@ -329,10 +255,18 @@ void PacketBufferTest::PrepareTestBuffer(BufferConfiguration * config, int flags config->handle->tot_len = config->init_len; } -bool PacketBufferTest::ResetHandles() +bool TestSystemPacketBuffer::ResetConfigurations() +{ + // Clear the configurations' buffer handles. + for (auto & configuration : configurations) + configuration.handle = nullptr; + return true; +} + +bool TestSystemPacketBuffer::ResetHandles() { // Check against leaks or double-frees in tests: every handle obtained through - // PacketBufferTest::NewPacketBuffer should have a reference count of 1. + // TestSystemPacketBuffer::NewPacketBuffer should have a reference count of 1. bool handles_ok = true; for (size_t i = 0; i < handles.size(); ++i) { @@ -356,8 +290,6 @@ bool PacketBufferTest::ResetHandles() return handles_ok; } -// Test functions invoked from the suite. - /** * Test PacketBufferHandle::New() function. * @@ -367,24 +299,20 @@ bool PacketBufferTest::ResetHandles() * the method returns nullptr. Otherwise, check for correctness of initializing * the new buffer's internal state. */ -void PacketBufferTest::CheckNew(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckNew) { - TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (const auto & config : test->configurations) + for (const auto & config : configurations) { const PacketBufferHandle buffer = PacketBufferHandle::New(0, config.reserved_size); if (config.reserved_size > PacketBuffer::kMaxSizeWithoutReserve) { - NL_TEST_ASSERT(inSuite, buffer.IsNull()); + EXPECT_TRUE(buffer.IsNull()); continue; } - NL_TEST_ASSERT(inSuite, config.reserved_size <= buffer->AllocSize()); - NL_TEST_ASSERT(inSuite, !buffer.IsNull()); + EXPECT_LE(config.reserved_size, buffer->AllocSize()); + ASSERT_FALSE(buffer.IsNull()); if (!buffer.IsNull()) { @@ -393,10 +321,10 @@ void PacketBufferTest::CheckNew(nlTestSuite * inSuite, void * inContext) const pbuf * const pb = TO_LWIP_PBUF(buffer.Get()); // NOLINTEND(bugprone-casting-through-void) - NL_TEST_ASSERT(inSuite, pb->len == 0); - NL_TEST_ASSERT(inSuite, pb->tot_len == 0); - NL_TEST_ASSERT(inSuite, pb->next == nullptr); - NL_TEST_ASSERT(inSuite, pb->ref == 1); + EXPECT_EQ(pb->len, 0); + EXPECT_EQ(pb->tot_len, 0); + EXPECT_EQ(pb->next, nullptr); + EXPECT_EQ(pb->ref, 1); } } @@ -419,16 +347,13 @@ void PacketBufferTest::CheckNew(nlTestSuite * inSuite, void * inContext) /** * Test PacketBuffer::Start() function. */ -void PacketBufferTest::CheckStart(nlTestSuite * inSuite, void * inContext) +TEST_F(TestSystemPacketBuffer, CheckStart) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - for (auto & config : test->configurations) + for (auto & config : configurations) { - test->PrepareTestBuffer(&config, kRecordHandle); - NL_TEST_ASSERT(inSuite, config.handle->Start() == config.payload_ptr); + PrepareTestBuffer(&config, kRecordHandle); + EXPECT_EQ(config.handle->Start(), config.payload_ptr); } } @@ -443,15 +368,11 @@ void PacketBufferTest::CheckStart(nlTestSuite * inSuite, void * inContext) * adjusted according to the offset value passed into the * SetStart() method. */ -void PacketBufferTest::CheckSetStart(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckSetStart) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - static constexpr ptrdiff_t sSizePacketBuffer = kBlockSize; - for (auto & config : test->configurations) + for (auto & config : configurations) { // clang-format off static constexpr ptrdiff_t start_offset[] = @@ -468,16 +389,16 @@ void PacketBufferTest::CheckSetStart(nlTestSuite * inSuite, void * inContext) for (ptrdiff_t offset : start_offset) { - test->PrepareTestBuffer(&config, kRecordHandle | kAllowHandleReuse); + PrepareTestBuffer(&config, kRecordHandle | kAllowHandleReuse); uint8_t * const test_start = config.payload_ptr + offset; uint8_t * verify_start = test_start; config.handle->SetStart(test_start); - if (verify_start < config.start_buffer + PacketBuffer::kStructureSize) + if (verify_start < config.start_buffer + kStructureSize) { // Set start before valid payload beginning. - verify_start = config.start_buffer + PacketBuffer::kStructureSize; + verify_start = config.start_buffer + kStructureSize; } if (verify_start > config.end_buffer) @@ -486,18 +407,18 @@ void PacketBufferTest::CheckSetStart(nlTestSuite * inSuite, void * inContext) verify_start = config.end_buffer; } - NL_TEST_ASSERT(inSuite, config.handle->payload == verify_start); + EXPECT_EQ(config.handle->payload, verify_start); if ((verify_start - config.payload_ptr) > config.init_len) { // Set start to the beginning of payload, right after handle's header. - NL_TEST_ASSERT(inSuite, config.handle->len == 0); + EXPECT_EQ(config.handle->len, 0); } else { // Set start to somewhere between the end of the handle's // header and the end of payload. - NL_TEST_ASSERT(inSuite, config.handle->len == (config.init_len - (verify_start - config.payload_ptr))); + EXPECT_EQ(config.handle->len, (config.init_len - (verify_start - config.payload_ptr))); } } } @@ -506,17 +427,12 @@ void PacketBufferTest::CheckSetStart(nlTestSuite * inSuite, void * inContext) /** * Test PacketBuffer::DataLength() function. */ -void PacketBufferTest::CheckDataLength(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckDataLength) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config : test->configurations) + for (auto & config : configurations) { - test->PrepareTestBuffer(&config, kRecordHandle); - - NL_TEST_ASSERT(inSuite, config.handle->DataLength() == config.handle->len); + PrepareTestBuffer(&config, kRecordHandle); + EXPECT_EQ(config.handle->DataLength(), config.handle->len); } } @@ -533,21 +449,16 @@ void PacketBufferTest::CheckDataLength(nlTestSuite * inSuite, void * inContext) * other one being passed as the head of the chain. After calling * the method verify that data lengths were correctly adjusted. */ -void PacketBufferTest::CheckSetDataLength(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckSetDataLength) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { - for (size_t i = 0; i < theContext->length_count; ++i) + for (auto length : kLengths) { - const uint16_t length = theContext->lengths[i]; - test->PrepareTestBuffer(&config_1, kRecordHandle | kAllowHandleReuse); - test->PrepareTestBuffer(&config_2, kRecordHandle | kAllowHandleReuse); + PrepareTestBuffer(&config_1, kRecordHandle | kAllowHandleReuse); + PrepareTestBuffer(&config_2, kRecordHandle | kAllowHandleReuse); if (&config_1 == &config_2) { @@ -556,15 +467,15 @@ void PacketBufferTest::CheckSetDataLength(nlTestSuite * inSuite, void * inContex if (length > (config_2.end_buffer - config_2.payload_ptr)) { - NL_TEST_ASSERT(inSuite, config_2.handle->len == (config_2.end_buffer - config_2.payload_ptr)); - NL_TEST_ASSERT(inSuite, config_2.handle->tot_len == (config_2.end_buffer - config_2.payload_ptr)); - NL_TEST_ASSERT(inSuite, config_2.handle->next == nullptr); + EXPECT_EQ(config_2.handle->len, (config_2.end_buffer - config_2.payload_ptr)); + EXPECT_EQ(config_2.handle->tot_len, (config_2.end_buffer - config_2.payload_ptr)); + EXPECT_EQ(config_2.handle->next, nullptr); } else { - NL_TEST_ASSERT(inSuite, config_2.handle->len == length); - NL_TEST_ASSERT(inSuite, config_2.handle->tot_len == length); - NL_TEST_ASSERT(inSuite, config_2.handle->next == nullptr); + EXPECT_EQ(config_2.handle->len, length); + EXPECT_EQ(config_2.handle->tot_len, length); + EXPECT_EQ(config_2.handle->next, nullptr); } } else @@ -574,25 +485,22 @@ void PacketBufferTest::CheckSetDataLength(nlTestSuite * inSuite, void * inContex if (length > (config_2.end_buffer - config_2.payload_ptr)) { - NL_TEST_ASSERT(inSuite, config_2.handle->len == (config_2.end_buffer - config_2.payload_ptr)); - NL_TEST_ASSERT(inSuite, config_2.handle->tot_len == (config_2.end_buffer - config_2.payload_ptr)); - NL_TEST_ASSERT(inSuite, config_2.handle->next == nullptr); - - NL_TEST_ASSERT(inSuite, - config_1.handle->tot_len == - (config_1.init_len + static_cast(config_2.end_buffer - config_2.payload_ptr) - - static_cast(config_2.init_len))); + EXPECT_EQ(config_2.handle->len, (config_2.end_buffer - config_2.payload_ptr)); + EXPECT_EQ(config_2.handle->tot_len, (config_2.end_buffer - config_2.payload_ptr)); + EXPECT_EQ(config_2.handle->next, nullptr); + + EXPECT_EQ(config_1.handle->tot_len, + (config_1.init_len + static_cast(config_2.end_buffer - config_2.payload_ptr) - + static_cast(config_2.init_len))); } else { - NL_TEST_ASSERT(inSuite, config_2.handle->len == length); - NL_TEST_ASSERT(inSuite, config_2.handle->tot_len == length); - NL_TEST_ASSERT(inSuite, config_2.handle->next == nullptr); - - NL_TEST_ASSERT( - inSuite, - config_1.handle->tot_len == - (config_1.init_len + static_cast(length) - static_cast(config_2.init_len))); + EXPECT_EQ(config_2.handle->len, length); + EXPECT_EQ(config_2.handle->tot_len, length); + EXPECT_EQ(config_2.handle->next, nullptr); + + EXPECT_EQ(config_1.handle->tot_len, + (config_1.init_len + static_cast(length) - static_cast(config_2.init_len))); } } } @@ -603,75 +511,56 @@ void PacketBufferTest::CheckSetDataLength(nlTestSuite * inSuite, void * inContex /** * Test PacketBuffer::TotalLength() function. */ -void PacketBufferTest::CheckTotalLength(nlTestSuite * inSuite, void * inContext) +TEST_F(TestSystemPacketBuffer, CheckTotalLength) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config : test->configurations) + for (auto & config : configurations) { - test->PrepareTestBuffer(&config, kRecordHandle); - NL_TEST_ASSERT(inSuite, config.handle->TotalLength() == config.init_len); + PrepareTestBuffer(&config, kRecordHandle); + EXPECT_EQ(config.handle->TotalLength(), config.init_len); } } /** * Test PacketBuffer::MaxDataLength() function. */ -void PacketBufferTest::CheckMaxDataLength(nlTestSuite * inSuite, void * inContext) +TEST_F(TestSystemPacketBuffer, CheckMaxDataLength) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config : test->configurations) + for (auto & config : configurations) { - test->PrepareTestBuffer(&config, kRecordHandle); - - NL_TEST_ASSERT(inSuite, config.handle->MaxDataLength() == (config.end_buffer - config.payload_ptr)); + PrepareTestBuffer(&config, kRecordHandle); + EXPECT_EQ(config.handle->MaxDataLength(), (config.end_buffer - config.payload_ptr)); } } /** * Test PacketBuffer::AvailableDataLength() function. */ -void PacketBufferTest::CheckAvailableDataLength(nlTestSuite * inSuite, void * inContext) +TEST_F(TestSystemPacketBuffer, CheckAvailableDataLength) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config : test->configurations) + for (auto & config : configurations) { - test->PrepareTestBuffer(&config, kRecordHandle); - - NL_TEST_ASSERT(inSuite, - config.handle->AvailableDataLength() == ((config.end_buffer - config.payload_ptr) - config.init_len)); + PrepareTestBuffer(&config, kRecordHandle); + EXPECT_EQ(config.handle->AvailableDataLength(), ((config.end_buffer - config.payload_ptr) - config.init_len)); } } /** * Test PacketBuffer::ReservedSize() function. */ -void PacketBufferTest::CheckReservedSize(nlTestSuite * inSuite, void * inContext) +TEST_F(TestSystemPacketBuffer, CheckReservedSize) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config : test->configurations) + for (auto & config : configurations) { - test->PrepareTestBuffer(&config, kRecordHandle); + PrepareTestBuffer(&config, kRecordHandle); const size_t kAllocSize = config.handle->AllocSize(); if (config.reserved_size > kAllocSize) { - NL_TEST_ASSERT(inSuite, config.handle->ReservedSize() == kAllocSize); + EXPECT_EQ(config.handle->ReservedSize(), kAllocSize); } else { - NL_TEST_ASSERT(inSuite, config.handle->ReservedSize() == config.reserved_size); + EXPECT_EQ(config.handle->ReservedSize(), config.reserved_size); } } } @@ -679,30 +568,26 @@ void PacketBufferTest::CheckReservedSize(nlTestSuite * inSuite, void * inContext /** * Test PacketBuffer::HasChainedBuffer() function. */ -void PacketBufferTest::CheckHasChainedBuffer(nlTestSuite * inSuite, void * inContext) +TEST_F(TestSystemPacketBuffer, CheckHasChainedBuffer) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { if (&config_1 == &config_2) { continue; } - test->PrepareTestBuffer(&config_1); - test->PrepareTestBuffer(&config_2); + PrepareTestBuffer(&config_1); + PrepareTestBuffer(&config_2); - NL_TEST_ASSERT(inSuite, config_1.handle->HasChainedBuffer() == false); - NL_TEST_ASSERT(inSuite, config_2.handle->HasChainedBuffer() == false); + EXPECT_FALSE(config_1.handle->HasChainedBuffer()); + EXPECT_FALSE(config_2.handle->HasChainedBuffer()); config_1.handle->AddToEnd(config_2.handle.Retain()); - NL_TEST_ASSERT(inSuite, config_1.handle->HasChainedBuffer() == true); - NL_TEST_ASSERT(inSuite, config_2.handle->HasChainedBuffer() == false); + EXPECT_TRUE(config_1.handle->HasChainedBuffer()); + EXPECT_FALSE(config_2.handle->HasChainedBuffer()); config_1.handle = nullptr; config_2.handle = nullptr; @@ -721,49 +606,45 @@ void PacketBufferTest::CheckHasChainedBuffer(nlTestSuite * inSuite, void * inCon * This test function tests linking any combination of three * buffer-configurations passed within inContext. */ -void PacketBufferTest::CheckAddToEnd(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckAddToEnd) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { - for (auto & config_3 : test->configurations) + for (auto & config_3 : configurations) { if (&config_1 == &config_2 || &config_1 == &config_3 || &config_2 == &config_3) { continue; } - test->PrepareTestBuffer(&config_1); - test->PrepareTestBuffer(&config_2); - test->PrepareTestBuffer(&config_3); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 1); - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 1); - NL_TEST_ASSERT(inSuite, config_3.handle->ref == 1); + PrepareTestBuffer(&config_1); + PrepareTestBuffer(&config_2); + PrepareTestBuffer(&config_3); + EXPECT_EQ(config_1.handle->ref, 1); + EXPECT_EQ(config_2.handle->ref, 1); + EXPECT_EQ(config_3.handle->ref, 1); config_1.handle->AddToEnd(config_2.handle.Retain()); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 1); // config_1.handle - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 2); // config_2.handle and config_1.handle->next - NL_TEST_ASSERT(inSuite, config_3.handle->ref == 1); // config_3.handle + EXPECT_EQ(config_1.handle->ref, 1); // config_1.handle + EXPECT_EQ(config_2.handle->ref, 2); // config_2.handle and config_1.handle->next + EXPECT_EQ(config_3.handle->ref, 1); // config_3.handle - NL_TEST_ASSERT(inSuite, config_1.handle->tot_len == (config_1.init_len + config_2.init_len)); - NL_TEST_ASSERT(inSuite, config_1.handle->next == config_2.handle.Get()); - NL_TEST_ASSERT(inSuite, config_2.handle->next == nullptr); - NL_TEST_ASSERT(inSuite, config_3.handle->next == nullptr); + EXPECT_EQ(config_1.handle->tot_len, (config_1.init_len + config_2.init_len)); + EXPECT_EQ(config_1.handle->next, config_2.handle.Get()); + EXPECT_EQ(config_2.handle->next, nullptr); + EXPECT_EQ(config_3.handle->next, nullptr); config_1.handle->AddToEnd(config_3.handle.Retain()); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 1); // config_1.handle - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 2); // config_2.handle and config_1.handle->next - NL_TEST_ASSERT(inSuite, config_3.handle->ref == 2); // config_3.handle and config_2.handle->next + EXPECT_EQ(config_1.handle->ref, 1); // config_1.handle + EXPECT_EQ(config_2.handle->ref, 2); // config_2.handle and config_1.handle->next + EXPECT_EQ(config_3.handle->ref, 2); // config_3.handle and config_2.handle->next - NL_TEST_ASSERT(inSuite, config_1.handle->tot_len == (config_1.init_len + config_2.init_len + config_3.init_len)); - NL_TEST_ASSERT(inSuite, config_1.handle->next == config_2.handle.Get()); - NL_TEST_ASSERT(inSuite, config_2.handle->next == config_3.handle.Get()); - NL_TEST_ASSERT(inSuite, config_3.handle->next == nullptr); + EXPECT_EQ(config_1.handle->tot_len, (config_1.init_len + config_2.init_len + config_3.init_len)); + EXPECT_EQ(config_1.handle->next, config_2.handle.Get()); + EXPECT_EQ(config_2.handle->next, config_3.handle.Get()); + EXPECT_EQ(config_3.handle->next, nullptr); config_1.handle = nullptr; config_2.handle = nullptr; @@ -783,50 +664,47 @@ void PacketBufferTest::CheckAddToEnd(nlTestSuite * inSuite, void * inContext) * on the first buffer to unlink the second buffer. After the call, * verify correct internal state of the first buffer. */ -void PacketBufferTest::CheckPopHead(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckPopHead) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - // Single buffer test. - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - test->PrepareTestBuffer(&config_1, kRecordHandle | kAllowHandleReuse); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 2); + PrepareTestBuffer(&config_1, kRecordHandle | kAllowHandleReuse); + EXPECT_EQ(config_1.handle->ref, 2); const PacketBuffer * const buffer_1 = config_1.handle.mBuffer; const PacketBufferHandle popped = config_1.handle.PopHead(); - NL_TEST_ASSERT(inSuite, config_1.handle.IsNull()); - NL_TEST_ASSERT(inSuite, popped.mBuffer == buffer_1); - NL_TEST_ASSERT(inSuite, popped->next == nullptr); - NL_TEST_ASSERT(inSuite, popped->tot_len == config_1.init_len); - NL_TEST_ASSERT(inSuite, popped->ref == 2); + EXPECT_TRUE(config_1.handle.IsNull()); + EXPECT_EQ(popped.mBuffer, buffer_1); + EXPECT_EQ(popped->next, nullptr); + EXPECT_EQ(popped->tot_len, config_1.init_len); + EXPECT_EQ(popped->ref, 2); } - test->ResetHandles(); + + ResetHandles(); // Chained buffers test. - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { if (&config_1 == &config_2) { continue; } - test->PrepareTestBuffer(&config_1, kRecordHandle | kAllowHandleReuse); - test->PrepareTestBuffer(&config_2, kRecordHandle | kAllowHandleReuse); + PrepareTestBuffer(&config_1, kRecordHandle | kAllowHandleReuse); + PrepareTestBuffer(&config_2, kRecordHandle | kAllowHandleReuse); config_1.handle->AddToEnd(config_2.handle.Retain()); const PacketBufferHandle popped = config_1.handle.PopHead(); - NL_TEST_ASSERT(inSuite, config_1.handle == config_2.handle); - NL_TEST_ASSERT(inSuite, config_1.handle->next == nullptr); - NL_TEST_ASSERT(inSuite, config_1.handle->tot_len == config_1.init_len); + EXPECT_EQ(config_1.handle, config_2.handle); + EXPECT_EQ(config_1.handle->next, nullptr); + EXPECT_EQ(config_1.handle->tot_len, config_1.init_len); } } } @@ -842,37 +720,32 @@ void PacketBufferTest::CheckPopHead(nlTestSuite * inSuite, void * inContext) * the chain. After calling the method, verify correctly adjusted * state of the first buffer. */ -void PacketBufferTest::CheckCompactHead(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckCompactHead) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - // Single buffer test. - for (auto & config : test->configurations) + for (auto & config : configurations) { - for (size_t i = 0; i < theContext->length_count; ++i) + for (auto length : kLengths) { - const uint16_t length = theContext->lengths[i]; - - test->PrepareTestBuffer(&config, kRecordHandle | kAllowHandleReuse); + PrepareTestBuffer(&config, kRecordHandle | kAllowHandleReuse); config.handle->SetDataLength(length, config.handle); const uint16_t data_length = config.handle->DataLength(); config.handle->CompactHead(); - NL_TEST_ASSERT(inSuite, config.handle->payload == (config.start_buffer + PacketBuffer::kStructureSize)); - NL_TEST_ASSERT(inSuite, config.handle->tot_len == data_length); + EXPECT_EQ(config.handle->payload, (config.start_buffer + kStructureSize)); + EXPECT_EQ(config.handle->tot_len, data_length); } config.handle = nullptr; } - NL_TEST_ASSERT(inSuite, test->ResetHandles()); + + EXPECT_TRUE(ResetHandles()); // Chained buffers test. - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { if (&config_1 == &config_2) { @@ -880,24 +753,20 @@ void PacketBufferTest::CheckCompactHead(nlTestSuite * inSuite, void * inContext) } // start with various initial length for the first buffer - for (size_t i = 0; i < theContext->length_count; ++i) + for (auto length_1 : kLengths) { - const uint16_t length_1 = theContext->lengths[i]; - // start with various initial length for the second buffer - for (size_t j = 0; j < theContext->length_count; ++j) + for (auto length_2 : kLengths) { - const uint16_t length_2 = theContext->lengths[j]; - - test->PrepareTestBuffer(&config_1, kRecordHandle | kAllowHandleReuse); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 2); + PrepareTestBuffer(&config_1, kRecordHandle | kAllowHandleReuse); + EXPECT_EQ(config_1.handle->ref, 2); // CompactHead requires that there be no other references to the chained buffer, // so we manage it manually. - test->PrepareTestBuffer(&config_2); - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 1); + PrepareTestBuffer(&config_2); + EXPECT_EQ(config_2.handle->ref, 1); PacketBuffer * buffer_2 = std::move(config_2.handle).UnsafeRelease(); - NL_TEST_ASSERT(inSuite, config_2.handle.IsNull()); + EXPECT_TRUE(config_2.handle.IsNull()); config_1.handle->SetDataLength(length_1, config_1.handle); const uint16_t data_length_1 = config_1.handle->DataLength(); @@ -911,38 +780,38 @@ void PacketBufferTest::CheckCompactHead(nlTestSuite * inSuite, void * inContext) config_1.handle->CompactHead(); - NL_TEST_ASSERT(inSuite, config_1.handle->payload == (config_1.start_buffer + PacketBuffer::kStructureSize)); + EXPECT_EQ(config_1.handle->payload, (config_1.start_buffer + kStructureSize)); if (config_1.handle->tot_len > config_1.handle->MaxDataLength()) { - NL_TEST_ASSERT(inSuite, config_1.handle->len == config_1.handle->MaxDataLength()); - NL_TEST_ASSERT(inSuite, buffer_2->len == config_1.handle->tot_len - config_1.handle->MaxDataLength()); - NL_TEST_ASSERT(inSuite, config_1.handle->next == buffer_2); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 2); - NL_TEST_ASSERT(inSuite, buffer_2->ref == 1); + EXPECT_EQ(config_1.handle->len, config_1.handle->MaxDataLength()); + EXPECT_EQ(buffer_2->len, config_1.handle->tot_len - config_1.handle->MaxDataLength()); + EXPECT_EQ(config_1.handle->next, buffer_2); + EXPECT_EQ(config_1.handle->ref, 2); + EXPECT_EQ(buffer_2->ref, 1); } else { - NL_TEST_ASSERT(inSuite, config_1.handle->len == config_1.handle->tot_len); + EXPECT_EQ(config_1.handle->len, config_1.handle->tot_len); if (data_length_1 >= config_1.handle->MaxDataLength() && data_length_2 == 0) { /* make sure the second buffer is not freed */ - NL_TEST_ASSERT(inSuite, config_1.handle->next == buffer_2); - NL_TEST_ASSERT(inSuite, buffer_2->ref == 1); + EXPECT_EQ(config_1.handle->next, buffer_2); + EXPECT_EQ(buffer_2->ref, 1); } else { /* make sure the second buffer is freed */ - NL_TEST_ASSERT(inSuite, config_1.handle->next == nullptr); + EXPECT_EQ(config_1.handle->next, nullptr); buffer_2 = nullptr; } } - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 2); + EXPECT_EQ(config_1.handle->ref, 2); config_1.handle = nullptr; // Verify and release handles. - NL_TEST_ASSERT(inSuite, test->ResetHandles()); + EXPECT_TRUE(ResetHandles()); } } } @@ -959,32 +828,27 @@ void PacketBufferTest::CheckCompactHead(nlTestSuite * inSuite, void * inContext) * the internal state of the buffer has been correctly * adjusted according to the value passed into the method. */ -void PacketBufferTest::CheckConsumeHead(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckConsumeHead) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config : test->configurations) + for (auto & config : configurations) { - for (size_t i = 0; i < theContext->length_count; ++i) + for (auto length : kLengths) { - const uint16_t length = theContext->lengths[i]; - test->PrepareTestBuffer(&config, kRecordHandle | kAllowHandleReuse); + PrepareTestBuffer(&config, kRecordHandle | kAllowHandleReuse); config.handle->ConsumeHead(length); if (length > config.init_len) { - NL_TEST_ASSERT(inSuite, config.handle->payload == (config.payload_ptr + config.init_len)); - NL_TEST_ASSERT(inSuite, config.handle->len == 0); - NL_TEST_ASSERT(inSuite, config.handle->tot_len == 0); + EXPECT_EQ(config.handle->payload, (config.payload_ptr + config.init_len)); + EXPECT_EQ(config.handle->len, 0); + EXPECT_EQ(config.handle->tot_len, 0); } else { - NL_TEST_ASSERT(inSuite, config.handle->payload == (config.payload_ptr + length)); - NL_TEST_ASSERT(inSuite, config.handle->len == (config.handle->len - length)); - NL_TEST_ASSERT(inSuite, config.handle->tot_len == (config.handle->tot_len - length)); + EXPECT_EQ(config.handle->payload, (config.payload_ptr + length)); + EXPECT_EQ(config.handle->len, (config.handle->len - length)); + EXPECT_EQ(config.handle->tot_len, (config.handle->tot_len - length)); } } } @@ -1002,15 +866,11 @@ void PacketBufferTest::CheckConsumeHead(nlTestSuite * inSuite, void * inContext) * method, verify correctly adjusted the state of the first * buffer and appropriate return pointer from the method's call. */ -void PacketBufferTest::CheckConsume(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckConsume) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { if (&config_1 == &config_2) { @@ -1018,22 +878,18 @@ void PacketBufferTest::CheckConsume(nlTestSuite * inSuite, void * inContext) } // consume various amounts of memory - for (size_t i = 0; i < theContext->length_count; ++i) + for (auto consumeLength : kLengths) { - const uint16_t consumeLength = theContext->lengths[i]; // start with various initial length for the first buffer - for (size_t j = 0; j < theContext->length_count; ++j) + for (auto len_1 : kLengths) { - const uint16_t len_1 = theContext->lengths[j]; // start with various initial length for the second buffer - for (size_t k = 0; k < theContext->length_count; ++k) + for (auto len_2 : kLengths) { - const uint16_t len_2 = theContext->lengths[k]; - - test->PrepareTestBuffer(&config_1); - test->PrepareTestBuffer(&config_2); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 1); - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 1); + PrepareTestBuffer(&config_1); + PrepareTestBuffer(&config_2); + EXPECT_EQ(config_1.handle->ref, 1); + EXPECT_EQ(config_2.handle->ref, 1); config_1.handle->AddToEnd(config_2.handle.Retain()); @@ -1045,40 +901,40 @@ void PacketBufferTest::CheckConsume(nlTestSuite * inSuite, void * inContext) const uint16_t buf_2_len = config_2.handle->len; PacketBufferHandle original_handle_1 = config_1.handle.Retain(); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 2); // config_1.handle and original_handle_1 - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 2); // config_2.handle and config_1.handle->next + EXPECT_EQ(config_1.handle->ref, 2); // config_1.handle and original_handle_1 + EXPECT_EQ(config_2.handle->ref, 2); // config_2.handle and config_1.handle->next config_1.handle.Consume(consumeLength); if (consumeLength == 0) { - NL_TEST_ASSERT(inSuite, config_1.handle == original_handle_1); - NL_TEST_ASSERT(inSuite, config_1.handle->len == buf_1_len); - NL_TEST_ASSERT(inSuite, config_2.handle->len == buf_2_len); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 2); // config_1.handle and original_handle_1 - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 2); // config_2.handle and config_1.handle->next + EXPECT_EQ(config_1.handle, original_handle_1); + EXPECT_EQ(config_1.handle->len, buf_1_len); + EXPECT_EQ(config_2.handle->len, buf_2_len); + EXPECT_EQ(config_1.handle->ref, 2); // config_1.handle and original_handle_1 + EXPECT_EQ(config_2.handle->ref, 2); // config_2.handle and config_1.handle->next } else if (consumeLength < buf_1_len) { - NL_TEST_ASSERT(inSuite, config_1.handle == original_handle_1); - NL_TEST_ASSERT(inSuite, config_1.handle->len == buf_1_len - consumeLength); - NL_TEST_ASSERT(inSuite, config_2.handle->len == buf_2_len); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 2); // config_1.handle and original_handle_1 - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 2); // config_2.handle and config_1.handle->next + EXPECT_EQ(config_1.handle, original_handle_1); + EXPECT_EQ(config_1.handle->len, buf_1_len - consumeLength); + EXPECT_EQ(config_2.handle->len, buf_2_len); + EXPECT_EQ(config_1.handle->ref, 2); // config_1.handle and original_handle_1 + EXPECT_EQ(config_2.handle->ref, 2); // config_2.handle and config_1.handle->next } else if ((consumeLength < buf_1_len + buf_2_len || (consumeLength == buf_1_len + buf_2_len && buf_2_len == 0))) { - NL_TEST_ASSERT(inSuite, config_1.handle == config_2.handle); - NL_TEST_ASSERT(inSuite, config_2.handle->len == buf_1_len + buf_2_len - consumeLength); - NL_TEST_ASSERT(inSuite, original_handle_1->ref == 1); // original_handle_1 - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 2); // config_1.handle and config_2.handle + EXPECT_EQ(config_1.handle, config_2.handle); + EXPECT_EQ(config_2.handle->len, buf_1_len + buf_2_len - consumeLength); + EXPECT_EQ(original_handle_1->ref, 1); // original_handle_1 + EXPECT_EQ(config_2.handle->ref, 2); // config_1.handle and config_2.handle } else { - NL_TEST_ASSERT(inSuite, config_1.handle.IsNull()); - NL_TEST_ASSERT(inSuite, original_handle_1->ref == 1); // original_handle_1 - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 1); // config_2.handle + EXPECT_TRUE(config_1.handle.IsNull()); + EXPECT_EQ(original_handle_1->ref, 1); // original_handle_1 + EXPECT_EQ(config_2.handle->ref, 1); // config_2.handle } original_handle_1 = nullptr; @@ -1100,41 +956,35 @@ void PacketBufferTest::CheckConsume(nlTestSuite * inSuite, void * inContext) * Then, verify that EnsureReservedSize() method correctly * retrieves the amount of the reserved space. */ -void PacketBufferTest::CheckEnsureReservedSize(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckEnsureReservedSize) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config : test->configurations) + for (auto & config : configurations) { - for (size_t i = 0; i < theContext->length_count; ++i) + for (auto length : kLengths) { - const uint16_t length = theContext->lengths[i]; - - test->PrepareTestBuffer(&config, kRecordHandle | kAllowHandleReuse); + PrepareTestBuffer(&config, kRecordHandle | kAllowHandleReuse); const uint16_t kAllocSize = config.handle->AllocSize(); uint16_t reserved_size = config.reserved_size; - if (PacketBuffer::kStructureSize + config.reserved_size > kAllocSize) + if (kStructureSize + config.reserved_size > kAllocSize) { - reserved_size = static_cast(kAllocSize - PacketBuffer::kStructureSize); + reserved_size = static_cast(kAllocSize - kStructureSize); } if (length <= reserved_size) { - NL_TEST_ASSERT(inSuite, config.handle->EnsureReservedSize(length) == true); + EXPECT_EQ(config.handle->EnsureReservedSize(length), true); continue; } - if ((length + config.init_len) > (kAllocSize - PacketBuffer::kStructureSize)) + if ((length + config.init_len) > (kAllocSize - kStructureSize)) { - NL_TEST_ASSERT(inSuite, config.handle->EnsureReservedSize(length) == false); + EXPECT_FALSE(config.handle->EnsureReservedSize(length)); continue; } - NL_TEST_ASSERT(inSuite, config.handle->EnsureReservedSize(length) == true); - NL_TEST_ASSERT(inSuite, config.handle->payload == (config.payload_ptr + length - reserved_size)); + EXPECT_EQ(config.handle->EnsureReservedSize(length), true); + EXPECT_EQ(config.handle->payload, (config.payload_ptr + length - reserved_size)); } } } @@ -1148,22 +998,18 @@ void PacketBufferTest::CheckEnsureReservedSize(nlTestSuite * inSuite, void * inC * required payload shift. Then, verify that AlignPayload() * method correctly aligns the payload start pointer. */ -void PacketBufferTest::CheckAlignPayload(nlTestSuite * inSuite, void * inContext) +TEST_F(TestSystemPacketBuffer, CheckAlignPayload) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config : test->configurations) + for (auto & config : configurations) { - for (size_t n = 0; n < theContext->length_count; ++n) + for (auto length : kLengths) { - test->PrepareTestBuffer(&config, kRecordHandle | kAllowHandleReuse); + PrepareTestBuffer(&config, kRecordHandle | kAllowHandleReuse); const uint16_t kAllocSize = config.handle->AllocSize(); - if (theContext->lengths[n] == 0) + if (length == 0) { - NL_TEST_ASSERT(inSuite, config.handle->AlignPayload(theContext->lengths[n]) == false); + EXPECT_FALSE(config.handle->AlignPayload(length)); continue; } @@ -1173,20 +1019,19 @@ void PacketBufferTest::CheckAlignPayload(nlTestSuite * inSuite, void * inContext reserved_size = kAllocSize; } - const uint16_t payload_offset = - static_cast(reinterpret_cast(config.handle->Start()) % theContext->lengths[n]); - uint16_t payload_shift = 0; + const uint16_t payload_offset = static_cast(reinterpret_cast(config.handle->Start()) % length); + uint16_t payload_shift = 0; if (payload_offset > 0) - payload_shift = static_cast(theContext->lengths[n] - payload_offset); + payload_shift = static_cast(length - payload_offset); if (payload_shift <= kAllocSize - reserved_size) { - NL_TEST_ASSERT(inSuite, config.handle->AlignPayload(theContext->lengths[n]) == true); - NL_TEST_ASSERT(inSuite, ((unsigned long) config.handle->Start() % theContext->lengths[n]) == 0); + EXPECT_EQ(config.handle->AlignPayload(length), true); + EXPECT_EQ(((unsigned long) config.handle->Start() % length), 0UL); } else { - NL_TEST_ASSERT(inSuite, config.handle->AlignPayload(theContext->lengths[n]) == false); + EXPECT_FALSE(config.handle->AlignPayload(length)); } } } @@ -1195,34 +1040,30 @@ void PacketBufferTest::CheckAlignPayload(nlTestSuite * inSuite, void * inContext /** * Test PacketBuffer::Next() function. */ -void PacketBufferTest::CheckNext(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckNext) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { - test->PrepareTestBuffer(&config_1, kRecordHandle | kAllowHandleReuse); - test->PrepareTestBuffer(&config_2, kRecordHandle | kAllowHandleReuse); + PrepareTestBuffer(&config_1, kRecordHandle | kAllowHandleReuse); + PrepareTestBuffer(&config_2, kRecordHandle | kAllowHandleReuse); if (&config_1 != &config_2) { - NL_TEST_ASSERT(inSuite, config_1.handle->Next().IsNull()); + EXPECT_TRUE(config_1.handle->Next().IsNull()); config_1.handle->AddToEnd(config_2.handle.Retain()); - NL_TEST_ASSERT(inSuite, config_1.handle->Next() == config_2.handle); - NL_TEST_ASSERT(inSuite, config_1.handle->ChainedBuffer() == config_2.handle.Get()); + EXPECT_EQ(config_1.handle->Next(), config_2.handle); + EXPECT_EQ(config_1.handle->ChainedBuffer(), config_2.handle.Get()); } else { - NL_TEST_ASSERT(inSuite, !config_1.handle->HasChainedBuffer()); + EXPECT_FALSE(config_1.handle->HasChainedBuffer()); } - NL_TEST_ASSERT(inSuite, !config_2.handle->HasChainedBuffer()); + EXPECT_FALSE(config_2.handle->HasChainedBuffer()); } } } @@ -1230,42 +1071,38 @@ void PacketBufferTest::CheckNext(nlTestSuite * inSuite, void * inContext) /** * Test PacketBuffer::Last() function. */ -void PacketBufferTest::CheckLast(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckLast) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { - for (auto & config_3 : test->configurations) + for (auto & config_3 : configurations) { if (&config_1 == &config_2 || &config_1 == &config_3 || &config_2 == &config_3) { continue; } - test->PrepareTestBuffer(&config_1); - test->PrepareTestBuffer(&config_2); - test->PrepareTestBuffer(&config_3); + PrepareTestBuffer(&config_1); + PrepareTestBuffer(&config_2); + PrepareTestBuffer(&config_3); - NL_TEST_ASSERT(inSuite, config_1.handle->Last() == config_1.handle); - NL_TEST_ASSERT(inSuite, config_2.handle->Last() == config_2.handle); - NL_TEST_ASSERT(inSuite, config_3.handle->Last() == config_3.handle); + EXPECT_EQ(config_1.handle->Last(), config_1.handle); + EXPECT_EQ(config_2.handle->Last(), config_2.handle); + EXPECT_EQ(config_3.handle->Last(), config_3.handle); config_1.handle->AddToEnd(config_2.handle.Retain()); - NL_TEST_ASSERT(inSuite, config_1.handle->Last() == config_2.handle); - NL_TEST_ASSERT(inSuite, config_2.handle->Last() == config_2.handle); - NL_TEST_ASSERT(inSuite, config_3.handle->Last() == config_3.handle); + EXPECT_EQ(config_1.handle->Last(), config_2.handle); + EXPECT_EQ(config_2.handle->Last(), config_2.handle); + EXPECT_EQ(config_3.handle->Last(), config_3.handle); config_1.handle->AddToEnd(config_3.handle.Retain()); - NL_TEST_ASSERT(inSuite, config_1.handle->Last() == config_3.handle); - NL_TEST_ASSERT(inSuite, config_2.handle->Last() == config_3.handle); - NL_TEST_ASSERT(inSuite, config_3.handle->Last() == config_3.handle); + EXPECT_EQ(config_1.handle->Last(), config_3.handle); + EXPECT_EQ(config_2.handle->Last(), config_3.handle); + EXPECT_EQ(config_3.handle->Last(), config_3.handle); config_1.handle = nullptr; config_2.handle = nullptr; @@ -1278,12 +1115,8 @@ void PacketBufferTest::CheckLast(nlTestSuite * inSuite, void * inContext) /** * Test PacketBuffer::Read() function. */ -void PacketBufferTest::CheckRead(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckRead) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - uint8_t payloads[2 * kBlockSize] = { 1 }; uint8_t result[2 * kBlockSize]; for (size_t i = 1; i < sizeof(payloads); ++i) @@ -1291,47 +1124,47 @@ void PacketBufferTest::CheckRead(nlTestSuite * inSuite, void * inContext) payloads[i] = static_cast(random()); } - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { if (&config_1 == &config_2) { continue; } - test->PrepareTestBuffer(&config_1, kAllowHandleReuse); - test->PrepareTestBuffer(&config_2, kAllowHandleReuse); + PrepareTestBuffer(&config_1, kAllowHandleReuse); + PrepareTestBuffer(&config_2, kAllowHandleReuse); const uint16_t length_1 = config_1.handle->MaxDataLength(); const uint16_t length_2 = config_2.handle->MaxDataLength(); const size_t length_sum = length_1 + length_2; const uint16_t length_total = static_cast(length_sum); - NL_TEST_ASSERT(inSuite, length_total == length_sum); + EXPECT_EQ(length_total, length_sum); memcpy(config_1.handle->Start(), payloads, length_1); memcpy(config_2.handle->Start(), payloads + length_1, length_2); config_1.handle->SetDataLength(length_1); config_2.handle->SetDataLength(length_2); config_1.handle->AddToEnd(config_2.handle.Retain()); - NL_TEST_ASSERT(inSuite, config_1.handle->TotalLength() == length_total); + EXPECT_EQ(config_1.handle->TotalLength(), length_total); if (length_1 >= 1) { // Check a read that does not span packet buffers. CHIP_ERROR err = config_1.handle->Read(result, 1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, result[0] == payloads[0]); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(result[0], payloads[0]); } // Check a read that spans packet buffers. CHIP_ERROR err = config_1.handle->Read(result, length_total); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(payloads, result, length_total) == 0); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(memcmp(payloads, result, length_total), 0); // Check a read that is too long fails. err = config_1.handle->Read(result, length_total + 1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(err, CHIP_ERROR_BUFFER_TOO_SMALL); // Check that running off the end of a corrupt buffer chain is detected. if (length_total < UINT16_MAX) @@ -1339,7 +1172,7 @@ void PacketBufferTest::CheckRead(nlTestSuite * inSuite, void * inContext) // First case: TotalLength() is wrong. config_1.handle->tot_len = static_cast(config_1.handle->tot_len + 1); err = config_1.handle->Read(result, length_total + 1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INTERNAL); + EXPECT_EQ(err, CHIP_ERROR_INTERNAL); config_1.handle->tot_len = static_cast(config_1.handle->tot_len - 1); } if (length_1 >= 1) @@ -1347,7 +1180,7 @@ void PacketBufferTest::CheckRead(nlTestSuite * inSuite, void * inContext) // Second case: an individual buffer's DataLength() is wrong. config_1.handle->len = static_cast(config_1.handle->len - 1); err = config_1.handle->Read(result, length_total); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INTERNAL); + EXPECT_EQ(err, CHIP_ERROR_INTERNAL); config_1.handle->len = static_cast(config_1.handle->len + 1); } @@ -1360,18 +1193,14 @@ void PacketBufferTest::CheckRead(nlTestSuite * inSuite, void * inContext) /** * Test PacketBuffer::AddRef() function. */ -void PacketBufferTest::CheckAddRef(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckAddRef) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config : test->configurations) + for (auto & config : configurations) { - test->PrepareTestBuffer(&config, kRecordHandle); + PrepareTestBuffer(&config, kRecordHandle); const auto refs = config.handle->ref; config.handle->AddRef(); - NL_TEST_ASSERT(inSuite, config.handle->ref == refs + 1); + EXPECT_EQ(config.handle->ref, refs + 1); config.handle->ref = refs; // Don't leak buffers. } } @@ -1387,18 +1216,14 @@ void PacketBufferTest::CheckAddRef(nlTestSuite * inSuite, void * inContext) * the chain and verify correctly adjusted states of the two * buffers. */ -void PacketBufferTest::CheckFree(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckFree) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - const decltype(PacketBuffer::ref) init_ref_count[] = { 1, 2, 3 }; constexpr size_t kRefs = sizeof(init_ref_count) / sizeof(init_ref_count[0]); - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { if (&config_1 == &config_2) { @@ -1410,13 +1235,13 @@ void PacketBufferTest::CheckFree(nlTestSuite * inSuite, void * inContext) { config_1.handle = PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); config_2.handle = PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); - NL_TEST_ASSERT(inSuite, !config_1.handle.IsNull()); - NL_TEST_ASSERT(inSuite, !config_2.handle.IsNull()); + ASSERT_FALSE(config_1.handle.IsNull()); + ASSERT_FALSE(config_2.handle.IsNull()); - test->PrepareTestBuffer(&config_1, kAllowHandleReuse); - test->PrepareTestBuffer(&config_2, kAllowHandleReuse); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 1); - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 1); + PrepareTestBuffer(&config_1, kAllowHandleReuse); + PrepareTestBuffer(&config_2, kAllowHandleReuse); + EXPECT_EQ(config_1.handle->ref, 1); + EXPECT_EQ(config_2.handle->ref, 1); // Chain buffers. config_1.handle->next = config_2.handle.Get(); @@ -1436,18 +1261,18 @@ void PacketBufferTest::CheckFree(nlTestSuite * inSuite, void * inContext) if (initial_refs_1 > 1) { // Verify that head ref count is decremented. - NL_TEST_ASSERT(inSuite, config_1.handle->ref == initial_refs_1 - 1); + EXPECT_EQ(config_1.handle->ref, initial_refs_1 - 1); // Verify that chain is maintained. - NL_TEST_ASSERT(inSuite, config_1.handle->next == config_2.handle.Get()); + EXPECT_EQ(config_1.handle->next, config_2.handle.Get()); // Verify that chained buffer ref count has not changed. - NL_TEST_ASSERT(inSuite, config_2.handle->ref == initial_refs_2); + EXPECT_EQ(config_2.handle->ref, initial_refs_2); } else { if (initial_refs_2 > 1) { // Verify that chained buffer ref count is decremented. - NL_TEST_ASSERT(inSuite, config_2.handle->ref == initial_refs_2 - 1); + EXPECT_EQ(config_2.handle->ref, initial_refs_2 - 1); } else { @@ -1483,15 +1308,11 @@ void PacketBufferTest::CheckFree(nlTestSuite * inSuite, void * inContext) * FreeHead() on the first buffer in the chain and verify that * the method returned pointer to the second buffer. */ -void PacketBufferTest::CheckFreeHead(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckFreeHead) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { if (&config_1 == &config_2) { @@ -1500,47 +1321,47 @@ void PacketBufferTest::CheckFreeHead(nlTestSuite * inSuite, void * inContext) // Test PacketBuffer::FreeHead - test->PrepareTestBuffer(&config_1, kAllowHandleReuse); - test->PrepareTestBuffer(&config_2, kAllowHandleReuse); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 1); - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 1); + PrepareTestBuffer(&config_1, kAllowHandleReuse); + PrepareTestBuffer(&config_2, kAllowHandleReuse); + EXPECT_EQ(config_1.handle->ref, 1); + EXPECT_EQ(config_2.handle->ref, 1); PacketBufferHandle handle_1 = config_1.handle.Retain(); config_1.handle->AddToEnd(config_2.handle.Retain()); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 2); - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 2); // config_2.handle and config_1.handle->next + EXPECT_EQ(config_1.handle->ref, 2); + EXPECT_EQ(config_2.handle->ref, 2); // config_2.handle and config_1.handle->next PacketBuffer * const returned = PacketBuffer::FreeHead(std::move(config_1.handle).UnsafeRelease()); - NL_TEST_ASSERT(inSuite, handle_1->ref == 1); - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 2); // config_2.handle and returned - NL_TEST_ASSERT(inSuite, returned == config_2.handle.Get()); + EXPECT_EQ(handle_1->ref, 1); + EXPECT_EQ(config_2.handle->ref, 2); // config_2.handle and returned + EXPECT_EQ(returned, config_2.handle.Get()); config_1.handle = nullptr; - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 2); + EXPECT_EQ(config_2.handle->ref, 2); config_2.handle = nullptr; - NL_TEST_ASSERT(inSuite, returned->ref == 1); + EXPECT_EQ(returned->ref, 1); PacketBuffer::Free(returned); // Test PacketBufferHandle::FreeHead - test->PrepareTestBuffer(&config_1, kAllowHandleReuse); - test->PrepareTestBuffer(&config_2, kAllowHandleReuse); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 1); - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 1); + PrepareTestBuffer(&config_1, kAllowHandleReuse); + PrepareTestBuffer(&config_2, kAllowHandleReuse); + EXPECT_EQ(config_1.handle->ref, 1); + EXPECT_EQ(config_2.handle->ref, 1); handle_1 = config_1.handle.Retain(); config_1.handle->AddToEnd(config_2.handle.Retain()); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 2); - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 2); // config_2.handle and config_1.handle->next + EXPECT_EQ(config_1.handle->ref, 2); + EXPECT_EQ(config_2.handle->ref, 2); // config_2.handle and config_1.handle->next PacketBuffer * const buffer_1 = config_1.handle.Get(); config_1.handle.FreeHead(); - NL_TEST_ASSERT(inSuite, buffer_1->ref == 1); - NL_TEST_ASSERT(inSuite, config_1.handle == config_2.handle); - NL_TEST_ASSERT(inSuite, config_2.handle->ref == 2); // config_2.handle and config_1.handle + EXPECT_EQ(buffer_1->ref, 1); + EXPECT_EQ(config_1.handle, config_2.handle); + EXPECT_EQ(config_2.handle->ref, 2); // config_2.handle and config_1.handle config_1.handle = nullptr; config_2.handle = nullptr; @@ -1548,193 +1369,161 @@ void PacketBufferTest::CheckFreeHead(nlTestSuite * inSuite, void * inContext) } } -void PacketBufferTest::CheckHandleConstruct(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckHandleConstruct) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - PacketBufferHandle handle_1; - NL_TEST_ASSERT(inSuite, handle_1.IsNull()); + EXPECT_TRUE(handle_1.IsNull()); PacketBufferHandle handle_2(nullptr); - NL_TEST_ASSERT(inSuite, handle_2.IsNull()); + EXPECT_TRUE(handle_2.IsNull()); PacketBufferHandle handle_3(PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); - NL_TEST_ASSERT(inSuite, !handle_3.IsNull()); + ASSERT_FALSE(handle_3.IsNull()); // Private constructor. PacketBuffer * const buffer_3 = std::move(handle_3).UnsafeRelease(); PacketBufferHandle handle_4(buffer_3); - NL_TEST_ASSERT(inSuite, handle_4.Get() == buffer_3); + EXPECT_EQ(handle_4.Get(), buffer_3); } -void PacketBufferTest::CheckHandleMove(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckHandleMove) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { if (&config_1 == &config_2) { continue; } - test->PrepareTestBuffer(&config_1, kRecordHandle); - test->PrepareTestBuffer(&config_2, kRecordHandle); + PrepareTestBuffer(&config_1, kRecordHandle); + PrepareTestBuffer(&config_2, kRecordHandle); const PacketBuffer * const buffer_1 = config_1.handle.Get(); const PacketBuffer * const buffer_2 = config_2.handle.Get(); - NL_TEST_ASSERT(inSuite, buffer_1 != buffer_2); - NL_TEST_ASSERT(inSuite, buffer_1->ref == 2); // test.handles and config_1.handle - NL_TEST_ASSERT(inSuite, buffer_2->ref == 2); // test.handles and config_2.handle + EXPECT_NE(buffer_1, buffer_2); + EXPECT_EQ(buffer_1->ref, 2); // test.handles and config_1.handle + EXPECT_EQ(buffer_2->ref, 2); // test.handles and config_2.handle config_1.handle = std::move(config_2.handle); - NL_TEST_ASSERT(inSuite, config_1.handle.Get() == buffer_2); - NL_TEST_ASSERT(inSuite, config_2.handle.Get() == nullptr); - NL_TEST_ASSERT(inSuite, buffer_1->ref == 1); // test.handles - NL_TEST_ASSERT(inSuite, buffer_2->ref == 2); // test.handles and config_1.handle + EXPECT_EQ(config_1.handle.Get(), buffer_2); + EXPECT_EQ(config_2.handle.Get(), nullptr); + EXPECT_EQ(buffer_1->ref, 1); // test.handles + EXPECT_EQ(buffer_2->ref, 2); // test.handles and config_1.handle config_1.handle = nullptr; } // Verify and release handles. - NL_TEST_ASSERT(inSuite, test->ResetHandles()); + EXPECT_TRUE(ResetHandles()); } } -void PacketBufferTest::CheckHandleRelease(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckHandleRelease) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - test->PrepareTestBuffer(&config_1); + PrepareTestBuffer(&config_1); PacketBuffer * const buffer_1 = config_1.handle.Get(); PacketBuffer * const taken_1 = std::move(config_1.handle).UnsafeRelease(); - NL_TEST_ASSERT(inSuite, buffer_1 == taken_1); - NL_TEST_ASSERT(inSuite, config_1.handle.IsNull()); - NL_TEST_ASSERT(inSuite, buffer_1->ref == 1); + EXPECT_EQ(buffer_1, taken_1); + EXPECT_TRUE(config_1.handle.IsNull()); + EXPECT_EQ(buffer_1->ref, 1); PacketBuffer::Free(buffer_1); } } -void PacketBufferTest::CheckHandleFree(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckHandleFree) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - test->PrepareTestBuffer(&config_1, kRecordHandle); + PrepareTestBuffer(&config_1, kRecordHandle); const PacketBuffer * const buffer_1 = config_1.handle.Get(); - NL_TEST_ASSERT(inSuite, buffer_1->ref == 2); // test.handles and config_1.handle + EXPECT_EQ(buffer_1->ref, 2); // test.handles and config_1.handle config_1.handle = nullptr; - NL_TEST_ASSERT(inSuite, config_1.handle.IsNull()); - NL_TEST_ASSERT(inSuite, config_1.handle.Get() == nullptr); - NL_TEST_ASSERT(inSuite, buffer_1->ref == 1); // test.handles only + EXPECT_TRUE(config_1.handle.IsNull()); + EXPECT_EQ(config_1.handle.Get(), nullptr); + EXPECT_EQ(buffer_1->ref, 1); // test.handles only } } -void PacketBufferTest::CheckHandleRetain(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckHandleRetain) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - test->PrepareTestBuffer(&config_1, kRecordHandle); + PrepareTestBuffer(&config_1, kRecordHandle); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 2); // test.handles and config_1.handle + EXPECT_EQ(config_1.handle->ref, 2); // test.handles and config_1.handle PacketBufferHandle handle_1 = config_1.handle.Retain(); - NL_TEST_ASSERT(inSuite, config_1.handle == handle_1); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 3); // test.handles and config_1.handle and handle_1 + EXPECT_EQ(config_1.handle, handle_1); + EXPECT_EQ(config_1.handle->ref, 3); // test.handles and config_1.handle and handle_1 } } -void PacketBufferTest::CheckHandleAdopt(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckHandleAdopt) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - test->PrepareTestBuffer(&config_1, kRecordHandle); + PrepareTestBuffer(&config_1, kRecordHandle); PacketBuffer * buffer_1 = std::move(config_1.handle).UnsafeRelease(); - NL_TEST_ASSERT(inSuite, config_1.handle.IsNull()); - NL_TEST_ASSERT(inSuite, buffer_1->ref == 2); // test.handles and buffer_1 + EXPECT_TRUE(config_1.handle.IsNull()); + EXPECT_EQ(buffer_1->ref, 2); // test.handles and buffer_1 config_1.handle = PacketBufferHandle::Adopt(buffer_1); - NL_TEST_ASSERT(inSuite, config_1.handle.Get() == buffer_1); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 2); // test.handles and config_1.handle + EXPECT_EQ(config_1.handle.Get(), buffer_1); + EXPECT_EQ(config_1.handle->ref, 2); // test.handles and config_1.handle config_1.handle = nullptr; - NL_TEST_ASSERT(inSuite, config_1.handle.IsNull()); - NL_TEST_ASSERT(inSuite, buffer_1->ref == 1); // test.handles only + EXPECT_TRUE(config_1.handle.IsNull()); + EXPECT_EQ(buffer_1->ref, 1); // test.handles only } } -void PacketBufferTest::CheckHandleHold(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckHandleHold) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - test->PrepareTestBuffer(&config_1, kRecordHandle); + PrepareTestBuffer(&config_1, kRecordHandle); PacketBuffer * buffer_1 = std::move(config_1.handle).UnsafeRelease(); - NL_TEST_ASSERT(inSuite, config_1.handle.IsNull()); - NL_TEST_ASSERT(inSuite, buffer_1->ref == 2); // test.handles and buffer_1 + EXPECT_TRUE(config_1.handle.IsNull()); + EXPECT_EQ(buffer_1->ref, 2); // test.handles and buffer_1 config_1.handle = PacketBufferHandle::Hold(buffer_1); - NL_TEST_ASSERT(inSuite, config_1.handle.Get() == buffer_1); - NL_TEST_ASSERT(inSuite, config_1.handle->ref == 3); // test.handles and config_1.handle and buffer_1 + EXPECT_EQ(config_1.handle.Get(), buffer_1); + EXPECT_EQ(config_1.handle->ref, 3); // test.handles and config_1.handle and buffer_1 config_1.handle = nullptr; - NL_TEST_ASSERT(inSuite, config_1.handle.IsNull()); - NL_TEST_ASSERT(inSuite, buffer_1->ref == 2); // test.handles only and buffer_1 + EXPECT_TRUE(config_1.handle.IsNull()); + EXPECT_EQ(buffer_1->ref, 2); // test.handles only and buffer_1 PacketBuffer::Free(buffer_1); } } -void PacketBufferTest::CheckHandleAdvance(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckHandleAdvance) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { - for (auto & config_3 : test->configurations) + for (auto & config_3 : configurations) { if (&config_1 == &config_2 || &config_1 == &config_3 || &config_2 == &config_3) { continue; } - test->PrepareTestBuffer(&config_1); - test->PrepareTestBuffer(&config_2); - test->PrepareTestBuffer(&config_3); + PrepareTestBuffer(&config_1); + PrepareTestBuffer(&config_2); + PrepareTestBuffer(&config_3); PacketBufferHandle handle_1 = config_1.handle.Retain(); PacketBufferHandle handle_2 = config_2.handle.Retain(); @@ -1743,26 +1532,26 @@ void PacketBufferTest::CheckHandleAdvance(nlTestSuite * inSuite, void * inContex config_1.handle->AddToEnd(config_2.handle.Retain()); config_1.handle->AddToEnd(config_3.handle.Retain()); - NL_TEST_ASSERT(inSuite, config_1.handle->ChainedBuffer() == config_2.handle.Get()); - NL_TEST_ASSERT(inSuite, config_2.handle->ChainedBuffer() == config_3.handle.Get()); - NL_TEST_ASSERT(inSuite, config_3.handle->HasChainedBuffer() == false); - NL_TEST_ASSERT(inSuite, handle_1->ref == 2); // handle_1 and config_1.handle - NL_TEST_ASSERT(inSuite, handle_2->ref == 3); // handle_2 and config_2.handle and config_1.handle->next - NL_TEST_ASSERT(inSuite, handle_3->ref == 3); // handle_3 and config_3.handle and config_2.handle->next + EXPECT_EQ(config_1.handle->ChainedBuffer(), config_2.handle.Get()); + EXPECT_EQ(config_2.handle->ChainedBuffer(), config_3.handle.Get()); + EXPECT_FALSE(config_3.handle->HasChainedBuffer()); + EXPECT_EQ(handle_1->ref, 2); // handle_1 and config_1.handle + EXPECT_EQ(handle_2->ref, 3); // handle_2 and config_2.handle and config_1.handle->next + EXPECT_EQ(handle_3->ref, 3); // handle_3 and config_3.handle and config_2.handle->next config_1.handle.Advance(); - NL_TEST_ASSERT(inSuite, config_1.handle == handle_2); - NL_TEST_ASSERT(inSuite, handle_1->ref == 1); // handle_1 only - NL_TEST_ASSERT(inSuite, handle_2->ref == 4); // handle_2, config_[12].handle, handle_1->next - NL_TEST_ASSERT(inSuite, handle_3->ref == 3); // handle_3, config_3.handle, config_2.handle->next + EXPECT_EQ(config_1.handle, handle_2); + EXPECT_EQ(handle_1->ref, 1); // handle_1 only + EXPECT_EQ(handle_2->ref, 4); // handle_2, config_[12].handle, handle_1->next + EXPECT_EQ(handle_3->ref, 3); // handle_3, config_3.handle, config_2.handle->next config_1.handle.Advance(); - NL_TEST_ASSERT(inSuite, config_1.handle == handle_3); - NL_TEST_ASSERT(inSuite, handle_1->ref == 1); // handle_1 only - NL_TEST_ASSERT(inSuite, handle_2->ref == 3); // handle_2, config_2.handle, handle_1->next - NL_TEST_ASSERT(inSuite, handle_3->ref == 4); // handle_3, config_[13].handle, handle_2->next + EXPECT_EQ(config_1.handle, handle_3); + EXPECT_EQ(handle_1->ref, 1); // handle_1 only + EXPECT_EQ(handle_2->ref, 3); // handle_2, config_2.handle, handle_1->next + EXPECT_EQ(handle_3->ref, 4); // handle_3, config_[13].handle, handle_2->next config_1.handle = nullptr; config_2.handle = nullptr; @@ -1772,66 +1561,58 @@ void PacketBufferTest::CheckHandleAdvance(nlTestSuite * inSuite, void * inContex } } -void PacketBufferTest::CheckHandleRightSize(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckHandleRightSize) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - static const char kPayload[] = "Joy!"; PacketBufferHandle handle = PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); PacketBuffer * buffer = handle.mBuffer; memcpy(handle->Start(), kPayload, sizeof kPayload); buffer->SetDataLength(sizeof kPayload); - NL_TEST_ASSERT(inSuite, handle->ref == 1); + EXPECT_EQ(handle->ref, 1); // RightSize should do nothing if there is another reference to the buffer. { PacketBufferHandle anotherHandle = handle.Retain(); handle.RightSize(); - NL_TEST_ASSERT(inSuite, handle.mBuffer == buffer); + EXPECT_EQ(handle.mBuffer, buffer); } #if CHIP_SYSTEM_PACKETBUFFER_HAS_RIGHTSIZE handle.RightSize(); - NL_TEST_ASSERT(inSuite, handle.mBuffer != buffer); - NL_TEST_ASSERT(inSuite, handle->DataLength() == sizeof kPayload); - NL_TEST_ASSERT(inSuite, memcmp(handle->Start(), kPayload, sizeof kPayload) == 0); + EXPECT_NE(handle.mBuffer, buffer); + EXPECT_EQ(handle->DataLength(), sizeof kPayload); + EXPECT_EQ(memcmp(handle->Start(), kPayload, sizeof kPayload), 0); #else // CHIP_SYSTEM_PACKETBUFFER_HAS_RIGHTSIZE // For this configuration, RightSize() does nothing. handle.RightSize(); - NL_TEST_ASSERT(inSuite, handle.mBuffer == buffer); + EXPECT_EQ(handle.mBuffer, buffer); #endif // CHIP_SYSTEM_PACKETBUFFER_HAS_RIGHTSIZE } -void PacketBufferTest::CheckHandleCloneData(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestSystemPacketBuffer, CheckHandleCloneData) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - uint8_t lPayload[2 * PacketBuffer::kMaxSizeWithoutReserve]; for (uint8_t & payload : lPayload) { payload = static_cast(random()); } - for (auto & config_1 : test->configurations) + for (auto & config_1 : configurations) { - for (auto & config_2 : test->configurations) + for (auto & config_2 : configurations) { if (&config_1 == &config_2) { continue; } - test->PrepareTestBuffer(&config_1); - test->PrepareTestBuffer(&config_2); + PrepareTestBuffer(&config_1); + PrepareTestBuffer(&config_2); const uint8_t * payload_1 = lPayload; memcpy(config_1.handle->Start(), payload_1, config_1.handle->MaxDataLength()); @@ -1843,40 +1624,40 @@ void PacketBufferTest::CheckHandleCloneData(nlTestSuite * inSuite, void * inCont // Clone single buffer. PacketBufferHandle clone_1 = config_1.handle.CloneData(); - NL_TEST_ASSERT(inSuite, !clone_1.IsNull()); - NL_TEST_ASSERT(inSuite, clone_1->DataLength() == config_1.handle->DataLength()); - NL_TEST_ASSERT(inSuite, memcmp(clone_1->Start(), payload_1, clone_1->DataLength()) == 0); + ASSERT_FALSE(clone_1.IsNull()); + EXPECT_EQ(clone_1->DataLength(), config_1.handle->DataLength()); + EXPECT_EQ(memcmp(clone_1->Start(), payload_1, clone_1->DataLength()), 0); if (clone_1->DataLength()) { // Verify that modifying the clone does not affect the original. ScrambleData(clone_1->Start(), clone_1->DataLength()); - NL_TEST_ASSERT(inSuite, memcmp(clone_1->Start(), payload_1, clone_1->DataLength()) != 0); - NL_TEST_ASSERT(inSuite, memcmp(config_1.handle->Start(), payload_1, config_1.handle->DataLength()) == 0); + EXPECT_NE(memcmp(clone_1->Start(), payload_1, clone_1->DataLength()), 0); + EXPECT_EQ(memcmp(config_1.handle->Start(), payload_1, config_1.handle->DataLength()), 0); } // Clone buffer chain. config_1.handle->AddToEnd(config_2.handle.Retain()); - NL_TEST_ASSERT(inSuite, config_1.handle->HasChainedBuffer()); + EXPECT_TRUE(config_1.handle->HasChainedBuffer()); clone_1 = config_1.handle.CloneData(); PacketBufferHandle clone_1_next = clone_1->Next(); - NL_TEST_ASSERT(inSuite, !clone_1.IsNull()); - NL_TEST_ASSERT(inSuite, clone_1->HasChainedBuffer()); - NL_TEST_ASSERT(inSuite, clone_1->DataLength() == config_1.handle->DataLength()); - NL_TEST_ASSERT(inSuite, clone_1->TotalLength() == config_1.handle->TotalLength()); - NL_TEST_ASSERT(inSuite, clone_1_next->DataLength() == config_2.handle->DataLength()); - NL_TEST_ASSERT(inSuite, memcmp(clone_1->Start(), payload_1, clone_1->DataLength()) == 0); - NL_TEST_ASSERT(inSuite, memcmp(clone_1_next->Start(), payload_2, clone_1_next->DataLength()) == 0); + ASSERT_FALSE(clone_1.IsNull()); + EXPECT_TRUE(clone_1->HasChainedBuffer()); + EXPECT_EQ(clone_1->DataLength(), config_1.handle->DataLength()); + EXPECT_EQ(clone_1->TotalLength(), config_1.handle->TotalLength()); + EXPECT_EQ(clone_1_next->DataLength(), config_2.handle->DataLength()); + EXPECT_EQ(memcmp(clone_1->Start(), payload_1, clone_1->DataLength()), 0); + EXPECT_EQ(memcmp(clone_1_next->Start(), payload_2, clone_1_next->DataLength()), 0); if (clone_1->DataLength()) { ScrambleData(clone_1->Start(), clone_1->DataLength()); - NL_TEST_ASSERT(inSuite, memcmp(clone_1->Start(), payload_1, clone_1->DataLength()) != 0); - NL_TEST_ASSERT(inSuite, memcmp(config_1.handle->Start(), payload_1, config_1.handle->DataLength()) == 0); + EXPECT_NE(memcmp(clone_1->Start(), payload_1, clone_1->DataLength()), 0); + EXPECT_EQ(memcmp(config_1.handle->Start(), payload_1, config_1.handle->DataLength()), 0); } if (clone_1_next->DataLength()) { ScrambleData(clone_1_next->Start(), clone_1_next->DataLength()); - NL_TEST_ASSERT(inSuite, memcmp(clone_1_next->Start(), payload_2, clone_1_next->DataLength()) != 0); - NL_TEST_ASSERT(inSuite, memcmp(config_2.handle->Start(), payload_2, config_2.handle->DataLength()) == 0); + EXPECT_NE(memcmp(clone_1_next->Start(), payload_2, clone_1_next->DataLength()), 0); + EXPECT_EQ(memcmp(config_2.handle->Start(), payload_2, config_2.handle->DataLength()), 0); } config_1.handle = nullptr; @@ -1895,12 +1676,11 @@ void PacketBufferTest::CheckHandleCloneData(nlTestSuite * inSuite, void * inCont // construct an oversize buffer. constexpr uint16_t kOversizeDataSize = PacketBuffer::kMaxSizeWithoutReserve + 99; - PacketBuffer * p = - reinterpret_cast(chip::Platform::MemoryAlloc(PacketBuffer::kStructureSize + kOversizeDataSize)); - NL_TEST_ASSERT(inSuite, p != nullptr); + PacketBuffer * p = reinterpret_cast(chip::Platform::MemoryAlloc(kStructureSize + kOversizeDataSize)); + ASSERT_NE(p, nullptr); p->next = nullptr; - p->payload = reinterpret_cast(p) + PacketBuffer::kStructureSize; + p->payload = reinterpret_cast(p) + kStructureSize; p->tot_len = 0; p->len = 0; p->ref = 1; @@ -1912,20 +1692,20 @@ void PacketBufferTest::CheckHandleCloneData(nlTestSuite * inSuite, void * inCont memset(handle->Start(), 1, PacketBuffer::kMaxSizeWithoutReserve); handle->SetDataLength(PacketBuffer::kMaxSizeWithoutReserve); - NL_TEST_ASSERT(inSuite, handle->DataLength() == PacketBuffer::kMaxSizeWithoutReserve); + EXPECT_EQ(handle->DataLength(), PacketBuffer::kMaxSizeWithoutReserve); PacketBufferHandle clone = handle.CloneData(); - NL_TEST_ASSERT(inSuite, !clone.IsNull()); - NL_TEST_ASSERT(inSuite, clone->DataLength() == PacketBuffer::kMaxSizeWithoutReserve); - NL_TEST_ASSERT(inSuite, memcmp(handle->Start(), clone->Start(), PacketBuffer::kMaxSizeWithoutReserve) == 0); + ASSERT_FALSE(clone.IsNull()); + EXPECT_EQ(clone->DataLength(), PacketBuffer::kMaxSizeWithoutReserve); + EXPECT_EQ(memcmp(handle->Start(), clone->Start(), PacketBuffer::kMaxSizeWithoutReserve), 0); // Overfill the buffer and verify that it can not be cloned. memset(handle->Start(), 2, kOversizeDataSize); handle->SetDataLength(kOversizeDataSize); - NL_TEST_ASSERT(inSuite, handle->DataLength() == kOversizeDataSize); + EXPECT_EQ(handle->DataLength(), kOversizeDataSize); clone = handle.CloneData(); - NL_TEST_ASSERT(inSuite, clone.IsNull()); + EXPECT_TRUE(clone.IsNull()); // Free the packet buffer memory ourselves, since we allocated it ourselves. chip::Platform::MemoryFree(std::move(handle).UnsafeRelease()); @@ -1933,97 +1713,30 @@ void PacketBufferTest::CheckHandleCloneData(nlTestSuite * inSuite, void * inCont #endif // CHIP_SYSTEM_PACKETBUFFER_FROM_CHIP_HEAP } -void PacketBufferTest::CheckPacketBufferWriter(nlTestSuite * inSuite, void * inContext) +TEST_F(TestSystemPacketBuffer, CheckPacketBufferWriter) { - struct TestContext * const theContext = static_cast(inContext); - PacketBufferTest * const test = theContext->test; - NL_TEST_ASSERT(inSuite, test->mContext == theContext); - static const char kPayload[] = "Hello, world!"; PacketBufferWriter yay(PacketBufferHandle::New(sizeof(kPayload))); PacketBufferWriter nay(PacketBufferHandle::New(sizeof(kPayload)), sizeof(kPayload) - 2); - NL_TEST_ASSERT(inSuite, !yay.IsNull()); - NL_TEST_ASSERT(inSuite, !nay.IsNull()); + ASSERT_FALSE(yay.IsNull()); + ASSERT_FALSE(nay.IsNull()); yay.Put(kPayload); yay.Put('\0'); nay.Put(kPayload); nay.Put('\0'); - NL_TEST_ASSERT(inSuite, yay.Fit()); - NL_TEST_ASSERT(inSuite, !nay.Fit()); + EXPECT_TRUE(yay.Fit()); + EXPECT_FALSE(nay.Fit()); PacketBufferHandle yayBuffer = yay.Finalize(); PacketBufferHandle nayBuffer = nay.Finalize(); - NL_TEST_ASSERT(inSuite, yay.IsNull()); - NL_TEST_ASSERT(inSuite, nay.IsNull()); - NL_TEST_ASSERT(inSuite, !yayBuffer.IsNull()); - NL_TEST_ASSERT(inSuite, nayBuffer.IsNull()); - NL_TEST_ASSERT(inSuite, memcmp(yayBuffer->Start(), kPayload, sizeof kPayload) == 0); -} - -/** - * Test Suite. It lists all the test functions. - */ -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("PacketBuffer::New", PacketBufferTest::CheckNew), - NL_TEST_DEF("PacketBuffer::Start", PacketBufferTest::CheckStart), - NL_TEST_DEF("PacketBuffer::SetStart", PacketBufferTest::CheckSetStart), - NL_TEST_DEF("PacketBuffer::DataLength", PacketBufferTest::CheckDataLength), - NL_TEST_DEF("PacketBuffer::SetDataLength", PacketBufferTest::CheckSetDataLength), - NL_TEST_DEF("PacketBuffer::TotalLength", PacketBufferTest::CheckTotalLength), - NL_TEST_DEF("PacketBuffer::MaxDataLength", PacketBufferTest::CheckMaxDataLength), - NL_TEST_DEF("PacketBuffer::AvailableDataLength", PacketBufferTest::CheckAvailableDataLength), - NL_TEST_DEF("PacketBuffer::HasChainedBuffer", PacketBufferTest::CheckHasChainedBuffer), - NL_TEST_DEF("PacketBuffer::ReservedSize", PacketBufferTest::CheckReservedSize), - NL_TEST_DEF("PacketBuffer::AddToEnd", PacketBufferTest::CheckAddToEnd), - NL_TEST_DEF("PacketBuffer::PopHead", PacketBufferTest::CheckPopHead), - NL_TEST_DEF("PacketBuffer::CompactHead", PacketBufferTest::CheckCompactHead), - NL_TEST_DEF("PacketBuffer::ConsumeHead", PacketBufferTest::CheckConsumeHead), - NL_TEST_DEF("PacketBuffer::Consume", PacketBufferTest::CheckConsume), - NL_TEST_DEF("PacketBuffer::EnsureReservedSize", PacketBufferTest::CheckEnsureReservedSize), - NL_TEST_DEF("PacketBuffer::AlignPayload", PacketBufferTest::CheckAlignPayload), - NL_TEST_DEF("PacketBuffer::Next", PacketBufferTest::CheckNext), - NL_TEST_DEF("PacketBuffer::Last", PacketBufferTest::CheckLast), - NL_TEST_DEF("PacketBuffer::Read", PacketBufferTest::CheckRead), - NL_TEST_DEF("PacketBuffer::AddRef", PacketBufferTest::CheckAddRef), - NL_TEST_DEF("PacketBuffer::Free", PacketBufferTest::CheckFree), - NL_TEST_DEF("PacketBuffer::FreeHead", PacketBufferTest::CheckFreeHead), - NL_TEST_DEF("PacketBuffer::HandleConstruct", PacketBufferTest::CheckHandleConstruct), - NL_TEST_DEF("PacketBuffer::HandleMove", PacketBufferTest::CheckHandleMove), - NL_TEST_DEF("PacketBuffer::HandleRelease", PacketBufferTest::CheckHandleRelease), - NL_TEST_DEF("PacketBuffer::HandleFree", PacketBufferTest::CheckHandleFree), - NL_TEST_DEF("PacketBuffer::HandleRetain", PacketBufferTest::CheckHandleRetain), - NL_TEST_DEF("PacketBuffer::HandleAdopt", PacketBufferTest::CheckHandleAdopt), - NL_TEST_DEF("PacketBuffer::HandleHold", PacketBufferTest::CheckHandleHold), - NL_TEST_DEF("PacketBuffer::HandleAdvance", PacketBufferTest::CheckHandleAdvance), - NL_TEST_DEF("PacketBuffer::HandleRightSize", PacketBufferTest::CheckHandleRightSize), - NL_TEST_DEF("PacketBuffer::HandleCloneData", PacketBufferTest::CheckHandleCloneData), - NL_TEST_DEF("PacketBuffer::PacketBufferWriter", PacketBufferTest::CheckPacketBufferWriter), - - NL_TEST_SENTINEL() -}; -// clang-format on - -int TestSystemPacketBuffer() -{ - // clang-format off - nlTestSuite theSuite = { - .name ="chip-system-packetbuffer", - .tests = &sTests[0], - .setup = PacketBufferTest::TestSetup, - .tear_down = PacketBufferTest::TestTeardown, - // .initialize = PacketBufferTest::TestInitialize, - .terminate = PacketBufferTest::TestTerminate - }; - // clang-format on - - // Run test suite against one context. - nlTestRunner(&theSuite, &sContext); - - return (nlTestRunnerStats(&theSuite)); + EXPECT_TRUE(yay.IsNull()); + EXPECT_TRUE(nay.IsNull()); + ASSERT_FALSE(yayBuffer.IsNull()); + EXPECT_TRUE(nayBuffer.IsNull()); + EXPECT_EQ(memcmp(yayBuffer->Start(), kPayload, sizeof kPayload), 0); } -CHIP_REGISTER_TEST_SUITE(TestSystemPacketBuffer) +} // namespace System +} // namespace chip diff --git a/src/system/tests/TestSystemScheduleLambda.cpp b/src/system/tests/TestSystemScheduleLambda.cpp index f43fadd94ab2eb..66919780b5d7fe 100644 --- a/src/system/tests/TestSystemScheduleLambda.cpp +++ b/src/system/tests/TestSystemScheduleLambda.cpp @@ -14,83 +14,36 @@ * limitations under the License. */ -#include +#include #include #include -#include -#include #include +#include -// Test input data. +class TestSystemScheduleLambda : public ::testing::Test +{ +public: + static void SetUpTestSuite() + { + ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); + ASSERT_EQ(chip::DeviceLayer::PlatformMgr().InitChipStack(), CHIP_NO_ERROR); + } + + static void TearDownTestSuite() + { + chip::DeviceLayer::PlatformMgr().Shutdown(); + chip::Platform::MemoryShutdown(); + } +}; -static void CheckScheduleLambda(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemScheduleLambda, CheckScheduleLambda) { - bool * called = new bool(false); - chip::DeviceLayer::SystemLayer().ScheduleLambda([called] { - *called = true; + bool called = false; + chip::DeviceLayer::SystemLayer().ScheduleLambda([&called] { + called = true; chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); }); chip::DeviceLayer::PlatformMgr().RunEventLoop(); - NL_TEST_ASSERT(inSuite, *called); - delete called; -} - -// Test Suite - -/** - * Test Suite. It lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("System::TestScheduleLambda", CheckScheduleLambda), - NL_TEST_SENTINEL() -}; -// clang-format on - -static int TestSetup(void * aContext); -static int TestTeardown(void * aContext); - -// clang-format off -static nlTestSuite kTheSuite = -{ - "chip-system-schedule-lambda", - &sTests[0], - TestSetup, - TestTeardown -}; -// clang-format on - -/** - * Set up the test suite. - */ -static int TestSetup(void * aContext) -{ - if (chip::Platform::MemoryInit() != CHIP_NO_ERROR) - return FAILURE; - if (chip::DeviceLayer::PlatformMgr().InitChipStack() != CHIP_NO_ERROR) - return FAILURE; - return (SUCCESS); + EXPECT_TRUE(called); } - -/** - * Tear down the test suite. - * Free memory reserved at TestSetup. - */ -static int TestTeardown(void * aContext) -{ - chip::DeviceLayer::PlatformMgr().Shutdown(); - chip::Platform::MemoryShutdown(); - return (SUCCESS); -} - -int TestSystemScheduleLambda() -{ - // Run test suit againt one lContext. - nlTestRunner(&kTheSuite, nullptr); - - return nlTestRunnerStats(&kTheSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestSystemScheduleLambda) diff --git a/src/system/tests/TestSystemScheduleWork.cpp b/src/system/tests/TestSystemScheduleWork.cpp index 29c4a6eda75efd..793e267be929e0 100644 --- a/src/system/tests/TestSystemScheduleWork.cpp +++ b/src/system/tests/TestSystemScheduleWork.cpp @@ -14,13 +14,28 @@ * limitations under the License. */ -#include +#include #include #include -#include -#include #include +#include + +class TestSystemScheduleWork : public ::testing::Test +{ +public: + static void SetUpTestSuite() + { + ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); + ASSERT_EQ(chip::DeviceLayer::PlatformMgr().InitChipStack(), CHIP_NO_ERROR); + } + + static void TearDownTestSuite() + { + chip::DeviceLayer::PlatformMgr().Shutdown(); + chip::Platform::MemoryShutdown(); + } +}; static void IncrementIntCounter(chip::System::Layer *, void * state) { @@ -32,76 +47,12 @@ static void StopEventLoop(chip::System::Layer *, void *) chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); } -static void CheckScheduleWorkTwice(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemScheduleWork, CheckScheduleWork) { - int * callCount = new int(0); - NL_TEST_ASSERT(inSuite, chip::DeviceLayer::SystemLayer().ScheduleWork(IncrementIntCounter, callCount) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, chip::DeviceLayer::SystemLayer().ScheduleWork(IncrementIntCounter, callCount) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, chip::DeviceLayer::SystemLayer().ScheduleWork(StopEventLoop, nullptr) == CHIP_NO_ERROR); + int callCount = 0; + EXPECT_EQ(chip::DeviceLayer::SystemLayer().ScheduleWork(IncrementIntCounter, &callCount), CHIP_NO_ERROR); + EXPECT_EQ(chip::DeviceLayer::SystemLayer().ScheduleWork(IncrementIntCounter, &callCount), CHIP_NO_ERROR); + EXPECT_EQ(chip::DeviceLayer::SystemLayer().ScheduleWork(StopEventLoop, nullptr), CHIP_NO_ERROR); chip::DeviceLayer::PlatformMgr().RunEventLoop(); - NL_TEST_ASSERT(inSuite, *callCount == 2); - delete callCount; -} - -// Test Suite - -/** - * Test Suite. It lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("System::TestScheduleWorkTwice", CheckScheduleWorkTwice), - NL_TEST_SENTINEL() -}; -// clang-format on - -static int TestSetup(void * aContext); -static int TestTeardown(void * aContext); - -// clang-format off -static nlTestSuite kTheSuite = -{ - "chip-system-schedule-work", - &sTests[0], - TestSetup, - TestTeardown -}; -// clang-format on - -/** - * Set up the test suite. - */ -static int TestSetup(void * aContext) -{ - if (chip::Platform::MemoryInit() != CHIP_NO_ERROR) - { - return FAILURE; - } - - if (chip::DeviceLayer::PlatformMgr().InitChipStack() != CHIP_NO_ERROR) - return FAILURE; - - return (SUCCESS); + EXPECT_EQ(callCount, 2); } - -/** - * Tear down the test suite. - * Free memory reserved at TestSetup. - */ -static int TestTeardown(void * aContext) -{ - chip::DeviceLayer::PlatformMgr().Shutdown(); - chip::Platform::MemoryShutdown(); - return (SUCCESS); -} - -int TestSystemScheduleWork() -{ - // Run test suit againt one lContext. - nlTestRunner(&kTheSuite, nullptr); - - return nlTestRunnerStats(&kTheSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestSystemScheduleWork) diff --git a/src/system/tests/TestSystemTimer.cpp b/src/system/tests/TestSystemTimer.cpp index 5cd499fdcb816f..6c065b96a01f9a 100644 --- a/src/system/tests/TestSystemTimer.cpp +++ b/src/system/tests/TestSystemTimer.cpp @@ -23,13 +23,15 @@ * */ -#include +#include +#include +#include + +#include #include #include -#include -#include -#include +#include #include #include @@ -39,10 +41,6 @@ #include #endif // CHIP_SYSTEM_CONFIG_USE_LWIP -#include -#include -#include - using chip::ErrorStr; using namespace chip::System; @@ -94,52 +92,64 @@ class LayerEvents mGreedyTimer; // for greedy timer - uint32_t mNumTimersHandled; + static void SetUpTestSuite() + { + ASSERT_EQ(::chip::Platform::MemoryInit(), CHIP_NO_ERROR); + +#if CHIP_SYSTEM_CONFIG_USE_LWIP && (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0) && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT) + static sys_mbox_t * sLwIPEventQueue = NULL; + sys_mbox_new(sLwIPEventQueue, 100); + tcpip_init(NULL, NULL); +#endif // CHIP_SYSTEM_CONFIG_USE_LWIP && (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0) && + // !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT) + + mLayer.Init(); + } - void GreedyTimer() + static void TearDownTestSuite() { - NL_TEST_ASSERT(mTestSuite, mNumTimersHandled < MAX_NUM_TIMERS); + mLayer.Shutdown(); - if (mNumTimersHandled >= MAX_NUM_TIMERS) - { - return; - } +#if CHIP_SYSTEM_CONFIG_USE_LWIP && (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0) && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT) + tcpip_finish(NULL, NULL); +#endif // CHIP_SYSTEM_CONFIG_USE_LWIP && (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0) && + // !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT) - mNumTimersHandled++; + ::chip::Platform::MemoryShutdown(); } - static void GreedyTimer(void * p) + + template + static auto GetTimerPoolObject(T && pool) { - TestContext * lContext = static_cast(p); - lContext->GreedyTimer(); + return pool.mTimerPool; } - TestContext() : mGreedyTimer(GreedyTimer, this), mNumTimersHandled(0) {} + static LayerImpl mLayer; }; -static TestContext * gCurrentTestContext = nullptr; +LayerImpl TestSystemTimer::mLayer; + +static TestSystemTimer * gCurrentTestContext = nullptr; class ScopedGlobalTestContext { public: - ScopedGlobalTestContext(TestContext * ctx) { gCurrentTestContext = ctx; } + ScopedGlobalTestContext(TestSystemTimer * ctx) { gCurrentTestContext = ctx; } ~ScopedGlobalTestContext() { gCurrentTestContext = nullptr; } }; -// Test input data. - static volatile bool sOverflowTestDone; void TimerFailed(void * aState) { - TestContext * lContext = static_cast(aState); - NL_TEST_ASSERT(lContext->mTestSuite, false); sOverflowTestDone = true; + FAIL() << "Timer failed"; } void HandleTimerFailed(Layer * systemLayer, void * aState) @@ -150,12 +160,11 @@ void HandleTimerFailed(Layer * systemLayer, void * aState) void HandleTimer10Success(Layer * systemLayer, void * aState) { - TestContext & lContext = *static_cast(aState); - NL_TEST_ASSERT(lContext.mTestSuite, true); + EXPECT_TRUE(true); sOverflowTestDone = true; } -static void CheckOverflow(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemTimer, CheckOverflow) { if (!LayerEvents::HasServiceEvents()) return; @@ -163,29 +172,27 @@ static void CheckOverflow(nlTestSuite * inSuite, void * aContext) chip::System::Clock::Milliseconds32 timeout_overflow_0ms = chip::System::Clock::Milliseconds32(652835029); chip::System::Clock::Milliseconds32 timeout_10ms = chip::System::Clock::Milliseconds32(10); - TestContext & lContext = *static_cast(aContext); - Layer & lSys = *lContext.mLayer; + Layer & lSys = mLayer; sOverflowTestDone = false; - lSys.StartTimer(timeout_overflow_0ms, HandleTimerFailed, aContext); - lSys.StartTimer(timeout_10ms, HandleTimer10Success, aContext); + lSys.StartTimer(timeout_overflow_0ms, HandleTimerFailed, this); + lSys.StartTimer(timeout_10ms, HandleTimer10Success, this); while (!sOverflowTestDone) { LayerEvents::ServiceEvents(lSys); } - lSys.CancelTimer(HandleTimerFailed, aContext); + lSys.CancelTimer(HandleTimerFailed, this); // cb timer is cancelled by destructor - lSys.CancelTimer(HandleTimer10Success, aContext); + lSys.CancelTimer(HandleTimer10Success, this); } void HandleGreedyTimer(Layer * aLayer, void * aState) { static uint32_t sNumTimersHandled = 0; - TestContext & lContext = *static_cast(aState); - NL_TEST_ASSERT(lContext.mTestSuite, sNumTimersHandled < MAX_NUM_TIMERS); + EXPECT_LT(sNumTimersHandled, MAX_NUM_TIMERS); if (sNumTimersHandled >= MAX_NUM_TIMERS) { @@ -196,27 +203,24 @@ void HandleGreedyTimer(Layer * aLayer, void * aState) sNumTimersHandled++; } -static void CheckStarvation(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemTimer, CheckStarvation) { if (!LayerEvents::HasServiceEvents()) return; - TestContext & lContext = *static_cast(aContext); - Layer & lSys = *lContext.mLayer; + Layer & lSys = mLayer; - lSys.StartTimer(chip::System::Clock::kZero, HandleGreedyTimer, aContext); + lSys.StartTimer(chip::System::Clock::kZero, HandleGreedyTimer, this); LayerEvents::ServiceEvents(lSys); } -static void CheckOrder(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemTimer, CheckOrder) { if (!LayerEvents::HasServiceEvents()) return; - TestContext & testContext = *static_cast(aContext); - Layer & systemLayer = *testContext.mLayer; - nlTestSuite * const suite = testContext.mTestSuite; + Layer & systemLayer = mLayer; struct TestState { @@ -236,7 +240,7 @@ static void CheckOrder(nlTestSuite * inSuite, void * aContext) char record[5] = { 0 }; }; TestState testState; - NL_TEST_ASSERT(suite, testState.record[0] == 0); + EXPECT_EQ(testState.record[0], 0); Clock::ClockBase * const savedClock = &SystemClock(); Clock::Internal::MockClock mockClock; @@ -249,27 +253,25 @@ static void CheckOrder(nlTestSuite * inSuite, void * aContext) systemLayer.StartTimer(0_ms, TestState::A, &testState); LayerEvents::ServiceEvents(systemLayer); - NL_TEST_ASSERT(suite, strcmp(testState.record, "A") == 0); + EXPECT_EQ(strcmp(testState.record, "A"), 0); mockClock.AdvanceMonotonic(100_ms); LayerEvents::ServiceEvents(systemLayer); - NL_TEST_ASSERT(suite, strcmp(testState.record, "AB") == 0); + EXPECT_EQ(strcmp(testState.record, "AB"), 0); mockClock.AdvanceMonotonic(200_ms); LayerEvents::ServiceEvents(systemLayer); - NL_TEST_ASSERT(suite, strcmp(testState.record, "ABCD") == 0); + EXPECT_EQ(strcmp(testState.record, "ABCD"), 0); Clock::Internal::SetSystemClockForTesting(savedClock); } -static void CheckCancellation(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemTimer, CheckCancellation) { if (!LayerEvents::HasServiceEvents()) return; - TestContext & testContext = *static_cast(aContext); - Layer & systemLayer = *testContext.mLayer; - nlTestSuite * const suite = testContext.mTestSuite; + Layer & systemLayer = mLayer; struct TestState { @@ -305,7 +307,7 @@ static void CheckCancellation(nlTestSuite * inSuite, void * aContext) Layer & mSystemLayer; }; TestState testState(systemLayer); - NL_TEST_ASSERT(suite, testState.record[0] == 0); + EXPECT_EQ(testState.record[0], 0); Clock::ClockBase * const savedClock = &SystemClock(); Clock::Internal::MockClock mockClock; @@ -320,7 +322,7 @@ static void CheckCancellation(nlTestSuite * inSuite, void * aContext) mockClock.AdvanceMonotonic(100_ms); LayerEvents::ServiceEvents(systemLayer); - NL_TEST_ASSERT(suite, strcmp(testState.record, "AC") == 0); + EXPECT_EQ(strcmp(testState.record, "AC"), 0); Clock::Internal::SetSystemClockForTesting(savedClock); } @@ -335,11 +337,11 @@ constexpr unsigned kCancelTimerCount = CHIP_SYSTEM_CONFIG_NUM_TIMERS - 4; int gCallbackProcessed[kCancelTimerCount]; /// Validates that gCallbackProcessed has valid values (0 or 1) -void ValidateExecutedTimerCounts(nlTestSuite * suite) +void ValidateExecutedTimerCounts() { for (int processed : gCallbackProcessed) { - NL_TEST_ASSERT(suite, (processed == 0) || (processed == 1)); + EXPECT_TRUE((processed == 0) || (processed == 1)); } } @@ -376,13 +378,13 @@ void Callback(Layer * layer, void * state) continue; } ChipLogProgress(Test, "Timer %u is being cancelled", i); - gCurrentTestContext->mLayer->CancelTimer(Callback, reinterpret_cast(static_cast(i))); + gCurrentTestContext->mLayer.CancelTimer(Callback, reinterpret_cast(static_cast(i))); gCallbackProcessed[i]++; // pretend executed. } } } -void Test(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemTimer, CancelTimerTest) { // Validates that timers can cancel other timers. Generally the test will // do the following: @@ -395,11 +397,10 @@ void Test(nlTestSuite * inSuite, void * aContext) // other timers, even if they are expiring at the same time) memset(gCallbackProcessed, 0, sizeof(gCallbackProcessed)); - TestContext & testContext = *static_cast(aContext); - ScopedGlobalTestContext testScope(&testContext); + // TestContext & testContext = *static_cast(aContext); + // ScopedGlobalTestContext testScope(&testContext); - Layer & systemLayer = *testContext.mLayer; - nlTestSuite * const suite = testContext.mTestSuite; + Layer & systemLayer = mLayer; Clock::ClockBase * const savedClock = &SystemClock(); Clock::Internal::MockClock mockClock; @@ -408,19 +409,18 @@ void Test(nlTestSuite * inSuite, void * aContext) for (unsigned i = 0; i < kCancelTimerCount; i++) { - NL_TEST_ASSERT( - suite, systemLayer.StartTimer(10_ms, Callback, reinterpret_cast(static_cast(i))) == CHIP_NO_ERROR); + EXPECT_EQ(systemLayer.StartTimer(10_ms, Callback, reinterpret_cast(static_cast(i))), CHIP_NO_ERROR); } LayerEvents::ServiceEvents(systemLayer); - ValidateExecutedTimerCounts(suite); - NL_TEST_ASSERT(suite, ExecutedTimerCount() == 0); + ValidateExecutedTimerCounts(); + EXPECT_EQ(ExecutedTimerCount(), 0U); mockClock.AdvanceMonotonic(20_ms); LayerEvents::ServiceEvents(systemLayer); - ValidateExecutedTimerCounts(suite); - NL_TEST_ASSERT(suite, ExecutedTimerCount() == kCancelTimerCount); + ValidateExecutedTimerCounts(); + EXPECT_EQ(ExecutedTimerCount(), kCancelTimerCount); Clock::Internal::SetSystemClockForTesting(savedClock); } @@ -429,22 +429,8 @@ void Test(nlTestSuite * inSuite, void * aContext) } // namespace // Test the implementation helper classes TimerPool, TimerList, and TimerData. -namespace chip { -namespace System { -class TestTimer +TEST_F(TestSystemTimer, CheckTimerPool) { -public: - static void CheckTimerPool(nlTestSuite * inSuite, void * aContext); -}; -} // namespace System -} // namespace chip - -void chip::System::TestTimer::CheckTimerPool(nlTestSuite * inSuite, void * aContext) -{ - TestContext & testContext = *static_cast(aContext); - Layer & systemLayer = *testContext.mLayer; - nlTestSuite * const suite = testContext.mTestSuite; - using Timer = TimerList::Node; struct TestState { @@ -468,122 +454,121 @@ void chip::System::TestTimer::CheckTimerPool(nlTestSuite * inSuite, void * aCont }; TimerPool pool; - NL_TEST_ASSERT(suite, pool.mTimerPool.Allocated() == 0); + EXPECT_EQ(pool.mTimerPool.Allocated(), 0U); SYSTEM_STATS_RESET(Stats::kSystemLayer_NumTimers); SYSTEM_STATS_RESET_HIGH_WATER_MARK_FOR_TESTING(Stats::kSystemLayer_NumTimers); - NL_TEST_ASSERT(suite, SYSTEM_STATS_TEST_IN_USE(Stats::kSystemLayer_NumTimers, 0)); - NL_TEST_ASSERT(suite, SYSTEM_STATS_TEST_HIGH_WATER_MARK(Stats::kSystemLayer_NumTimers, 0)); + EXPECT_TRUE(SYSTEM_STATS_TEST_IN_USE(Stats::kSystemLayer_NumTimers, 0)); + EXPECT_TRUE(SYSTEM_STATS_TEST_HIGH_WATER_MARK(Stats::kSystemLayer_NumTimers, 0)); // Test TimerPool::Create() and TimerData accessors. for (auto & timer : testTimer) { - timer.timer = pool.Create(systemLayer, timer.awakenTime, timer.onComplete, &testState); + timer.timer = pool.Create(mLayer, timer.awakenTime, timer.onComplete, &testState); } - NL_TEST_ASSERT(suite, SYSTEM_STATS_TEST_IN_USE(Stats::kSystemLayer_NumTimers, 4)); + EXPECT_TRUE(SYSTEM_STATS_TEST_IN_USE(Stats::kSystemLayer_NumTimers, 4)); for (auto & timer : testTimer) { - NL_TEST_ASSERT(suite, timer.timer != nullptr); - NL_TEST_ASSERT(suite, timer.timer->AwakenTime() == timer.awakenTime); - NL_TEST_ASSERT(suite, timer.timer->GetCallback().GetOnComplete() == timer.onComplete); - NL_TEST_ASSERT(suite, timer.timer->GetCallback().GetAppState() == &testState); - NL_TEST_ASSERT(suite, timer.timer->GetCallback().GetSystemLayer() == &systemLayer); + ASSERT_NE(timer.timer, nullptr); + EXPECT_EQ(timer.timer->AwakenTime(), timer.awakenTime); + // TODO: Fix casting and use EXPECT_EQ + EXPECT_TRUE(timer.timer->GetCallback().GetOnComplete() == timer.onComplete); + EXPECT_EQ(timer.timer->GetCallback().GetAppState(), &testState); + EXPECT_EQ(timer.timer->GetCallback().GetSystemLayer(), &mLayer); } // Test TimerList operations. TimerList list; - NL_TEST_ASSERT(suite, list.Remove(nullptr) == nullptr); - NL_TEST_ASSERT(suite, list.Remove(nullptr, nullptr) == nullptr); - NL_TEST_ASSERT(suite, list.PopEarliest() == nullptr); - NL_TEST_ASSERT(suite, list.PopIfEarlier(500_ms) == nullptr); - NL_TEST_ASSERT(suite, list.Earliest() == nullptr); - NL_TEST_ASSERT(suite, list.Empty()); + EXPECT_EQ(list.Remove(nullptr), nullptr); + EXPECT_EQ(list.Remove(nullptr, nullptr), nullptr); + EXPECT_EQ(list.PopEarliest(), nullptr); + EXPECT_EQ(list.PopIfEarlier(500_ms), nullptr); + EXPECT_EQ(list.Earliest(), nullptr); + EXPECT_TRUE(list.Empty()); Timer * earliest = list.Add(testTimer[0].timer); // list: () → (0) returns: 0 - NL_TEST_ASSERT(suite, earliest == testTimer[0].timer); - NL_TEST_ASSERT(suite, list.PopIfEarlier(10_ms) == nullptr); - NL_TEST_ASSERT(suite, list.Earliest() == testTimer[0].timer); - NL_TEST_ASSERT(suite, !list.Empty()); + EXPECT_EQ(earliest, testTimer[0].timer); + EXPECT_EQ(list.PopIfEarlier(10_ms), nullptr); + EXPECT_EQ(list.Earliest(), testTimer[0].timer); + EXPECT_FALSE(list.Empty()); earliest = list.Add(testTimer[1].timer); // list: (0) → (1 0) returns: 1 - NL_TEST_ASSERT(suite, earliest == testTimer[1].timer); - NL_TEST_ASSERT(suite, list.Earliest() == testTimer[1].timer); + EXPECT_EQ(earliest, testTimer[1].timer); + EXPECT_EQ(list.Earliest(), testTimer[1].timer); earliest = list.Add(testTimer[2].timer); // list: (1 0) → (1 0 2) returns: 1 - NL_TEST_ASSERT(suite, earliest == testTimer[1].timer); - NL_TEST_ASSERT(suite, list.Earliest() == testTimer[1].timer); + EXPECT_EQ(earliest, testTimer[1].timer); + EXPECT_EQ(list.Earliest(), testTimer[1].timer); earliest = list.Add(testTimer[3].timer); // list: (1 0 2) → (1 0 2 3) returns: 1 - NL_TEST_ASSERT(suite, earliest == testTimer[1].timer); - NL_TEST_ASSERT(suite, list.Earliest() == testTimer[1].timer); + EXPECT_EQ(earliest, testTimer[1].timer); + EXPECT_EQ(list.Earliest(), testTimer[1].timer); earliest = list.Remove(earliest); // list: (1 0 2 3) → (0 2 3) returns: 0 - NL_TEST_ASSERT(suite, earliest == testTimer[0].timer); - NL_TEST_ASSERT(suite, list.Earliest() == testTimer[0].timer); + EXPECT_EQ(earliest, testTimer[0].timer); + EXPECT_EQ(list.Earliest(), testTimer[0].timer); earliest = list.Remove(TestState::Reset, &testState); // list: (0 2 3) → (0 3) returns: 2 - NL_TEST_ASSERT(suite, earliest == testTimer[2].timer); - NL_TEST_ASSERT(suite, list.Earliest() == testTimer[0].timer); + EXPECT_EQ(earliest, testTimer[2].timer); + EXPECT_EQ(list.Earliest(), testTimer[0].timer); earliest = list.PopEarliest(); // list: (0 3) → (3) returns: 0 - NL_TEST_ASSERT(suite, earliest == testTimer[0].timer); - NL_TEST_ASSERT(suite, list.Earliest() == testTimer[3].timer); + EXPECT_EQ(earliest, testTimer[0].timer); + EXPECT_EQ(list.Earliest(), testTimer[3].timer); earliest = list.PopIfEarlier(10_ms); // list: (3) → (3) returns: nullptr - NL_TEST_ASSERT(suite, earliest == nullptr); + EXPECT_EQ(earliest, nullptr); earliest = list.PopIfEarlier(500_ms); // list: (3) → () returns: 3 - NL_TEST_ASSERT(suite, earliest == testTimer[3].timer); - NL_TEST_ASSERT(suite, list.Empty()); + EXPECT_EQ(earliest, testTimer[3].timer); + EXPECT_TRUE(list.Empty()); earliest = list.Add(testTimer[3].timer); // list: () → (3) returns: 3 list.Clear(); // list: (3) → () - NL_TEST_ASSERT(suite, earliest == testTimer[3].timer); - NL_TEST_ASSERT(suite, list.Empty()); + EXPECT_EQ(earliest, testTimer[3].timer); + EXPECT_TRUE(list.Empty()); for (auto & timer : testTimer) { list.Add(timer.timer); } TimerList early = list.ExtractEarlier(200_ms); // list: (1 0 2 3) → (2 3) returns: (1 0) - NL_TEST_ASSERT(suite, list.PopEarliest() == testTimer[2].timer); - NL_TEST_ASSERT(suite, list.PopEarliest() == testTimer[3].timer); - NL_TEST_ASSERT(suite, list.PopEarliest() == nullptr); - NL_TEST_ASSERT(suite, early.PopEarliest() == testTimer[1].timer); - NL_TEST_ASSERT(suite, early.PopEarliest() == testTimer[0].timer); - NL_TEST_ASSERT(suite, early.PopEarliest() == nullptr); + EXPECT_EQ(list.PopEarliest(), testTimer[2].timer); + EXPECT_EQ(list.PopEarliest(), testTimer[3].timer); + EXPECT_EQ(list.PopEarliest(), nullptr); + EXPECT_EQ(early.PopEarliest(), testTimer[1].timer); + EXPECT_EQ(early.PopEarliest(), testTimer[0].timer); + EXPECT_EQ(early.PopEarliest(), nullptr); // Test TimerPool::Invoke() - NL_TEST_ASSERT(suite, testState.count == 0); + EXPECT_EQ(testState.count, 0); pool.Invoke(testTimer[0].timer); testTimer[0].timer = nullptr; - NL_TEST_ASSERT(suite, testState.count == 1); - NL_TEST_ASSERT(suite, pool.mTimerPool.Allocated() == 3); - NL_TEST_ASSERT(suite, SYSTEM_STATS_TEST_IN_USE(Stats::kSystemLayer_NumTimers, 3)); + EXPECT_EQ(testState.count, 1); + EXPECT_EQ(pool.mTimerPool.Allocated(), 3U); + EXPECT_TRUE(SYSTEM_STATS_TEST_IN_USE(Stats::kSystemLayer_NumTimers, 3)); // Test TimerPool::Release() pool.Release(testTimer[1].timer); testTimer[1].timer = nullptr; - NL_TEST_ASSERT(suite, testState.count == 1); - NL_TEST_ASSERT(suite, pool.mTimerPool.Allocated() == 2); - NL_TEST_ASSERT(suite, SYSTEM_STATS_TEST_IN_USE(Stats::kSystemLayer_NumTimers, 2)); + EXPECT_EQ(testState.count, 1); + EXPECT_EQ(pool.mTimerPool.Allocated(), 2U); + EXPECT_TRUE(SYSTEM_STATS_TEST_IN_USE(Stats::kSystemLayer_NumTimers, 2)); pool.ReleaseAll(); - NL_TEST_ASSERT(suite, pool.mTimerPool.Allocated() == 0); - NL_TEST_ASSERT(suite, SYSTEM_STATS_TEST_IN_USE(Stats::kSystemLayer_NumTimers, 0)); - NL_TEST_ASSERT(suite, SYSTEM_STATS_TEST_HIGH_WATER_MARK(Stats::kSystemLayer_NumTimers, 4)); + EXPECT_EQ(pool.mTimerPool.Allocated(), 0U); + EXPECT_TRUE(SYSTEM_STATS_TEST_IN_USE(Stats::kSystemLayer_NumTimers, 0)); + EXPECT_TRUE(SYSTEM_STATS_TEST_HIGH_WATER_MARK(Stats::kSystemLayer_NumTimers, 4)); } -static void ExtendTimerToTest(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemTimer, ExtendTimerToTest) { if (!LayerEvents::HasServiceEvents()) return; - TestContext & testContext = *static_cast(aContext); - Layer & systemLayer = *testContext.mLayer; - nlTestSuite * const suite = testContext.mTestSuite; + Layer & systemLayer = mLayer; struct TestState { @@ -603,7 +588,7 @@ static void ExtendTimerToTest(nlTestSuite * inSuite, void * aContext) char record[5] = { 0 }; }; TestState testState; - NL_TEST_ASSERT(suite, testState.record[0] == 0); + EXPECT_EQ(testState.record[0], 0); Clock::ClockBase * const savedClock = &SystemClock(); Clock::Internal::MockClock mockClock; @@ -618,7 +603,7 @@ static void ExtendTimerToTest(nlTestSuite * inSuite, void * aContext) systemLayer.ExtendTimerTo(100_ms, TestState::A, &testState); mockClock.AdvanceMonotonic(100_ms); LayerEvents::ServiceEvents(systemLayer); - NL_TEST_ASSERT(suite, strcmp(testState.record, "A") == 0); + EXPECT_EQ(strcmp(testState.record, "A"), 0); // Timer B as 50ms remaining. ExtendTimerTo 25 should have no effect // Timer C as 100ms remaining. ExtendTimerTo 75ms should have no effect @@ -629,32 +614,30 @@ static void ExtendTimerToTest(nlTestSuite * inSuite, void * aContext) mockClock.AdvanceMonotonic(25_ms); LayerEvents::ServiceEvents(systemLayer); - NL_TEST_ASSERT(suite, strcmp(testState.record, "A") == 0); + EXPECT_EQ(strcmp(testState.record, "A"), 0); mockClock.AdvanceMonotonic(25_ms); LayerEvents::ServiceEvents(systemLayer); - NL_TEST_ASSERT(suite, strcmp(testState.record, "AB") == 0); + EXPECT_EQ(strcmp(testState.record, "AB"), 0); // Timer D as 25ms remaining. Timer should be extend to a duration of 75ms systemLayer.ExtendTimerTo(75_ms, TestState::D, &testState); mockClock.AdvanceMonotonic(100_ms); LayerEvents::ServiceEvents(systemLayer); - NL_TEST_ASSERT(suite, strcmp(testState.record, "ABCD") == 0); + EXPECT_EQ(strcmp(testState.record, "ABCD"), 0); Clock::Internal::SetSystemClockForTesting(savedClock); // Extending a timer by 0 ms permitted - NL_TEST_ASSERT(suite, systemLayer.ExtendTimerTo(0_ms, TestState::A, &testState) == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(systemLayer.ExtendTimerTo(0_ms, TestState::A, &testState), CHIP_ERROR_INVALID_ARGUMENT); } -static void IsTimerActiveTest(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemTimer, IsTimerActiveTest) { if (!LayerEvents::HasServiceEvents()) return; - TestContext & testContext = *static_cast(aContext); - Layer & systemLayer = *testContext.mLayer; - nlTestSuite * const suite = testContext.mTestSuite; + Layer & systemLayer = mLayer; struct TestState { @@ -673,7 +656,7 @@ static void IsTimerActiveTest(nlTestSuite * inSuite, void * aContext) char record[4] = { 0 }; }; TestState testState; - NL_TEST_ASSERT(suite, testState.record[0] == 0); + EXPECT_EQ(testState.record[0], 0); Clock::ClockBase * const savedClock = &SystemClock(); Clock::Internal::MockClock mockClock; @@ -684,113 +667,27 @@ static void IsTimerActiveTest(nlTestSuite * inSuite, void * aContext) systemLayer.StartTimer(200_ms, TestState::B, &testState); systemLayer.StartTimer(300_ms, TestState::C, &testState); - NL_TEST_ASSERT(suite, systemLayer.IsTimerActive(TestState::A, &testState)); - NL_TEST_ASSERT(suite, systemLayer.IsTimerActive(TestState::B, &testState)); - NL_TEST_ASSERT(suite, systemLayer.IsTimerActive(TestState::C, &testState)); + EXPECT_TRUE(systemLayer.IsTimerActive(TestState::A, &testState)); + EXPECT_TRUE(systemLayer.IsTimerActive(TestState::B, &testState)); + EXPECT_TRUE(systemLayer.IsTimerActive(TestState::C, &testState)); mockClock.AdvanceMonotonic(100_ms); LayerEvents::ServiceEvents(systemLayer); - NL_TEST_ASSERT(suite, systemLayer.IsTimerActive(TestState::A, &testState) == false); - NL_TEST_ASSERT(suite, systemLayer.IsTimerActive(TestState::B, &testState)); - NL_TEST_ASSERT(suite, systemLayer.IsTimerActive(TestState::C, &testState)); + EXPECT_FALSE(systemLayer.IsTimerActive(TestState::A, &testState)); + EXPECT_TRUE(systemLayer.IsTimerActive(TestState::B, &testState)); + EXPECT_TRUE(systemLayer.IsTimerActive(TestState::C, &testState)); mockClock.AdvanceMonotonic(100_ms); LayerEvents::ServiceEvents(systemLayer); - NL_TEST_ASSERT(suite, systemLayer.IsTimerActive(TestState::B, &testState) == false); - NL_TEST_ASSERT(suite, systemLayer.IsTimerActive(TestState::C, &testState)); + EXPECT_FALSE(systemLayer.IsTimerActive(TestState::B, &testState)); + EXPECT_TRUE(systemLayer.IsTimerActive(TestState::C, &testState)); mockClock.AdvanceMonotonic(100_ms); LayerEvents::ServiceEvents(systemLayer); - NL_TEST_ASSERT(suite, systemLayer.IsTimerActive(TestState::C, &testState) == false); + EXPECT_FALSE(systemLayer.IsTimerActive(TestState::C, &testState)); Clock::Internal::SetSystemClockForTesting(savedClock); } -// Test Suite - -/** - * Test Suite. It lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("Timer::TestOverflow", CheckOverflow), - NL_TEST_DEF("Timer::TestTimerStarvation", CheckStarvation), - NL_TEST_DEF("Timer::TestTimerOrder", CheckOrder), - NL_TEST_DEF("Timer::TestTimerCancellation", CheckCancellation), - NL_TEST_DEF("Timer::TestTimerPool", chip::System::TestTimer::CheckTimerPool), - NL_TEST_DEF("Timer::TestCancelTimer", CancelTimerTest::Test), - NL_TEST_DEF("Timer::ExtendTimerTo", ExtendTimerToTest), - NL_TEST_DEF("Timer::TestIsTimerActive", IsTimerActiveTest), - NL_TEST_SENTINEL() -}; -// clang-format on - -static int TestSetup(void * aContext); -static int TestTeardown(void * aContext); - -// clang-format off -static nlTestSuite kTheSuite = -{ - "chip-system-timer", - &sTests[0], - TestSetup, - TestTeardown -}; -// clang-format on - -static LayerImpl sLayer; - -/** - * Set up the test suite. - */ -static int TestSetup(void * aContext) -{ - TestContext & lContext = *reinterpret_cast(aContext); - - if (::chip::Platform::MemoryInit() != CHIP_NO_ERROR) - { - return FAILURE; - } - -#if CHIP_SYSTEM_CONFIG_USE_LWIP && (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0) && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT) - static sys_mbox_t * sLwIPEventQueue = NULL; - - sys_mbox_new(sLwIPEventQueue, 100); - tcpip_init(NULL, NULL); -#endif // CHIP_SYSTEM_CONFIG_USE_LWIP && (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0) && - // !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT) - - sLayer.Init(); - - lContext.mLayer = &sLayer; - lContext.mTestSuite = &kTheSuite; - - return (SUCCESS); -} - -/** - * Tear down the test suite. - * Free memory reserved at TestSetup. - */ -static int TestTeardown(void * aContext) -{ - TestContext & lContext = *reinterpret_cast(aContext); - - lContext.mLayer->Shutdown(); - -#if CHIP_SYSTEM_CONFIG_USE_LWIP && (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0) && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT) - tcpip_finish(NULL, NULL); -#endif // CHIP_SYSTEM_CONFIG_USE_LWIP && (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0) && - // !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT) - - ::chip::Platform::MemoryShutdown(); - return (SUCCESS); -} - -int TestSystemTimer() -{ - return chip::ExecuteTestsWithContext(&kTheSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestSystemTimer) +} // namespace System +} // namespace chip diff --git a/src/system/tests/TestSystemWakeEvent.cpp b/src/system/tests/TestSystemWakeEvent.cpp index 46ed99dae31656..0978d22131b0e8 100644 --- a/src/system/tests/TestSystemWakeEvent.cpp +++ b/src/system/tests/TestSystemWakeEvent.cpp @@ -21,13 +21,11 @@ * */ -#include +#include #include #include -#include -#include -#include +#include #include #include @@ -51,25 +49,27 @@ class WakeEventTest namespace { -struct TestContext +class TestSystemWakeEvent : public ::testing::Test { - ::chip::System::LayerImpl mSystemLayer; - WakeEvent mWakeEvent; - fd_set mReadSet; - fd_set mWriteSet; - fd_set mErrorSet; - - TestContext() +public: + void SetUp() { mSystemLayer.Init(); mWakeEvent.Open(mSystemLayer); } - ~TestContext() + + void TearDown() { mWakeEvent.Close(mSystemLayer); mSystemLayer.Shutdown(); } + ::chip::System::LayerImpl mSystemLayer; + WakeEvent mWakeEvent; + fd_set mReadSet; + fd_set mWriteSet; + fd_set mErrorSet; + int SelectWakeEvent(timeval timeout = {}) { // NOLINTBEGIN(clang-analyzer-security.insecureAPI.bzero) @@ -85,108 +85,69 @@ struct TestContext } }; -void TestOpen(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemWakeEvent, TestOpen) { - TestContext & lContext = *static_cast(aContext); - NL_TEST_ASSERT(inSuite, WakeEventTest::GetReadFD(lContext.mWakeEvent) >= 0); - NL_TEST_ASSERT(inSuite, lContext.SelectWakeEvent() == 0); + EXPECT_GE(WakeEventTest::GetReadFD(mWakeEvent), 0); + EXPECT_EQ(SelectWakeEvent(), 0); } -void TestNotify(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemWakeEvent, TestNotify) { - TestContext & lContext = *static_cast(aContext); - NL_TEST_ASSERT(inSuite, lContext.SelectWakeEvent() == 0); + EXPECT_EQ(SelectWakeEvent(), 0); // Check that select() succeeds after Notify() has been called - lContext.mWakeEvent.Notify(); - NL_TEST_ASSERT(inSuite, lContext.SelectWakeEvent() == 1); - NL_TEST_ASSERT(inSuite, FD_ISSET(WakeEventTest::GetReadFD(lContext.mWakeEvent), &lContext.mReadSet)); + mWakeEvent.Notify(); + EXPECT_EQ(SelectWakeEvent(), 1); + EXPECT_TRUE(FD_ISSET(WakeEventTest::GetReadFD(mWakeEvent), &mReadSet)); // ...and state of the event is not cleared automatically - NL_TEST_ASSERT(inSuite, lContext.SelectWakeEvent() == 1); - NL_TEST_ASSERT(inSuite, FD_ISSET(WakeEventTest::GetReadFD(lContext.mWakeEvent), &lContext.mReadSet)); + EXPECT_EQ(SelectWakeEvent(), 1); + EXPECT_TRUE(FD_ISSET(WakeEventTest::GetReadFD(mWakeEvent), &mReadSet)); } -void TestConfirm(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemWakeEvent, TestConfirm) { - TestContext & lContext = *static_cast(aContext); - // Check that select() succeeds after Notify() has been called - lContext.mWakeEvent.Notify(); - NL_TEST_ASSERT(inSuite, lContext.SelectWakeEvent() == 1); - NL_TEST_ASSERT(inSuite, FD_ISSET(WakeEventTest::GetReadFD(lContext.mWakeEvent), &lContext.mReadSet)); + mWakeEvent.Notify(); + EXPECT_EQ(SelectWakeEvent(), 1); + EXPECT_TRUE(FD_ISSET(WakeEventTest::GetReadFD(mWakeEvent), &mReadSet)); // Check that Confirm() clears state of the event - lContext.mWakeEvent.Confirm(); - NL_TEST_ASSERT(inSuite, lContext.SelectWakeEvent() == 0); + mWakeEvent.Confirm(); + EXPECT_EQ(SelectWakeEvent(), 0); } #if CHIP_SYSTEM_CONFIG_POSIX_LOCKING void * WaitForEvent(void * aContext) { - TestContext & lContext = *static_cast(aContext); // wait 5 seconds - return reinterpret_cast(lContext.SelectWakeEvent(timeval{ 5, 0 })); + auto * context = static_cast(aContext); + return reinterpret_cast(context->SelectWakeEvent(timeval{ 5, 0 })); } -void TestBlockingSelect(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemWakeEvent, TestBlockingSelect) { - TestContext & lContext = *static_cast(aContext); - // Spawn a thread waiting for the event pthread_t tid = 0; - NL_TEST_ASSERT(inSuite, 0 == pthread_create(&tid, nullptr, WaitForEvent, aContext)); + EXPECT_EQ(0, pthread_create(&tid, nullptr, WaitForEvent, this)); - lContext.mWakeEvent.Notify(); + mWakeEvent.Notify(); void * selectResult = nullptr; - NL_TEST_ASSERT(inSuite, 0 == pthread_join(tid, &selectResult)); - NL_TEST_ASSERT(inSuite, selectResult == reinterpret_cast(1)); + EXPECT_EQ(0, pthread_join(tid, &selectResult)); + EXPECT_EQ(selectResult, reinterpret_cast(1)); } -#else // CHIP_SYSTEM_CONFIG_POSIX_LOCKING -void TestBlockingSelect(nlTestSuite *, void *) {} #endif // CHIP_SYSTEM_CONFIG_POSIX_LOCKING -void TestClose(nlTestSuite * inSuite, void * aContext) +TEST_F(TestSystemWakeEvent, TestClose) { - TestContext & lContext = *static_cast(aContext); - lContext.mWakeEvent.Close(lContext.mSystemLayer); + mWakeEvent.Close(mSystemLayer); - const auto notifFD = WakeEventTest::GetReadFD(lContext.mWakeEvent); + const auto notifFD = WakeEventTest::GetReadFD(mWakeEvent); // Check that Close() has cleaned up itself and reopen is possible - NL_TEST_ASSERT(inSuite, lContext.mWakeEvent.Open(lContext.mSystemLayer) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, notifFD < 0); + EXPECT_EQ(mWakeEvent.Open(mSystemLayer), CHIP_NO_ERROR); + EXPECT_LT(notifFD, 0); } } // namespace -// Test Suite - -/** - * Test Suite. It lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("WakeEvent::TestOpen", TestOpen), - NL_TEST_DEF("WakeEvent::TestNotify", TestNotify), - NL_TEST_DEF("WakeEvent::TestConfirm", TestConfirm), - NL_TEST_DEF("WakeEvent::TestBlockingSelect", TestBlockingSelect), - NL_TEST_DEF("WakeEvent::TestClose", TestClose), - NL_TEST_SENTINEL() -}; -// clang-format on - -static nlTestSuite kTheSuite = { "chip-system-wake-event", sTests }; - -int TestSystemWakeEvent() -{ - return chip::ExecuteTestsWithContext(&kTheSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestSystemWakeEvent) -#else // CHIP_SYSTEM_CONFIG_USE_SOCKETS -int TestSystemWakeEvent(void) -{ - return SUCCESS; -} #endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS diff --git a/src/system/tests/TestTLVPacketBufferBackingStore.cpp b/src/system/tests/TestTLVPacketBufferBackingStore.cpp index e46906d2edbbb3..6dc76fed46745e 100644 --- a/src/system/tests/TestTLVPacketBufferBackingStore.cpp +++ b/src/system/tests/TestTLVPacketBufferBackingStore.cpp @@ -18,14 +18,13 @@ #include #include +#include + #include #include #include -#include #include -#include - using ::chip::Platform::ScopedMemoryBuffer; using ::chip::System::PacketBuffer; using ::chip::System::PacketBufferHandle; @@ -33,49 +32,27 @@ using ::chip::System::PacketBufferTLVReader; using ::chip::System::PacketBufferTLVWriter; using namespace ::chip; -namespace { - -void WriteUntilRemainingLessThan(nlTestSuite * inSuite, PacketBufferTLVWriter & writer, const uint32_t remainingSize) +class TestTLVPacketBufferBackingStore : public ::testing::Test { - uint32_t lengthRemaining = writer.GetRemainingFreeLength(); - while (lengthRemaining >= remainingSize) +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } + + void WriteUntilRemainingLessThan(PacketBufferTLVWriter & writer, const uint32_t remainingSize) { - NL_TEST_ASSERT(inSuite, writer.Put(TLV::AnonymousTag(), static_cast(7)) == CHIP_NO_ERROR); - lengthRemaining = writer.GetRemainingFreeLength(); + uint32_t lengthRemaining = writer.GetRemainingFreeLength(); + while (lengthRemaining >= remainingSize) + { + EXPECT_EQ(writer.Put(TLV::AnonymousTag(), static_cast(7)), CHIP_NO_ERROR); + lengthRemaining = writer.GetRemainingFreeLength(); + } } -} - -class TLVPacketBufferBackingStoreTest -{ -public: - static int TestSetup(void * inContext); - static int TestTeardown(void * inContext); - - static void BasicEncodeDecode(nlTestSuite * inSuite, void * inContext); - static void MultiBufferEncode(nlTestSuite * inSuite, void * inContext); - static void NonChainedBufferCanReserve(nlTestSuite * inSuite, void * inContext); - static void TestWriterReserveUnreserveDoesNotOverflow(nlTestSuite * inSuite, void * inContext); - static void TestWriterReserve(nlTestSuite * inSuite, void * inContext); }; -int TLVPacketBufferBackingStoreTest::TestSetup(void * inContext) -{ - chip::Platform::MemoryInit(); - - return SUCCESS; -} - -int TLVPacketBufferBackingStoreTest::TestTeardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - - return SUCCESS; -} - /** * Test that we can do a basic encode to TLV followed by decode. */ -void TLVPacketBufferBackingStoreTest::BasicEncodeDecode(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLVPacketBufferBackingStore, BasicEncodeDecode) { auto buffer = PacketBufferHandle::New(PacketBuffer::kMaxSizeWithoutReserve, 0); @@ -84,74 +61,74 @@ void TLVPacketBufferBackingStoreTest::BasicEncodeDecode(nlTestSuite * inSuite, v TLV::TLVType outerContainerType; CHIP_ERROR error = writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Array, outerContainerType); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = writer.Put(TLV::AnonymousTag(), static_cast(7)); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = writer.Put(TLV::AnonymousTag(), static_cast(8)); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = writer.Put(TLV::AnonymousTag(), static_cast(9)); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = writer.EndContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = writer.Finalize(&buffer); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); // Array start/end is 2 bytes. Each entry is also 2 bytes: control + // value. So 8 bytes total. - NL_TEST_ASSERT(inSuite, !buffer->HasChainedBuffer()); - NL_TEST_ASSERT(inSuite, buffer->TotalLength() == 8); - NL_TEST_ASSERT(inSuite, buffer->DataLength() == 8); + EXPECT_FALSE(buffer->HasChainedBuffer()); + EXPECT_EQ(buffer->TotalLength(), 8); + EXPECT_EQ(buffer->DataLength(), 8); PacketBufferTLVReader reader; reader.Init(std::move(buffer)); error = reader.Next(TLV::kTLVType_Array, TLV::AnonymousTag()); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = reader.EnterContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = reader.Next(TLV::kTLVType_UnsignedInteger, TLV::AnonymousTag()); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); uint8_t value; error = reader.Get(value); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, value == 7); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(value, 7); error = reader.Next(TLV::kTLVType_UnsignedInteger, TLV::AnonymousTag()); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = reader.Get(value); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, value == 8); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(value, 8); error = reader.Next(TLV::kTLVType_UnsignedInteger, TLV::AnonymousTag()); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = reader.Get(value); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, value == 9); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(value, 9); error = reader.Next(); - NL_TEST_ASSERT(inSuite, error == CHIP_END_OF_TLV); + EXPECT_EQ(error, CHIP_END_OF_TLV); error = reader.ExitContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = reader.Next(); - NL_TEST_ASSERT(inSuite, error == CHIP_END_OF_TLV); + EXPECT_EQ(error, CHIP_END_OF_TLV); } /** * Test that we can do an encode that's going to split across multiple buffers correctly. */ -void TLVPacketBufferBackingStoreTest::MultiBufferEncode(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLVPacketBufferBackingStore, MultiBufferEncode) { // Start with a too-small buffer. auto buffer = PacketBufferHandle::New(2, 0); @@ -161,97 +138,97 @@ void TLVPacketBufferBackingStoreTest::MultiBufferEncode(nlTestSuite * inSuite, v TLV::TLVType outerContainerType; CHIP_ERROR error = writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Array, outerContainerType); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = writer.Put(TLV::AnonymousTag(), static_cast(7)); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = writer.Put(TLV::AnonymousTag(), static_cast(8)); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); // Something to make sure we have 3 buffers. uint8_t bytes[2000] = { 0 }; error = writer.Put(TLV::AnonymousTag(), ByteSpan(bytes)); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = writer.EndContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = writer.Finalize(&buffer); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); // Array start/end is 2 bytes. First two entries are 2 bytes each. // Third entry is 1 control byte, 2 length bytes, 2000 bytes of data, // for a total of 2009 bytes. constexpr size_t totalSize = 2009; - NL_TEST_ASSERT(inSuite, buffer->HasChainedBuffer()); - NL_TEST_ASSERT(inSuite, buffer->TotalLength() == totalSize); - NL_TEST_ASSERT(inSuite, buffer->DataLength() == 2); + EXPECT_TRUE(buffer->HasChainedBuffer()); + EXPECT_EQ(buffer->TotalLength(), totalSize); + EXPECT_EQ(buffer->DataLength(), 2); auto nextBuffer = buffer->Next(); - NL_TEST_ASSERT(inSuite, nextBuffer->HasChainedBuffer()); - NL_TEST_ASSERT(inSuite, nextBuffer->TotalLength() == totalSize - 2); - NL_TEST_ASSERT(inSuite, nextBuffer->DataLength() == PacketBuffer::kMaxSizeWithoutReserve); + EXPECT_TRUE(nextBuffer->HasChainedBuffer()); + EXPECT_EQ(nextBuffer->TotalLength(), totalSize - 2); + EXPECT_EQ(nextBuffer->DataLength(), PacketBuffer::kMaxSizeWithoutReserve); nextBuffer = nextBuffer->Next(); - NL_TEST_ASSERT(inSuite, !nextBuffer->HasChainedBuffer()); - NL_TEST_ASSERT(inSuite, nextBuffer->TotalLength() == nextBuffer->DataLength()); - NL_TEST_ASSERT(inSuite, nextBuffer->DataLength() == totalSize - 2 - PacketBuffer::kMaxSizeWithoutReserve); + EXPECT_FALSE(nextBuffer->HasChainedBuffer()); + EXPECT_EQ(nextBuffer->TotalLength(), nextBuffer->DataLength()); + EXPECT_EQ(nextBuffer->DataLength(), totalSize - 2 - PacketBuffer::kMaxSizeWithoutReserve); // PacketBufferTLVReader cannot handle non-contiguous buffers, and our // buffers are too big to stick into a single packet buffer. ScopedMemoryBuffer buf; - NL_TEST_ASSERT(inSuite, buf.Calloc(totalSize)); + EXPECT_TRUE(buf.Calloc(totalSize)); size_t offset = 0; while (!buffer.IsNull()) { memcpy(buf.Get() + offset, buffer->Start(), buffer->DataLength()); offset += buffer->DataLength(); buffer.Advance(); - NL_TEST_ASSERT(inSuite, offset < totalSize || (offset == totalSize && buffer.IsNull())); + EXPECT_TRUE(offset < totalSize || (offset == totalSize && buffer.IsNull())); } TLV::TLVReader reader; reader.Init(buf.Get(), totalSize); error = reader.Next(TLV::kTLVType_Array, TLV::AnonymousTag()); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = reader.EnterContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = reader.Next(TLV::kTLVType_UnsignedInteger, TLV::AnonymousTag()); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); uint8_t value; error = reader.Get(value); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, value == 7); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(value, 7); error = reader.Next(TLV::kTLVType_UnsignedInteger, TLV::AnonymousTag()); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = reader.Get(value); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, value == 8); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(value, 8); error = reader.Next(TLV::kTLVType_ByteString, TLV::AnonymousTag()); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); ByteSpan byteValue; error = reader.Get(byteValue); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, byteValue.size() == sizeof(bytes)); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(byteValue.size(), sizeof(bytes)); error = reader.Next(); - NL_TEST_ASSERT(inSuite, error == CHIP_END_OF_TLV); + EXPECT_EQ(error, CHIP_END_OF_TLV); error = reader.ExitContainer(outerContainerType); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = reader.Next(); - NL_TEST_ASSERT(inSuite, error == CHIP_END_OF_TLV); + EXPECT_EQ(error, CHIP_END_OF_TLV); } -void TLVPacketBufferBackingStoreTest::NonChainedBufferCanReserve(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLVPacketBufferBackingStore, NonChainedBufferCanReserve) { // Start with a too-small buffer. uint32_t smallSize = 5; @@ -263,12 +240,12 @@ void TLVPacketBufferBackingStoreTest::NonChainedBufferCanReserve(nlTestSuite * i writer.Init(std::move(buffer), /* useChainedBuffers = */ false); CHIP_ERROR error = writer.ReserveBuffer(smallerSizeToReserver); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); } // This test previously was created to show that there was an overflow bug, now this test mainly // just checks that you cannot reserve this type of TLVBackingStorage buffer. -void TLVPacketBufferBackingStoreTest::TestWriterReserveUnreserveDoesNotOverflow(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLVPacketBufferBackingStore, TestWriterReserveUnreserveDoesNotOverflow) { // Start with a too-small buffer. uint32_t smallSize = 100; @@ -283,29 +260,29 @@ void TLVPacketBufferBackingStoreTest::TestWriterReserveUnreserveDoesNotOverflow( if (error == CHIP_NO_ERROR) { uint32_t lengthRemaining = writer.GetRemainingFreeLength(); - NL_TEST_ASSERT(inSuite, lengthRemaining == 1); + EXPECT_EQ(lengthRemaining, 1U); // Lets try to overflow by getting next buffer in the chain, // unreserving then writing until the end of the current buffer. error = writer.Put(TLV::AnonymousTag(), static_cast(7)); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); lengthRemaining = writer.GetRemainingFreeLength(); - NL_TEST_ASSERT(inSuite, lengthRemaining > smallerSizeToReserver); + EXPECT_GT(lengthRemaining, smallerSizeToReserver); - WriteUntilRemainingLessThan(inSuite, writer, 2); + WriteUntilRemainingLessThan(writer, 2); lengthRemaining = writer.GetRemainingFreeLength(); - NL_TEST_ASSERT(inSuite, lengthRemaining != 0); - NL_TEST_ASSERT(inSuite, lengthRemaining < smallerSizeToReserver); + EXPECT_NE(lengthRemaining, 0U); + EXPECT_LT(lengthRemaining, smallerSizeToReserver); error = writer.UnreserveBuffer(smallerSizeToReserver); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); lengthRemaining = writer.GetRemainingFreeLength(); - NL_TEST_ASSERT(inSuite, lengthRemaining > smallerSizeToReserver); + EXPECT_GT(lengthRemaining, smallerSizeToReserver); // This is where we get overflow. - WriteUntilRemainingLessThan(inSuite, writer, 2); + WriteUntilRemainingLessThan(writer, 2); // If we get here then the overflow condition we were expecting did not happen. If that is the case, // either we have fixed reservation for chained buffers, or expected failure didn't hit on this @@ -314,14 +291,14 @@ void TLVPacketBufferBackingStoreTest::TestWriterReserveUnreserveDoesNotOverflow( // If there is a fix please add reservation for chained buffers, please make sure you account for // what happens if TLVWriter::WriteData fails to get a new buffer but we are not at max size, do // you actually have space for what was supposed to be reserved. - NL_TEST_ASSERT(inSuite, false); + FAIL(); } // We no longer allow non-contigous buffers to be reserved. - NL_TEST_ASSERT(inSuite, error == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(error, CHIP_ERROR_INCORRECT_STATE); } -void TLVPacketBufferBackingStoreTest::TestWriterReserve(nlTestSuite * inSuite, void * inContext) +TEST_F(TestTLVPacketBufferBackingStore, TestWriterReserve) { // Start with a too-small buffer. uint32_t smallSize = 5; @@ -333,51 +310,14 @@ void TLVPacketBufferBackingStoreTest::TestWriterReserve(nlTestSuite * inSuite, v writer.Init(std::move(buffer), /* useChainedBuffers = */ false); CHIP_ERROR error = writer.ReserveBuffer(smallerSizeToReserver); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = writer.Put(TLV::AnonymousTag(), static_cast(7)); - NL_TEST_ASSERT(inSuite, error == CHIP_ERROR_NO_MEMORY); + EXPECT_EQ(error, CHIP_ERROR_NO_MEMORY); error = writer.UnreserveBuffer(smallerSizeToReserver); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = writer.Put(TLV::AnonymousTag(), static_cast(7)); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); } - -/** - * Test Suite. It lists all the test functions. - */ -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("BasicEncodeDecode", TLVPacketBufferBackingStoreTest::BasicEncodeDecode), - NL_TEST_DEF("MultiBufferEncode", TLVPacketBufferBackingStoreTest::MultiBufferEncode), - NL_TEST_DEF("NonChainedBufferCanReserve", TLVPacketBufferBackingStoreTest::NonChainedBufferCanReserve), - NL_TEST_DEF("TestWriterReserveUnreserveDoesNotOverflow", TLVPacketBufferBackingStoreTest::TestWriterReserveUnreserveDoesNotOverflow), - NL_TEST_DEF("TestWriterReserve", TLVPacketBufferBackingStoreTest::TestWriterReserve), - - NL_TEST_SENTINEL() -}; -// clang-format on - -} // anonymous namespace - -int TestTLVPacketBufferBackingStore() -{ - // clang-format off - nlTestSuite theSuite = { - .name ="chip-tlv-packet-buffer-backing-store", - .tests = &sTests[0], - .setup = TLVPacketBufferBackingStoreTest::TestSetup, - .tear_down = TLVPacketBufferBackingStoreTest::TestTeardown, - }; - // clang-format on - - // Run test suite. - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestTLVPacketBufferBackingStore) diff --git a/src/system/tests/TestTimeSource.cpp b/src/system/tests/TestTimeSource.cpp index daee4cfb974f8b..e6b8251f0ee63f 100644 --- a/src/system/tests/TestTimeSource.cpp +++ b/src/system/tests/TestTimeSource.cpp @@ -21,29 +21,26 @@ * the ability to compile and use the test implementation of the time source. */ -#include +#include #include #include -#include -#include +#include #include -namespace { - -void TestTimeSourceSetAndGet(nlTestSuite * inSuite, void * inContext) +TEST(TestTimeSource, TestTimeSourceSetAndGet) { chip::Time::TimeSource source; - NL_TEST_ASSERT(inSuite, source.GetMonotonicTimestamp() == chip::System::Clock::kZero); + EXPECT_EQ(source.GetMonotonicTimestamp(), chip::System::Clock::kZero); constexpr chip::System::Clock::Milliseconds64 k1234 = chip::System::Clock::Milliseconds64(1234); source.SetMonotonicTimestamp(k1234); - NL_TEST_ASSERT(inSuite, source.GetMonotonicTimestamp() == k1234); + EXPECT_EQ(source.GetMonotonicTimestamp(), k1234); } -void SystemTimeSourceGet(nlTestSuite * inSuite, void * inContext) +TEST(TestTimeSource, SystemTimeSourceGet) { chip::Time::TimeSource source; @@ -55,35 +52,7 @@ void SystemTimeSourceGet(nlTestSuite * inSuite, void * inContext) for (int i = 0; i < 100; i++) { chip::System::Clock::Timestamp newValue = source.GetMonotonicTimestamp(); - NL_TEST_ASSERT(inSuite, newValue >= oldValue); + EXPECT_GE(newValue, oldValue); oldValue = newValue; } } - -} // namespace - -/** - * Test Suite. It lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("TimeSource::SetAndGet", TestTimeSourceSetAndGet), - NL_TEST_DEF("TimeSource::SetAndGet", SystemTimeSourceGet), - NL_TEST_SENTINEL() -}; -// clang-format on - -int TestTimeSource() -{ - nlTestSuite theSuite = { - "chip-timesource", &sTests[0], nullptr /* setup */, nullptr /* teardown */ - }; - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr /* context */); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestTimeSource) diff --git a/src/test_driver/openiotsdk/unit-tests/test_components.txt b/src/test_driver/openiotsdk/unit-tests/test_components.txt index 4f14e9dd8434bb..e112a8b2ed5d50 100644 --- a/src/test_driver/openiotsdk/unit-tests/test_components.txt +++ b/src/test_driver/openiotsdk/unit-tests/test_components.txt @@ -1 +1,10 @@ accesstest +ASN1Tests +MinimalMdnsCoreTests +MinimalMdnsRecordsTests +MinimalMdnsRespondersTests +CoreTests +PlatformTests +SystemLayerTests +TestShell +SetupPayloadTests \ No newline at end of file diff --git a/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt b/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt index 4734fb8efa3dfd..13a59af526f4dd 100644 --- a/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt +++ b/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt @@ -1,23 +1,15 @@ AppTests -ASN1Tests BDXTests ChipCryptoTests -CoreTests CredentialsTest DataModelTests InetLayerTests MdnsTests MessagingLayerTests -MinimalMdnsCoreTests -MinimalMdnsRecordsTests -MinimalMdnsRespondersTests -PlatformTests RawTransportTests RetransmitTests SecureChannelTests -SetupPayloadTests +SetupPayloadTestsNL SupportTests -SystemLayerTests -TestShell TransportLayerTests UserDirectedCommissioningTests diff --git a/src/tools/interop/idt/.gitignore b/src/tools/interop/idt/.gitignore deleted file mode 100644 index 55da2a806dd412..00000000000000 --- a/src/tools/interop/idt/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -*~ -.DS_Store -.idea/ -IDT_ARTIFACTS/ -OUT/ -__pycache__/ -pycache/ -venv/ -.zip -BUILD diff --git a/src/tools/interop/idt/Dockerfile b/src/tools/interop/idt/Dockerfile deleted file mode 100644 index 29036c36bbabcf..00000000000000 --- a/src/tools/interop/idt/Dockerfile +++ /dev/null @@ -1,54 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -FROM debian:bookworm -RUN apt-get update && \ - apt-get install -y \ - adb \ - aircrack-ng \ - apt-utils \ - bison \ - byacc \ - dnsutils \ - flex \ - gcc-aarch64-linux-gnu \ - gcc-arm-linux-gnueabi \ - git \ - glib-2.0 \ - kmod \ - libbluetooth-dev \ - libboost-python-dev \ - libboost-thread-dev \ - libglib2.0-dev \ - net-tools \ - pciutils \ - pkg-config \ - python3-pip \ - python3.11 \ - python3.11-venv \ - tcpdump \ - usbutils \ - wget && \ - echo "wireshark-common wireshark-common/install-setuid boolean true" | debconf-set-selections && \ - DEBIAN_FRONTEND=noninteractive apt-get -y install wireshark && \ - rm -rf /var/lib/apt/lists/* -RUN usermod -aG plugdev $(whoami) -RUN git clone https://github.com/openthread/ot-br-posix -COPY requirements.txt / -RUN /bin/bash -c "python3 -m venv /env && source /env/bin/activate && pip install -r requirements.txt" -RUN echo "source /env/bin/activate; pip -V; source /idt/scripts/alias.sh;" >> /root/.bashrc -ENTRYPOINT ["/bin/bash"] diff --git a/src/tools/interop/idt/README.md b/src/tools/interop/idt/README.md deleted file mode 100644 index acc0c252fdbe39..00000000000000 --- a/src/tools/interop/idt/README.md +++ /dev/null @@ -1,365 +0,0 @@ -# Interoperability Debugging Tool - -## Overview - -The “Interoperability Debugging Tool” (IDT) is a python-based tool that supports -a variety of commands that are useful in the context of interoperability testing -of Matter devices and app controllers. - -### Discovery - -While in discovery mode, the tool displays all Matter devices that are in -commission and/or operational mode. This is useful to have a clear understanding -of all Matter devices currently “active” in the testing environment. - -See section “4.3. Discovery” of the Matter spec for official documentation. - -When run interactively, discovery functions in one of two modes: BLE and DNS-SD. - -### Capture - -While in capture mode, the tool starts capturing all data of interest (e.g. -video recording of interactions with the mobile app, logs from all components -involved, network packets capture, etc.) while a test is being conducted -manually. It also provides feedback to the user on test setup and execution. - -When the test completes, capture mode is stopped and all captured data is zipped -in a file that can then be sent to all parties involved in investigating any -issue uncovered via the manual test. Each ecosystem may implement an analysis -that analyzes capture data, displays info to the user, probes the local -environment and generates additional artifacts. - -## Single host installation (no Raspberry Pi) - -All features of `idt` are available on macOS and Linux (tested with Debian based -systems). -If you would prefer to execute capture and discovery from a Raspberry Pi, read -the next section instead. - -The machine running `idt` should be connected to the same Wi-Fi network used for -testing. -Follow the steps below to execute capture and discovery without a Raspberry Pi: - -- From the parent directory of `idt`, run `source idt/scripts/alias.sh`. -- Optionally, run `source idt/scripts/setup_shell.sh` to install aliases - permanently. -- After `idt` aliases are available in your environment, calling any `idt` - command will automatically create a new virtual environment and install - python dependencies. - - If you're missing non-Python dependencies, you'll be prompted to install - them until they're available. -- Bluetooth discovery on macOS will require granting the program where `idt` - is run, e.g. terminal emulator or IDE permission to access bluetooth in - macOS settings. - - Failure to do so may result in any of the following: - - A single `abort` message and no further output in the terminal. - - Failure with a relevant stack trace in the terminal. - - A prompt to allow the application access to bluetooth. - -## Raspberry Pi installation - -### Environment overview - -The execution environment of IDT when using Raspberry Pi is shown in the figure -below. - -[TODO] add figure. - -The Raspberry Pi is where "discovery" and "capture" are executed. - -The "admin" computer is the machine used to connect to and control the RPi, and -to fetch artifacts which were created during capture from the RPi. - -This directory contains tools for use on both the admin computer and the RPi. - -### Environment details - -1. `idt` will be used on both the admin computer and the RPi. -1. `scripts` only points to one installation location at a time. It is ideal to - maintain a single `idt` directory on each (admin and RPi) system accordingly. -1. The expected install location on the RPi is the home directory of the user - specified in `idt/scripts/vars.sh`, which will be generated by running a - script in the next section. -1. Helper scripts may be used on admin computers that support `zsh` and `bash` - (Linux and macOS). -1. Windows may be used as the admin computer via tools like `PowerShell`, - `MobaXterm` and `FileZilla`. -1. This setup is intended to work with the admin computer and RPi connected to - the same Wi-Fi network, which is also the Wi-Fi network used for testing. -1. Corporate networks are not expected to be used as test networks. - -### Prepare the RPi - -1. A >= 128 GB SD card is recommended. -1. Flash the RPi SD with the debian based distribution of your choice. -1. Plug the SD into the RPi. -1. Ensure the RPi is connected to your network, either via ethernet or with - Wi-Fi configured in the disk image. -1. Boot the RPi. - -### Configure admin computer and push to the RPi - -#### Linux and macOS admin computers - -1. On your admin computer, source the `alias` script from the parent directory - of `idt` to get `idt` commands in your current shell. - ``` - source idt/scripts/alias.sh - ``` - - To avoid having to repeat this step for each session, optionally configure - automatic aliases permanently. - - **_NOTE:_** Once run, `idt` commands will be globally and automatically - available. If you need to remove the installation, edit the `.rc` files - mentioned in `setup_shell`. - ``` - source idt/scripts/setup_shell.sh - ``` -1. Run `idt_create_vars` and follow the prompts to set IDs for the target RPi. -1. Send `idt` to the RPi: - ``` - idt_push - ``` -1. `ssh` to the RPi: - - **_NOTE:_** You may need to wait a few minutes after boot for the `ssh` - server to be available on the RPi. Retry if needed! - ``` - idt_connect - ``` - -#### Windows admin computers - -1. Open `PowerShell`, cd to the directory containing `idt` and send `idt` to the - RPi: - ``` - scp -r ./idt/* $PIUSER@$PIHOST:/home/$PIUSER/idt - ``` -1. `ssh` to the RPi, e.g. with `MobaXterm` - - **_NOTE:_** You may need to wait a few minutes after boot for the `ssh` - server to be available on the RPi. Retry if needed! - - Use `$PIUSER@$PIHOST` or `$PIUSER@$ip` where `$ip` is the RPi's IP found - in your router admin panel. - -### Configure the RPi - -1. Configure passwords or ssh keys. -1. Configure Wi-Fi networks if needed. -1. Set up `idt`: - ``` - cd ~ # Go to idt parent dir - source idt/scripts/setup_shell.sh # Setup atuo aliases - source idt/scripts/alias.sh # Get aliases now - idt_bootstrap # Initial configuration - idt_build # Build the container image - ``` - -### Install updates - -SCP may not overwrite all files. To clear the `idt` dir off of the RPi safely -between pushes, exit the container and: - -``` -idt_clean -``` - -NOTE the idt artifacts directory is contained in idt, so running this will -delete any artifacts. - -Then from the admin computer: - -``` -idt_push -``` - -## User guide - -> **_IMPORTANT_** -> `idt_` commands are shell aliases helpful for administrative commands. -> `idt` invokes the `idt` python package. -> Output from `idt` will generally be colorized while output from sub processes -> is generally not. - -RPi users, as needed: - -- For users with Windows admin computers, reconnect e.g., using `MobaXterm` -- Other users reconnect `ssh` to the RPi (from your admin computer): - ``` - idt_connect - ``` -- Run the `idt` container (from the RPi): - ``` - idt_activate - ``` - -### Capture - -> **_IMPORTANT_** -> Ensure you've made it to the log line "Starting real time analysis, press -> enter to stop!" before launching the app under test. - -``` -idt capture -h - -usage: idt capture [-h] [--platform {Android}] [--ecosystem {PlayServicesUser,PlayServices,ALL}] [--pcap {t,f}] [--interface {wlp0s20f3,lo,docker0,any}] - -options: - -h, --help show this help message and exit - --platform {Android}, -p {Android} - Run capture for a particular platform (default Android) - --ecosystem {PlayServicesUser,PlayServices,ALL}, -e {PlayServicesUser,PlayServices,ALL} - Run capture for a particular ecosystem or ALL ecosystems (default ALL) - --pcap {t,f}, -c {t,f} - Run packet capture (default t) - --interface {wlp0s20f3,lo,docker0,any}, -i {wlp0s20f3,lo,docker0,any} - Specify packet capture interface (default any) -``` - -For packet capture interface (`-i`/`--interface`: - -- On macOS, the only available interface is `any`. -- On Linux, `idt` checks available interfaces from `/sys/class/net/` as well - as allowing `any`. - -#### Artifacts - -Each ecosystem and platform involved in the capture will have their own -subdirectory in the root artifact dir. - -### Discovery - -``` -idt discover -h - -usage: idt discover [-h] --type {ble,b,dnssd,d} - -options: - -h, --help show this help message and exit - --type {ble,b,dnssd,d}, -t {ble,b,dnssd,d} - Specify the type of discovery to execute -``` - -#### BLE - -``` -idt discover -t b -``` - -#### mDNS - -``` -idt discover -t d -``` - -#### Artifacts - -There is a per device log in `ble` and `dnssd` subdirectory of the root artifact -dir. - -### Probe - -``` -usage: idt probe [-h] - -options: - -h, --help show this help message and exit -``` - -Collect contextually relevant networking info from the local environment and -provide artifacts. - -## Troubleshooting - -- Wireless `adb` may fail to connect indefinitely depending on network - configuration. Use a wired connection if wireless fails repeatedly. -- Change log level from `INFO` to `DEBUG` in root `config.py` for additional - logging. -- Compiling `tcpdump` for android may require additional dependencies. - - If the build script fails for you, try - `idt_go && source idt/scripts/compilers.sh`. -- You may disable colors and splash by setting `enable_color` in `config.py` - to `False`. -- `idt_clean_child` will kill any stray `tcpdump` and `adb` commands. - - `idt_check_child` will look for leftover processes. - - Not expected to be needed outside of development scenarios. - -## Project overview - -- The entry point is in `idt.py` which contains simple CLI parsing with - `argparse`. - -### `capture` - -- `base` contains the base classes for ecosystems and platforms. -- `controller` contains the ecosystem and platform producer and controller -- `loader` is a generic class loader that dynamically imports classes matching - a given super class from a given directory. -- `/platform` and `/ecosystem` contain one package for each platform and - ecosystem, which should each contain one implementation of the respective - base class. - -### `discovery` - -- `matter_ble` provides a simple ble scanner that shows matter devices being - discovered and lost, as well as their VID/PID, RSSI, etc. -- `matter_dnssd` provides a simple DNS-SD browser that searches for matter - devices and thread border routers. - -### `probe` - -- `probe` contains the base class for (`idt`'s) host platform specific - implementation. - - Reuses the dnssd discovery implementation to build probe targets. - - Calls platform + addr type specific probe methods for each target. -- `linux` and `mac` contain `probe` implementations for each host platform. - -### `utils` - -- `log` contains logging utilities used by everything in the project. -- `artifact` contains helper functions for managing artifacts. -- `shell` contains a simple helper class for background and foreground Bash - commands. -- `host_platform` contains helper functions for the interacting with the host - running `idt`. - -### Conventions - -- `config.py` should be used to hold development configs within the directory - where they are needed. - - It may also hold configs for flaky/cumbersome features that might need - to be disabled in an emergency. - - `config.py` **should not** be used for everyday operation. -- When needed, execute builds in a folder called `BUILD` within the source - tree. - - `idt_clean_all` deletes all `BUILD` dirs and `BUILD` is in `.gitignore`. - -## Extending functionality - -### Capture - -Ecosystem and Platform implementations are dynamically loaded. - -For each package in `capture/ecosystem`, the ecosystem loader expects a module -name matching the package name. -This module must contain a single class which is a subclass of -`capture.base.EcosystemCapture`. - -`/capture/ecosystem/play_services_user` contains a minimal example -implementation. - -As another example, link `/res/plugin_demo/ecosystem/demo_ext_ecosystem`. - -``` -$ idt_go && ln -s $PWD/idt/res/plugin_demo/ecosystem/demo_ext_ecosystem/ idt/capture/ecosystem -$ idt capture -h -usage: idt capture [-h] [--platform {Android}] [--ecosystem {DemoExtEcosystem... -``` - -> **IMPORTANT:** Note the following runtime expectations of ecosystems: -> `analyze_capture()` must not block the async event loop excessively and must -> not interact with standard in - -The platform loader functions the same as `capture/ecosystem`. - -For each package in `capture/platform`, the platform loader expects a module -name matching the package name. -This module must contain a single class which is a subclass of -`capture.base.PlatformLogStreamer`. diff --git a/src/tools/interop/idt/__main__.py b/src/tools/interop/idt/__main__.py deleted file mode 100644 index b927d050b9a0a2..00000000000000 --- a/src/tools/interop/idt/__main__.py +++ /dev/null @@ -1,23 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from idt import InteropDebuggingTool -from utils.host_platform import verify_py_version - -if __name__ == "__main__": - verify_py_version() - InteropDebuggingTool() diff --git a/src/tools/interop/idt/capture/__init__.py b/src/tools/interop/idt/capture/__init__.py deleted file mode 100644 index 18069e71ad7838..00000000000000 --- a/src/tools/interop/idt/capture/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from capture import ecosystem, platform - -from .controller import EcosystemCapture, PlatformLogStreamer -from .pcap import PacketCaptureRunner - -__all__ = [ - 'ecosystem', - 'platform', - 'controller', - 'EcosystemCapture', - 'PacketCaptureRunner', - 'PlatformLogStreamer', -] diff --git a/src/tools/interop/idt/capture/base.py b/src/tools/interop/idt/capture/base.py deleted file mode 100644 index b90571020a071f..00000000000000 --- a/src/tools/interop/idt/capture/base.py +++ /dev/null @@ -1,114 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from abc import ABC, abstractmethod - - -class PlatformLogStreamer(ABC): - """ - The abstract base class for a platform transport, subclassed by sub packages of platform - """ - - @abstractmethod - def __init__(self, artifact_dir: str) -> None: - """ - artifact_dir: the fully qualified path of the output directory. This directory already exists - """ - raise NotImplementedError - - @abstractmethod - async def connect(self) -> None: - """ - Establish connections to log targets for this platform - """ - raise NotImplementedError - - @abstractmethod - async def start_streaming(self) -> None: - """ - Begin streaming logs - """ - raise NotImplementedError - - @abstractmethod - async def run_observers(self) -> None: - """ - Observe log procs and restart as needed - Must be async aware and not interact with stdin - """ - raise NotImplementedError - - @abstractmethod - async def stop_streaming(self) -> None: - """ - Stop the capture and pull any artifacts from remote devices - Write artifacts to artifact_dir passed on instantiation - """ - raise NotImplementedError - - -class UnsupportedCapturePlatformException(Exception): - """EcosystemCapture should raise this for unsupported platform""" - - def __init__(self, message: str): - super().__init__(message) - - -class EcosystemCapture(ABC): - - @abstractmethod - def __init__( - self, - platform: PlatformLogStreamer, - artifact_dir: str) -> None: - """ - platform: the instance of the log streamer for the selected platform - artifact_dir: the fully qualified path of the output directory. This directory already exists. - """ - raise NotImplementedError - - @abstractmethod - async def start_capture(self) -> None: - """ - Start the capture - Platform is already started - """ - raise NotImplementedError - - @abstractmethod - async def stop_capture(self) -> None: - """ - Stop the capture and pull any artifacts from remote devices - Write artifacts to artifact_dir passed on instantiation - Platform is already stopped - """ - raise NotImplementedError - - @abstractmethod - async def analyze_capture(self) -> None: - """ - Parse the capture and create + display helpful analysis artifacts that are unique to the ecosystem - Must be async aware and not interact with stdin - """ - raise NotImplementedError - - @abstractmethod - async def probe_capture(self) -> None: - """ - Probe the local environment, e.g. ping relevant remote services and write respective artifacts - """ - raise NotImplementedError diff --git a/src/tools/interop/idt/capture/config.py b/src/tools/interop/idt/capture/config.py deleted file mode 100644 index 12ce985eb4b3e4..00000000000000 --- a/src/tools/interop/idt/capture/config.py +++ /dev/null @@ -1,50 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -""" -The timeout time used by Orchestrator in capture/controller - -Used when calling: -- Platform.connect() - if timeout, then halt -- Ecosystem.start(), .stop(), .probe() - if timeout, then continue execution and log error - -This is an async timeout, so dependent on event loop being released to work. -To illustrate, consider this example where no timeout is thrown despite the awaited task running for twice the timeout: ----- -sleep_time = 2 - -async def not_actually_async(): - time.sleep(sleep_time * 2) # Blocking the EL! - -async def try_timeout(): - async with asyncio.timeout(sleep_time): - await not_actually_async() - print("Timeout was NOT thrown!") - -asyncio.run(try_timeout()) ----- -Result: Timeout was NOT thrown! - -Update the example ----- -async def not_actually_async(): # Now it is_actually_async because we - await asyncio.sleep(sleep_time * 2) # change to something that isn't blocking the EL ----- -Result: The timeout error will be raised. - -""" -orchestrator_async_step_timeout_seconds = 240 diff --git a/src/tools/interop/idt/capture/controller.py b/src/tools/interop/idt/capture/controller.py deleted file mode 100644 index 624a6f292451d3..00000000000000 --- a/src/tools/interop/idt/capture/controller.py +++ /dev/null @@ -1,183 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import asyncio -import copy -import os -import sys -import traceback -import typing -from dataclasses import dataclass - -import capture -from capture.base import EcosystemCapture, PlatformLogStreamer, UnsupportedCapturePlatformException -from utils.artifact import create_standard_log_name, log, safe_mkdir -from utils.log import add_border, border_print - -from . import config - - -@dataclass(repr=True) -class ErrorRecord: - ecosystem: str - help_message: str - stack_trace: str - - -_PLATFORM_MAP: typing.Dict[str, PlatformLogStreamer] = {} -_ECOSYSTEM_MAP: typing.Dict[str, PlatformLogStreamer] = {} -_ERROR_REPORT: typing.Dict[str, ErrorRecord] = {} - -logger = log.get_logger(__file__) - - -def track_error(ecosystem: str, help_message: str) -> None: - if ecosystem not in _ERROR_REPORT: - _ERROR_REPORT[ecosystem] = [] - record = ErrorRecord(ecosystem, help_message, traceback.format_exc()) - logger.error(record) - _ERROR_REPORT[ecosystem].append(record) - - -def list_available_platforms() -> typing.List[str]: - return copy.deepcopy(capture.platform.__all__) - - -async def get_platform_impl( - platform: str, - artifact_dir: str) -> PlatformLogStreamer: - if platform in _PLATFORM_MAP: - return _PLATFORM_MAP[platform] - border_print(f"Initializing platform {platform}") - platform_class = getattr(capture.platform, platform) - platform_artifact_dir = os.path.join(artifact_dir, platform) - safe_mkdir(platform_artifact_dir) - platform_inst = platform_class(platform_artifact_dir) - _PLATFORM_MAP[platform] = platform_inst - async with asyncio.timeout(config.orchestrator_async_step_timeout_seconds): - await platform_inst.connect() - return platform_inst - - -def list_available_ecosystems() -> typing.List[str]: - return copy.deepcopy(capture.ecosystem.__all__) - - -async def get_ecosystem_impl( - ecosystem: str, - platform: PlatformLogStreamer, - artifact_dir: str) -> EcosystemCapture: - if ecosystem in _ECOSYSTEM_MAP: - return _ECOSYSTEM_MAP[ecosystem] - ecosystem_class = getattr(capture.ecosystem, ecosystem) - ecosystem_artifact_dir = os.path.join(artifact_dir, ecosystem) - safe_mkdir(ecosystem_artifact_dir) - ecosystem_instance = ecosystem_class(platform, ecosystem_artifact_dir) - _ECOSYSTEM_MAP[ecosystem] = ecosystem_instance - return ecosystem_instance - - -async def init_ecosystems(platform, ecosystem, artifact_dir): - platform = await get_platform_impl(platform, artifact_dir) - ecosystems_to_load = list_available_ecosystems() \ - if ecosystem == 'ALL' \ - else [ecosystem] - for ecosystem in ecosystems_to_load: - try: - await get_ecosystem_impl( - ecosystem, platform, artifact_dir) - except UnsupportedCapturePlatformException: - help_message = f"Unsupported platform {ecosystem} {platform}" - logger.error(help_message) - track_error(ecosystem, help_message) - except Exception: - help_message = f"Unknown error instantiating ecosystem {ecosystem} {platform}" - logger.error(help_message) - track_error(ecosystem, help_message) - - -async def handle_capture(attr): - attr = f"{attr}_capture" - for ecosystem in _ECOSYSTEM_MAP: - try: - border_print(f"{attr} for {ecosystem}") - async with asyncio.timeout(config.orchestrator_async_step_timeout_seconds): - await getattr(_ECOSYSTEM_MAP[ecosystem], attr)() - except TimeoutError: - help_message = f"Timeout after {config.orchestrator_async_step_timeout_seconds} seconds {attr} {ecosystem}" - logger.error(help_message) - track_error(ecosystem, help_message) - except Exception: - help_message = f"Unexpected error {attr} {ecosystem}" - logger.error(help_message) - track_error(ecosystem, help_message) - - -async def start(): - for platform_name, platform, in _PLATFORM_MAP.items(): - # TODO: Write error log if halt here - border_print(f"Starting streaming for platform {platform_name}") - await platform.start_streaming() - await handle_capture("start") - - -async def stop(): - for platform_name, platform, in _PLATFORM_MAP.items(): - # TODO: Write error log if halt here - border_print(f"Stopping streaming for platform {platform_name}") - await platform.stop_streaming() - await handle_capture("stop") - - -async def run_analyzers(): - border_print("Starting real time analysis, press enter to stop!", important=True) - analysis_tasks = [] - monitor_tasks = [] - for platform_name, platform in _PLATFORM_MAP.items(): - logger.info(f"Creating monitor task for {platform_name}") - monitor_tasks.append(asyncio.create_task(platform.run_observers())) - for ecosystem_name, ecosystem in _ECOSYSTEM_MAP.items(): - logger.info(f"Creating analysis task for {ecosystem_name}") - analysis_tasks.append(asyncio.create_task(ecosystem.analyze_capture())) - logger.info("Done creating analysis tasks") - await asyncio.get_event_loop().run_in_executor( - None, sys.stdin.readline) - border_print("Cancelling monitor tasks") - for task in monitor_tasks: - task.cancel() - logger.info("Done cancelling monitor tasks") - border_print("Cancelling analysis tasks") - for task in analysis_tasks: - task.cancel() - logger.info("Done cancelling analysis tasks") - - -async def probe(): - await handle_capture("probe") - - -def write_error_report(artifact_dir: str): - if _ERROR_REPORT: - logger.critical("DETECTED ERRORS THIS RUN!") - error_report_file_name = create_standard_log_name("error_report", "txt", parent=artifact_dir) - with open(error_report_file_name, "a+") as error_report_file: - for ecosystem in _ERROR_REPORT: - log.print_and_write(add_border(f"Errors for {ecosystem}"), error_report_file) - for record in _ERROR_REPORT[ecosystem]: - log.print_and_write(str(record), error_report_file) - else: - logger.info("No errors seen this run!") diff --git a/src/tools/interop/idt/capture/ecosystem/__init__.py b/src/tools/interop/idt/capture/ecosystem/__init__.py deleted file mode 100644 index 432af96d345a6b..00000000000000 --- a/src/tools/interop/idt/capture/ecosystem/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from capture.base import EcosystemCapture -from capture.loader import CaptureImplsLoader - -impl_loader = CaptureImplsLoader( - __path__[0], - "capture.ecosystem", - EcosystemCapture -) - -for impl_name, impl in impl_loader.impls.items(): - globals()[impl_name] = impl - -__all__ = impl_loader.impl_names diff --git a/src/tools/interop/idt/capture/ecosystem/play_services/__init__.py b/src/tools/interop/idt/capture/ecosystem/play_services/__init__.py deleted file mode 100644 index ea3a4669e12cfd..00000000000000 --- a/src/tools/interop/idt/capture/ecosystem/play_services/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .play_services import PlayServices - -__all__ = [ - 'PlayServices' -] diff --git a/src/tools/interop/idt/capture/ecosystem/play_services/command_map.py b/src/tools/interop/idt/capture/ecosystem/play_services/command_map.py deleted file mode 100644 index 4adf9b59bb5811..00000000000000 --- a/src/tools/interop/idt/capture/ecosystem/play_services/command_map.py +++ /dev/null @@ -1,39 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -getprop = { - 'ro.product.model': 'android_model', - 'ro.build.version.release': 'android_version', - 'ro.build.version.sdk': 'android_api', - 'ro.build.fingerprint': 'build_fingerprint', - 'ro.odm.build.fingerprint': 'odm_build_fingerprint', - 'ro.product.build.fingerprint': 'product_build_fingerprint', - 'ro.ecosystem.build.fingerprint': 'vendor_build_fingerprint', -} - -_ap = 'activity provider com.google.android.gms.chimera.container.GmsModuleProvider' -dumpsys = { - 'display_width': 'display | grep StableDisplayWidth | awk -F\'=\' \'{print $2}\'', - 'display_height': 'display | grep StableDisplayHeight | awk -F\'=\' \'{print $2}\'', - 'gha_info': ' package com.google.android.apps.chromecast.app | grep versionName', - 'container_info': 'package com.google.android.gms | grep "versionName"', - 'home_module_info': f'{_ap} | grep "com.google.android.gms.home" | grep -v graph', - 'optional_home_module_info': f'{_ap} | grep "com.google.android.gms.optional_home" | grep -v graph', - 'policy_home_module_info': f'{_ap} | grep "com.google.android.gms.policy_home" | grep -v graph', - 'thread_info': f'{_ap} | grep "com.google.android.gms.threadnetwork"', - 'mdns_info': f'{_ap} | grep -i com.google.android.gms.mdns', -} diff --git a/src/tools/interop/idt/capture/ecosystem/play_services/config.py b/src/tools/interop/idt/capture/ecosystem/play_services/config.py deleted file mode 100644 index 2daacb38dcf909..00000000000000 --- a/src/tools/interop/idt/capture/ecosystem/play_services/config.py +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -enable_foyer_probers = True -foyer_prober_traceroute_limit = 32 diff --git a/src/tools/interop/idt/capture/ecosystem/play_services/play_services.py b/src/tools/interop/idt/capture/ecosystem/play_services/play_services.py deleted file mode 100644 index e94a10f9260b94..00000000000000 --- a/src/tools/interop/idt/capture/ecosystem/play_services/play_services.py +++ /dev/null @@ -1,117 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import asyncio -import json -import os -from typing import IO, Dict - -from capture.base import EcosystemCapture, UnsupportedCapturePlatformException -from capture.platform.android import Android -from capture.platform.android.streams.logcat import LogcatStreamer -from utils.artifact import create_standard_log_name, log - -from . import config -from .command_map import dumpsys, getprop -from .play_services_analysis import PlayServicesAnalysis -from .prober import PlayServicesProber - -logger = log.get_logger(__file__) - - -class PlayServices(EcosystemCapture): - """ - Implementation of capture and analysis for Play Services - """ - - def __init__(self, platform: Android, artifact_dir: str) -> None: - self.artifact_dir = artifact_dir - - if not isinstance(platform, Android): - raise UnsupportedCapturePlatformException( - 'only platform=android is supported for ecosystem=play_services') - self.platform = platform - - self.standard_info_file_path = os.path.join( - self.artifact_dir, create_standard_log_name( - 'phone_info', 'json')) - self.standard_info_data: Dict[str, str] = {} - - self.analysis = PlayServicesAnalysis(self.platform, self.artifact_dir) - - self.service_ids = ['336', # Home - '305', # Thread - '168', # mDNS - ] - self.logcat_stream: LogcatStreamer = self.platform.streams["LogcatStreamer"] - self.logcat_file: IO = None - - def _write_standard_info_file(self) -> None: - for k, v in self.standard_info_data.items(): - logger.info(f"{k}: {v}") - standard_info_data_json = json.dumps(self.standard_info_data, indent=2) - with open(self.standard_info_file_path, mode='w+') as standard_info_file: - standard_info_file.write(standard_info_data_json) - - def _parse_get_prop(self) -> None: - get_prop = self.platform.run_adb_command( - "shell getprop", - capture_output=True).get_captured_output() - for output in get_prop.split("\n"): - for prop in getprop: - if prop in output: - self.standard_info_data[prop] = output[output.rindex("["):] - - def _parse_dumpsys(self) -> None: - for attr_name, command in dumpsys.items(): - command = f"shell dumpsys {command}" - command_output = self.platform.run_adb_command( - command, - capture_output=True).get_captured_output() - self.standard_info_data[attr_name] = command_output - - def _get_standard_info(self) -> None: - self._parse_get_prop() - self._parse_dumpsys() - self._write_standard_info_file() - - async def start_capture(self) -> None: - for service_id in self.service_ids: - verbose_command = f"shell setprop log.tag.gms_svc_id:{service_id} VERBOSE" - self.platform.run_adb_command(verbose_command) - self._get_standard_info() - - async def analyze_capture(self): - try: - self.logcat_file = open(self.logcat_stream.logcat_artifact, "r") - while True: - self.analysis.do_analysis(self.logcat_file.readlines()) - # Releasing async event loop for other analysis / monitor topics - await asyncio.sleep(0.5) - except asyncio.CancelledError: - logger.info("Closing logcat stream") - if self.logcat_file: - self.logcat_file.close() - - async def stop_capture(self) -> None: - self.analysis.show_analysis() - - async def probe_capture(self) -> None: - if config.enable_foyer_probers: - await PlayServicesProber(self.platform, self.artifact_dir).probe_services() - else: - logger.critical("Foyer probers disabled in config!") diff --git a/src/tools/interop/idt/capture/ecosystem/play_services/play_services_analysis.py b/src/tools/interop/idt/capture/ecosystem/play_services/play_services_analysis.py deleted file mode 100644 index e6ebb8f13075d8..00000000000000 --- a/src/tools/interop/idt/capture/ecosystem/play_services/play_services_analysis.py +++ /dev/null @@ -1,102 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import os - -from capture.platform.android import Android -from utils.artifact import create_standard_log_name, log -from utils.log import add_border, print_and_write - -logger = log.get_logger(__file__) - - -class PlayServicesAnalysis: - - def __init__(self, platform: Android, artifact_dir: str) -> None: - self.logger = logger - self.artifact_dir = artifact_dir - self.analysis_file_name = os.path.join( - self.artifact_dir, create_standard_log_name( - 'commissioning_logcat', 'txt')) - - self.platform = platform - - self.matter_commissioner_logs = '' - self.failure_stack_trace = '' - self.pake_logs = '' - self.resolver_logs = '' - self.sigma_logs = '' - self.fail_trace_line_counter = -1 - - def _log_proc_matter_commissioner(self, line: str) -> None: - """Core commissioning flow""" - if 'MatterCommissioner' in line: - self.logger.info(line) - self.matter_commissioner_logs += line - - def _log_proc_commissioning_failed(self, line: str) -> None: - parsed_stack_trace_max_depth = 15 - if self.fail_trace_line_counter > parsed_stack_trace_max_depth: - self.fail_trace_line_counter = -1 - if self.fail_trace_line_counter > -1 and 'SetupDevice' in line: - self.failure_stack_trace += line - self.fail_trace_line_counter += 1 - if 'SetupDeviceView' and 'Commissioning failed' in line: - self.logger.info(line) - self.fail_trace_line_counter = 0 - self.failure_stack_trace += line - - def _log_proc_pake(self, line: str) -> None: - """Three logs for pake 1-3 expected""" - if "Pake" in line and "chip_logging" in line: - self.logger.info(line) - self.pake_logs += line - - def _log_proc_mdns(self, line: str) -> None: - if "_matter" in line and "ServiceResolverAdapter" in line: - self.logger.info(line) - self.resolver_logs += line - - def _log_proc_sigma(self, line: str) -> None: - """Three logs expected for sigma 1-3""" - if "Sigma" in line and "chip_logging" in line: - self.logger.info(line) - self.sigma_logs += line - - def show_analysis(self) -> None: - analysis_file = open(self.analysis_file_name, mode="w+") - print_and_write(add_border('Matter commissioner logs'), analysis_file) - print_and_write(self.matter_commissioner_logs, analysis_file) - print_and_write( - add_border('Commissioning failure stack trace'), - analysis_file) - print_and_write(self.failure_stack_trace, analysis_file) - print_and_write(add_border('PASE Handshake'), analysis_file) - print_and_write(self.pake_logs, analysis_file) - print_and_write(add_border('DNS-SD resolution'), analysis_file) - print_and_write(self.resolver_logs, analysis_file) - print_and_write(add_border('CASE handshake'), analysis_file) - print_and_write(self.sigma_logs, analysis_file) - analysis_file.close() - - def process_line(self, line: str) -> None: - for line_func in [s for s in dir(self) if s.startswith('_log')]: - getattr(self, line_func)(line) - - def do_analysis(self, batch: [str]) -> None: - for line in batch: - self.process_line(line) diff --git a/src/tools/interop/idt/capture/ecosystem/play_services/prober.py b/src/tools/interop/idt/capture/ecosystem/play_services/prober.py deleted file mode 100644 index 8dcda80ddf3133..00000000000000 --- a/src/tools/interop/idt/capture/ecosystem/play_services/prober.py +++ /dev/null @@ -1,71 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import os - -from utils.shell import Bash, log - -from . import config - -logger = log.get_logger(__file__) - - -class PlayServicesProber: - - def __init__(self, platform, artifact_dir): - # TODO: Handle all resolved addresses - self.platform = platform - self.artifact_dir = artifact_dir - self.logger = logger - self.probe_artifact = os.path.join(self.artifact_dir, "net_probes.txt") - self.command_suffix = f" 2>&1 | tee -a {self.probe_artifact}" - self.target = "googlehomefoyer-pa.googleapis.com" - self.tracert_limit = config.foyer_prober_traceroute_limit - - def run_command(self, command): - Bash(f"{command} {self.command_suffix}", sync=True).start_command() - - async def _probe_tracert_icmp_foyer(self) -> None: - self.logger.info(f"icmp traceroute to {self.target}") - self.run_command(f"traceroute -m {self.tracert_limit} {self.target}") - - async def _probe_tracert_udp_foyer(self) -> None: - # TODO: Per-host-platform impl - self.logger.info(f"udp traceroute to {self.target}") - self.run_command(f"traceroute -m {self.tracert_limit} -U -p 443 {self.target}") - - async def _probe_tracert_tcp_foyer(self) -> None: - # TODO: Per-host-platform impl - self.logger.info(f"tcp traceroute to {self.target}") - self.run_command(f"traceroute -m {self.tracert_limit} -T -p 443 {self.target}") - - async def _probe_ping_foyer(self) -> None: - self.logger.info(f"ping {self.target}") - self.run_command(f"ping -c 4 {self.target}") - - async def _probe_dns_foyer(self) -> None: - self.logger.info(f"dig {self.target}") - self.run_command(f"dig {self.target}") - - async def _probe_from_phone_ping_foyer(self) -> None: - self.logger.info(f"ping {self.target} from phone") - self.platform.run_adb_command(f"shell ping -c 4 {self.target} {self.command_suffix}") - - async def probe_services(self) -> None: - self.logger.info(f"Probing {self.target}") - for probe_func in [s for s in dir(self) if s.startswith('_probe')]: - await getattr(self, probe_func)() diff --git a/src/tools/interop/idt/capture/ecosystem/play_services_user/__init__.py b/src/tools/interop/idt/capture/ecosystem/play_services_user/__init__.py deleted file mode 100644 index ea02f9df6b375f..00000000000000 --- a/src/tools/interop/idt/capture/ecosystem/play_services_user/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .play_services_user import PlayServicesUser - -__all__ = [ - 'PlayServicesUser' -] diff --git a/src/tools/interop/idt/capture/ecosystem/play_services_user/play_services_user.py b/src/tools/interop/idt/capture/ecosystem/play_services_user/play_services_user.py deleted file mode 100644 index 2fdac62b8bbdb7..00000000000000 --- a/src/tools/interop/idt/capture/ecosystem/play_services_user/play_services_user.py +++ /dev/null @@ -1,90 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import asyncio -import os - -from capture.base import EcosystemCapture, UnsupportedCapturePlatformException -from capture.platform.android.android import Android -from capture.platform.android.streams.logcat import LogcatStreamer -from utils.artifact import create_standard_log_name -from utils.log import get_logger, print_and_write - -logger = get_logger(__file__) - - -class PlayServicesUser(EcosystemCapture): - """ - Implementation of capture and analysis for Play Services 3P - """ - - def __init__(self, platform: Android, artifact_dir: str) -> None: - self.logger = logger - self.artifact_dir = artifact_dir - self.analysis_file = os.path.join( - self.artifact_dir, create_standard_log_name( - 'commissioning_boundaries', 'txt')) - - if not isinstance(platform, Android): - raise UnsupportedCapturePlatformException( - 'only platform=android is supported for ' - 'ecosystem=PlayServicesUser') - self.platform = platform - self.logcat_fd = None - self.output = "" - self.logcat_stream: LogcatStreamer = self.platform.streams["LogcatStreamer"] - - async def start_capture(self) -> None: - pass - - async def stop_capture(self) -> None: - self.show_analysis() - - def proc_line(self, line) -> None: - if "CommissioningServiceBin: Binding to service" in line: - s = f"3P commissioner initiated Play Services commissioning\n{line}" - logger.info(s) - self.output += f"{s}\n" - elif "CommissioningServiceBin: Sending commissioning request to bound service" in line: - s = f"Play Services commissioning complete; passing back to 3P\n{line}" - logger.info(s) - self.output += f"{s}\n" - elif "CommissioningServiceBin: Received commissioning complete from bound service" in line: - s = f"3P commissioning complete!\n{line}" - logger.info(s) - self.output += f"{s}\n" - - async def analyze_capture(self) -> None: - """"Show the start and end times of commissioning boundaries""" - try: - self.logcat_fd = open(self.logcat_stream.logcat_artifact, "r") - while True: - for line in self.logcat_fd.readlines(): - self.proc_line(line) - # Releasing async event loop for other analysis / monitor tasks - await asyncio.sleep(0.5) - except asyncio.CancelledError: - self.logger.info("Closing logcat stream") - if self.logcat_fd is not None: - self.logcat_fd.close() - - def show_analysis(self) -> None: - with open(self.analysis_file, "w") as analysis_file: - print_and_write(self.output, analysis_file) - - async def probe_capture(self) -> None: - pass diff --git a/src/tools/interop/idt/capture/loader.py b/src/tools/interop/idt/capture/loader.py deleted file mode 100644 index 8e02e9d492c2b5..00000000000000 --- a/src/tools/interop/idt/capture/loader.py +++ /dev/null @@ -1,104 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import importlib -import inspect -import os -import traceback -from typing import Any - -from utils import log - -logger = log.get_logger(__file__) - - -class CaptureImplsLoader: - - def __init__(self, root_dir: str, root_package: str, search_type: type): - self.logger = logger - self.root_dir = root_dir - self.root_package = root_package - self.search_type = search_type - self.impl_names = [] - self.impls = {} - self.fetch_impls() - - @staticmethod - def is_package(potential_package: str) -> bool: - init_path = os.path.join(potential_package, - "__init__.py") - return os.path.exists(init_path) - - def verify_coroutines(self, subclass) -> bool: - # ABC does not verify coroutines on subclass instantiation, it merely checks the presence of methods - for item in dir(self.search_type): - item_attr = getattr(self.search_type, item) - if inspect.iscoroutinefunction(item_attr): - if not hasattr(subclass, item): - self.logger.warning(f"Missing coroutine in {subclass}") - return False - if not inspect.iscoroutinefunction(getattr(subclass, item)): - self.logger.warning(f"Missing coroutine in {subclass}") - return False - for item in dir(subclass): - item_attr = getattr(subclass, item) - if inspect.iscoroutinefunction(item_attr) and hasattr(self.search_type, item): - if not inspect.iscoroutinefunction(getattr(self.search_type, item)): - self.logger.warning(f"Unexpected coroutine in {subclass}") - return False - return True - - def is_type_match(self, potential_class_match: Any) -> bool: - if inspect.isclass(potential_class_match): - self.logger.debug(f"Checking {self.search_type} match against {potential_class_match}") - if issubclass(potential_class_match, self.search_type): - self.logger.debug(f"Found type match search: {self.search_type} match: {potential_class_match}") - if self.verify_coroutines(potential_class_match): - return True - return False - - def load_module(self, to_load): - self.logger.debug(f"Loading module {to_load}") - saw_more_than_one_impl = False - saw_one_impl = False - found_class = None - for module_item in dir(to_load): - loaded_item = getattr(to_load, module_item) - if self.is_type_match(loaded_item): - found_class = module_item - found_impl = loaded_item - if not saw_one_impl: - saw_one_impl = True - else: - saw_more_than_one_impl = True - if saw_one_impl and not saw_more_than_one_impl: - self.impl_names.append(found_class) - self.impls[found_class] = found_impl - elif saw_more_than_one_impl: - self.logger.warning(f"more than one impl in {module_item}") - - def fetch_impls(self): - self.logger.debug(f"Searching for implementations in {self.root_dir}") - for item in os.listdir(self.root_dir): - dir_content = os.path.join(self.root_dir, item) - if self.is_package(dir_content): - self.logger.debug(f"Found package in {dir_content}") - try: - module = importlib.import_module("." + item, self.root_package) - self.load_module(module) - except ModuleNotFoundError: - self.logger.warning(f"No module matching package name for {item}\n{traceback.format_exc()}") diff --git a/src/tools/interop/idt/capture/pcap/__init__.py b/src/tools/interop/idt/capture/pcap/__init__.py deleted file mode 100644 index b536056a1c0add..00000000000000 --- a/src/tools/interop/idt/capture/pcap/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .pcap import PacketCaptureRunner - -__all__ = [ - 'PacketCaptureRunner' -] diff --git a/src/tools/interop/idt/capture/pcap/pcap.py b/src/tools/interop/idt/capture/pcap/pcap.py deleted file mode 100644 index 2cb2285908b066..00000000000000 --- a/src/tools/interop/idt/capture/pcap/pcap.py +++ /dev/null @@ -1,63 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import os -import time - -from utils.artifact import create_standard_log_name, log -from utils.shell import Bash - -logger = log.get_logger(__file__) - - -class PacketCaptureRunner: - - def __init__(self, artifact_dir: str, interface: str) -> None: - self.logger = logger - self.artifact_dir = artifact_dir - self.output_path = str( - os.path.join( - self.artifact_dir, - create_standard_log_name( - "pcap", - "pcap"))) - self.start_delay_seconds = 2 - self.interface = interface - self.pcap_command = f"tcpdump -i {self.interface} -n -w {self.output_path}" - self.pcap_proc = Bash(self.pcap_command) - - def start_pcap(self) -> None: - self.pcap_proc.start_command() - self.logger.info("Pausing to check if pcap started...") - time.sleep(self.start_delay_seconds) - if not self.pcap_proc.command_is_running(): - self.logger.error( - "Pcap did not start, you might need root; please authorize if prompted.") - Bash("sudo echo \"\"", sync=True).start_command() - self.logger.warning("Retrying pcap with sudo...") - self.pcap_command = f"sudo {self.pcap_command}" - self.pcap_proc = Bash(self.pcap_command) - self.pcap_proc.start_command() - time.sleep(self.start_delay_seconds) - if not self.pcap_proc.command_is_running(): - self.logger.error("Failed to start pcap!") - else: - self.logger.info(f"Pcap output path {self.output_path}") - - def stop_pcap(self) -> None: - self.logger.info("Stopping pcap proc") - self.pcap_proc.stop_command() diff --git a/src/tools/interop/idt/capture/platform/__init__.py b/src/tools/interop/idt/capture/platform/__init__.py deleted file mode 100644 index 92c1efcce79497..00000000000000 --- a/src/tools/interop/idt/capture/platform/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from capture.base import PlatformLogStreamer -from capture.loader import CaptureImplsLoader - -impl_loader = CaptureImplsLoader( - __path__[0], - "capture.platform", - PlatformLogStreamer -) - -for impl_name, impl in impl_loader.impls.items(): - globals()[impl_name] = impl - -__all__ = impl_loader.impl_names diff --git a/src/tools/interop/idt/capture/platform/android/__init__.py b/src/tools/interop/idt/capture/platform/android/__init__.py deleted file mode 100644 index 021ec15688c706..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .android import Android - -__all__ = [ - 'Android', -] diff --git a/src/tools/interop/idt/capture/platform/android/android.py b/src/tools/interop/idt/capture/platform/android/android.py deleted file mode 100644 index 4ca8b26baeda6b..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/android.py +++ /dev/null @@ -1,226 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import asyncio -import ipaddress -import os -import traceback -import typing -from asyncio import Task - -from capture.base import PlatformLogStreamer -from utils.shell import Bash, log - -from . import config, streams -from .capabilities import Capabilities - -logger = log.get_logger(__file__) - - -class Android(PlatformLogStreamer): - - def __init__(self, artifact_dir: str) -> None: - self.logger = logger - self.artifact_dir = artifact_dir - self.device_id: str | None = None - self.adb_devices: typing.Dict[str, bool] = {} - self.capabilities: None | Capabilities = None - self.streams = {} - self.connected = False - - def run_adb_command( - self, - command: str, - capture_output: bool = False, - cwd=None) -> Bash: - """ - Run an adb command synchronously - Capture_output must be true to call get_captured_output() later - """ - bash_command = Bash( - f'adb -s {self.device_id} {command}', - sync=True, - capture_output=capture_output, - cwd=cwd) - bash_command.start_command() - return bash_command - - def get_adb_background_command( - self, - command: str, - cwd=None) -> Bash: - return Bash(f'adb -s {self.device_id} {command}', cwd=cwd) - - def get_adb_devices(self) -> typing.Dict[str, bool]: - """Returns a dict of device ids and whether they are authorized""" - adb_devices = Bash('adb devices', sync=True, capture_output=True) - adb_devices.start_command() - adb_devices_output = adb_devices.get_captured_output().split('\n') - devices_auth = {} - header_done = False - for line in adb_devices_output: - if header_done: - line_parsed = line.split("\t") - device_id = line_parsed[0] - device_is_auth = line_parsed[1] == "device" - if line_parsed[1] == "offline": - disconnect_command = f"adb disconnect {device_id}" - self.logger.warning(f"Device {device_id} is offline, trying disconnect!") - Bash( - disconnect_command, - sync=True, - capture_output=False).start_command() - else: - devices_auth[device_id] = device_is_auth - header_done = True - self.adb_devices = devices_auth - return self.adb_devices - - def _only_one_device_connected(self) -> bool: - return len(self.adb_devices) == 1 - - def _get_first_connected_device(self) -> str: - return list(self.adb_devices.keys())[0] - - def _set_device_if_only_one_connected(self) -> None: - if self._only_one_device_connected(): - self.device_id = self._get_first_connected_device() - self.logger.warning(f'Only one device detected; using {self.device_id}') - - def _log_adb_devices(self) -> None: - for dev in self.adb_devices: - self.logger.info(dev) - - @staticmethod - def _is_connection_str(adb_input_str: str) -> bool: - valid_ipv4 = False - port_entered = False - valid_port = False - split_on_colon = adb_input_str.split(":") - try: - ipaddress.IPv4Network(split_on_colon[0]) - valid_ipv4 = True - except ValueError: - pass - if len(split_on_colon) > 1: - port_entered = True - try: - port = int(split_on_colon[1]) - valid_port = port < 65535 - except ValueError: - pass - valid_ip_no_port = valid_ipv4 and not port_entered - valid_ip_valid_port = valid_ipv4 and valid_port - return valid_ip_no_port or valid_ip_valid_port - - def _check_connect_wireless_adb(self, temp_device_id: str) -> None: - if Android._is_connection_str(temp_device_id): - connect_command = f"adb connect {temp_device_id}" - self.logger.warning( - f"Detected connection string; attempting to connect: {connect_command}") - Bash(connect_command, sync=True, capture_output=False).start_command() - self.get_adb_devices() - - def _device_id_user_input(self) -> None: - self.logger.error('Connect additional android devices via USB and press enter OR') - self.logger.error('Enter (copy paste) the target device id from the list of available devices below OR') - self.logger.error('Enter $IP4:$PORT to connect wireless debugging.') - self._log_adb_devices() - temp_device_id = input('').strip() - self._check_connect_wireless_adb(temp_device_id) - self.get_adb_devices() - if self._only_one_device_connected(): - self._set_device_if_only_one_connected() - elif temp_device_id not in self.adb_devices: - self.logger.warning('Entered device not in adb devices!') - else: - self.device_id = temp_device_id - - def _choose_device_id(self) -> None: - """ - Prompts the user to select a single device ID for this transport - If only one device is ever connected, use it. - """ - self._set_device_if_only_one_connected() - while self.device_id not in self.get_adb_devices(): - self._device_id_user_input() - self.logger.info(f'Selected device {self.device_id}') - - def _authorize_adb(self) -> None: - """ - Prompts the user until a single device is selected and adb is auth'd - """ - self.get_adb_devices() - self._choose_device_id() - while not self.get_adb_devices()[self.device_id]: - self.logger.info('Confirming authorization, press enter after auth') - input('') - self.logger.info(f'Target android device ID is authorized: {self.device_id}') - - async def connect(self) -> None: - if not self.connected: - self._authorize_adb() - self.capabilities = Capabilities(self) - self.capabilities.check_capabilities() - for stream in streams.__all__: - self.streams[stream] = getattr(streams, stream)(self) - self.connected = True - - async def handle_stream_action(self, action: str) -> None: - had_error = False - for stream_name, stream in self.streams.items(): - self.logger.info(f"Doing {action} for {stream_name}!") - try: - await getattr(stream, action)() - except Exception: - self.logger.error(traceback.format_exc()) - had_error = True - if had_error: - raise Exception("Propagating to controller!") - - async def start_streaming(self) -> None: - await self.handle_stream_action("start") - - async def run_observers(self) -> None: - try: - observer_tasks: [Task] = [] - for stream_name, stream in self.streams.items(): - observer_tasks.append(asyncio.create_task(stream.run_observer())) - while True: - self.logger.info("Android root observer task checking sub tasks") - for task in observer_tasks: - if task.done() or task.cancelled(): - self.logger.error(f"An android monitoring task has died, consider restarting! {task.__str__()}") - await asyncio.sleep(30) - except asyncio.CancelledError: - self.logger.info("Cancelling observer tasks") - for observer_tasks in observer_tasks: - observer_tasks.cancel() - - async def stop_streaming(self) -> None: - await self.handle_stream_action("stop") - if config.enable_bug_report: - found = False - for item in os.listdir(self.artifact_dir): - if "bugreport" in item and ".zip" in item: - found = True - if not found: - self.logger.info("Taking bugreport") - self.run_adb_command("bugreport", cwd=self.artifact_dir) - else: - self.logger.warning("bugreport already taken") - else: - self.logger.critical("bugreport disabled in settings!") diff --git a/src/tools/interop/idt/capture/platform/android/capabilities.py b/src/tools/interop/idt/capture/platform/android/capabilities.py deleted file mode 100644 index cd2f7f62797074..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/capabilities.py +++ /dev/null @@ -1,60 +0,0 @@ -from typing import TYPE_CHECKING - -from utils.artifact import create_standard_log_name, log -from utils.shell import Bash - -if TYPE_CHECKING: - from capture.platform.android import Android - -from . import config - -logger = log.get_logger(__file__) - - -class Capabilities: - - def __init__(self, platform: "Android"): - self.logger = logger - self.platform = platform - self.c_has_tcpdump = False - self.c_has_root = False - self.c_is_64 = False - self.c_hci_snoop_enabled = False - self.artifact = create_standard_log_name("capabilities", "txt", parent=platform.artifact_dir) - - def __repr__(self): - s = "Detected capabilities:\n" - for item in [x for x in dir(self) if x.startswith("c_")]: - s += f"{item}: {getattr(self, item)}\n" - return s - - def check_snoop_log(self) -> bool: - return config.hci_log_level in self.platform.run_adb_command("shell getprop persist.bluetooth.btsnooplogmode", - capture_output=True).get_captured_output() - - def check_capabilities(self): - self.logger.info("Checking if device has root") - self.c_has_root = self.platform.run_adb_command( - "shell which su", capture_output=True).finished_success() - if self.c_has_root: - self.logger.warning("adb root!") - Bash("adb root", sync=True).start_command() - self.logger.info("Checking if device has tcpdump") - self.c_has_tcpdump = self.platform.run_adb_command( - "shell which tcpdump", capture_output=True).finished_success() - self.logger.info("Checking device CPU arch") - self.c_is_64 = "8" in self.platform.run_adb_command("shell cat /proc/cpuinfo | grep rch", - capture_output=True).get_captured_output() - self.c_hci_snoop_enabled = self.check_snoop_log() - if not self.c_hci_snoop_enabled: - self.logger.info("HCI not enabled, attempting to enable!") - self.platform.run_adb_command( - f"shell setprop persist.bluetooth.btsnooplogmode {config.hci_log_level}") - self.platform.run_adb_command("shell svc bluetooth disable") - self.platform.run_adb_command("shell svc bluetooth enable") - self.c_hci_snoop_enabled = self.check_snoop_log() - if not self.c_hci_snoop_enabled: - self.logger.error("Failed to enabled HCI snoop log") - self.logger.info(self) - with open(self.artifact, "w") as artifact: - artifact.write(str(self)) diff --git a/src/tools/interop/idt/capture/platform/android/config.py b/src/tools/interop/idt/capture/platform/android/config.py deleted file mode 100644 index a0b05cd57a68cd..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/config.py +++ /dev/null @@ -1,20 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -enable_build_push_tcpdump = True -enable_bug_report = True -hci_log_level = "full" diff --git a/src/tools/interop/idt/capture/platform/android/streams/__init__.py b/src/tools/interop/idt/capture/platform/android/streams/__init__.py deleted file mode 100644 index 9f48b1f043fcd4..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/streams/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -from capture.loader import CaptureImplsLoader - -from .base import AndroidStream - -impl_loader = CaptureImplsLoader( - __path__[0], - "capture.platform.android.streams", - AndroidStream -) - -for impl_name, impl in impl_loader.impls.items(): - globals()[impl_name] = impl - -__all__ = impl_loader.impl_names diff --git a/src/tools/interop/idt/capture/platform/android/streams/base.py b/src/tools/interop/idt/capture/platform/android/streams/base.py deleted file mode 100644 index 64681312a36a3b..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/streams/base.py +++ /dev/null @@ -1,33 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from abc import ABC, abstractmethod - - -class AndroidStream(ABC): - - @abstractmethod - async def start(self) -> None: - raise NotImplementedError - - @abstractmethod - async def run_observer(self) -> None: - raise NotImplementedError - - @abstractmethod - async def stop(self) -> None: - raise NotImplementedError diff --git a/src/tools/interop/idt/capture/platform/android/streams/logcat/__init__.py b/src/tools/interop/idt/capture/platform/android/streams/logcat/__init__.py deleted file mode 100644 index eebc071333d89e..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/streams/logcat/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .logcat import LogcatStreamer - -__all__ = ["LogcatStreamer"] diff --git a/src/tools/interop/idt/capture/platform/android/streams/logcat/logcat.py b/src/tools/interop/idt/capture/platform/android/streams/logcat/logcat.py deleted file mode 100644 index 78670bf6504df0..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/streams/logcat/logcat.py +++ /dev/null @@ -1,65 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import asyncio -import os -from typing import TYPE_CHECKING - -from utils.artifact import create_standard_log_name, log - -from ..base import AndroidStream - -logger = log.get_logger(__file__) - -if TYPE_CHECKING: - from capture.platform.android import Android - - -class LogcatStreamer(AndroidStream): - - def __init__(self, platform: "Android"): - self.logger = logger - self.platform = platform - self.logcat_artifact = create_standard_log_name("logcat", "txt", parent=platform.artifact_dir) - self.logcat_command = f"logcat -T 1 >> {self.logcat_artifact}" - self.logcat_proc = platform.get_adb_background_command(self.logcat_command) - self.was_ever_running = False - - async def run_observer(self) -> None: - last_size = 0 - if not os.path.exists(self.logcat_artifact): - self.logger.warning("Logcat artifact does not exist yes, this might be normal at the start of execution") - asyncio.sleep(15) - while True: - try: - new_size = os.path.getsize(self.logcat_artifact) - if not (new_size > last_size): - self.logger.warning(f"Logcat file not growing for {self.platform.device_id}, check connection!") - last_size = new_size - except OSError: - self.logger.error(f"Logcat file does not exist for {self.platfrom.device_id}, check connection!") - if not self.logcat_proc.command_is_running(): - self.logger.error("Logcat proc is not running, trying to restart!") - self.logcat_proc = self.platform.get_adb_background_command(self.logcat_command) - self.logcat_proc.start_command() - await asyncio.sleep(4) - - async def start(self): - self.logcat_proc.start_command() - - async def stop(self): - self.logcat_proc.stop_command() diff --git a/src/tools/interop/idt/capture/platform/android/streams/pcap/__init__.py b/src/tools/interop/idt/capture/platform/android/streams/pcap/__init__.py deleted file mode 100644 index 846210798129ff..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/streams/pcap/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .pcap import AndroidPcap - -__all__ = ["AndroidPcap"] diff --git a/src/tools/interop/idt/capture/platform/android/streams/pcap/linux_build_tcpdump_64.sh b/src/tools/interop/idt/capture/platform/android/streams/pcap/linux_build_tcpdump_64.sh deleted file mode 100755 index c82141b13ec207..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/streams/pcap/linux_build_tcpdump_64.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/bash -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -set -e -export TCPDUMP=4.99.4 -export LIBPCAP=1.10.4 - -wget https://www.tcpdump.org/release/tcpdump-"$TCPDUMP".tar.gz -wget https://www.tcpdump.org/release/libpcap-"$LIBPCAP".tar.gz - -tar zxvf tcpdump-"$TCPDUMP".tar.gz -tar zxvf libpcap-"$LIBPCAP".tar.gz -export CC=aarch64-linux-gnu-gcc -cd libpcap-"$LIBPCAP" -./configure --host=arm-linux --with-pcap=linux -make -cd .. - -cd tcpdump-"$TCPDUMP" -export ac_cv_linux_vers=2 -export CFLAGS=-static -export CPPFLAGS=-static -export LDFLAGS=-static - -./configure --host=arm-linux -make - -aarch64-linux-gnu-strip tcpdump -cp tcpdump .. -cd .. -rm -R libpcap-"$LIBPCAP" -rm -R tcpdump-"$TCPDUMP" -rm libpcap-"$LIBPCAP".tar.gz -rm tcpdump-"$TCPDUMP".tar.gz diff --git a/src/tools/interop/idt/capture/platform/android/streams/pcap/mac_build_tcpdump_64.sh b/src/tools/interop/idt/capture/platform/android/streams/pcap/mac_build_tcpdump_64.sh deleted file mode 100644 index 15d911997b6d15..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/streams/pcap/mac_build_tcpdump_64.sh +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env bash - -# This script cross-compiles libpcap and tcpdump for a specified architecture (default: ARM64) - -# Set bash script to exit immediately if any commands fail, any variables are unexpanded, or any commands in a pipeline fail. -set -o errexit -set -o nounset -set -o pipefail - -# Check for optional target architecture argument, default to aarch64-linux-gnu if not provided -TARGET_ARCH="${1:-aarch64-linux-gnu}" - -# Create a random temporary directory using mktemp -TMP_DIR=$(mktemp -d) -OUT_DIR=$TMP_DIR/out - -# Function to download and extract archives -download_and_extract() { - local url="$1" - local filepath="$2" - local tar_dir="$3" - - wget -O "$filepath" "$url" - tar -C "$tar_dir" -zxvf "$filepath" -} - -# Function to clean up downloaded and extracted files -cleanup() { - local filepath="$1" - local dirpath="$2" - - rm -rf "$filepath" "$dirpath" -} - -# Cross-compile libpcap -LIBPCAP_VERSION=1.10.4 -LIBPCAP_DIR=$TMP_DIR/libpcap-$LIBPCAP_VERSION -LIBPCAP_ARCHIVE=$TMP_DIR/libpcap-$LIBPCAP_VERSION.tar.gz - -download_and_extract "https://www.tcpdump.org/release/libpcap-$LIBPCAP_VERSION.tar.gz" "$LIBPCAP_ARCHIVE" "$TMP_DIR" -(cd "$LIBPCAP_DIR" && ./configure --prefix="$OUT_DIR" --host="$TARGET_ARCH" --with-pcap=linux) -make -C "$LIBPCAP_DIR" -j"$(nproc)" -make -C "$LIBPCAP_DIR" install -cleanup "$LIBPCAP_ARCHIVE" "$LIBPCAP_DIR" - -# Cross-compile tcpdump -TCPDUMP_VERSION=4.99.4 -TCPDUMP_DIR=$TMP_DIR/tcpdump-$TCPDUMP_VERSION -TCPDUMP_ARCHIVE=$TMP_DIR/tcpdump-$TCPDUMP_VERSION.tar.gz - -download_and_extract "https://www.tcpdump.org/release/tcpdump-$TCPDUMP_VERSION.tar.gz" "$TCPDUMP_ARCHIVE" "$TMP_DIR" -(cd "$TCPDUMP_DIR" && CFLAGS="-static -I$OUT_DIR/include" CPPFLAGS="-static" LDFLAGS="-static -L$OUT_DIR/lib" ./configure --prefix="$OUT_DIR" --host="$TARGET_ARCH") -make -C "$TCPDUMP_DIR" -make -C "$TCPDUMP_DIR" install -cleanup "$TCPDUMP_ARCHIVE" "$TCPDUMP_DIR" - -# Prepare the artifact -strip "$OUT_DIR/bin/tcpdump" -mv "$OUT_DIR/bin/tcpdump" . -rm -rf "$TMP_DIR" diff --git a/src/tools/interop/idt/capture/platform/android/streams/pcap/pcap.py b/src/tools/interop/idt/capture/platform/android/streams/pcap/pcap.py deleted file mode 100644 index 8eab53b8ec0d03..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/streams/pcap/pcap.py +++ /dev/null @@ -1,99 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import asyncio -import os -from typing import TYPE_CHECKING - -from utils.artifact import create_standard_log_name, log, safe_mkdir -from utils.host_platform import is_mac -from utils.shell import Bash - -from ... import config -from ..base import AndroidStream - -if TYPE_CHECKING: - from capture.platform.android import Android - -logger = log.get_logger(__file__) - - -class AndroidPcap(AndroidStream): - - def __init__(self, platform: "Android"): - self.logger = logger - self.platform = platform - self.target_dir = "/sdcard/Download" - self.pcap_artifact = create_standard_log_name("android_tcpdump", "pcap", parent=self.platform.artifact_dir) - self.pcap_phone_out_path = f"{self.target_dir}/{os.path.basename(self.pcap_artifact)}" - self.pcap_phone_bin_location = "tcpdump" if platform.capabilities.c_has_tcpdump \ - else f"{self.target_dir}/tcpdump" - self.pcap_command = f"shell {self.pcap_phone_bin_location} -w {self.pcap_phone_out_path}" - self.pcap_proc = platform.get_adb_background_command(self.pcap_command) - self.pcap_pull = False - self.pcap_pull_command = f"pull {self.pcap_phone_out_path} {self.pcap_artifact}" - self.build_dir = os.path.join(os.path.dirname(__file__), "BUILD") - - async def pull_packet_capture(self) -> None: - if self.pcap_pull: - self.logger.info("Attempting to pull android pcap") - await asyncio.sleep(3) - self.platform.run_adb_command(self.pcap_pull_command) - self.pcap_pull = False - - async def start(self): - if not self.platform.capabilities.c_has_root: - self.logger.warning("Phone is not rooted, cannot take pcap!") - return - if self.platform.capabilities.c_has_tcpdump: - self.logger.info("tcpdump already available; using!") - self.pcap_proc.start_command() - self.pcap_pull = True - return - if not config.enable_build_push_tcpdump: - self.logger.critical("Android TCP Dump build and push disabled in configs!") - return - if not os.path.exists(os.path.join(self.build_dir, "tcpdump")): - self.logger.warning("tcpdump bin not found, attempting to build, please wait a few moments!") - safe_mkdir(self.build_dir) - if is_mac(): - build_script = os.path.join(os.path.dirname(__file__), "mac_build_tcpdump_64.sh") - Bash(f"{build_script} 2>&1 >> BUILD_LOG.txt", sync=True, cwd=self.build_dir).start_command() - else: - build_script = os.path.join(os.path.dirname(__file__), "linux_build_tcpdump_64.sh") - Bash(f"{build_script} 2>&1 >> BUILD_LOG.txt", sync=True, cwd=self.build_dir).start_command() - else: - self.logger.warning("Reusing existing tcpdump build") - if not self.platform.run_adb_command(f"shell ls {self.target_dir}/tcpdump").finished_success(): - self.logger.warning("Pushing tcpdump to device") - self.platform.run_adb_command(f"push {os.path.join(self.build_dir, 'tcpdump')} f{self.target_dir}") - self.platform.run_adb_command(f"chmod +x {self.target_dir}/tcpdump") - else: - self.logger.info("tcpdump already in the expected location, not pushing!") - self.logger.info("Starting Android pcap command") - self.pcap_proc.start_command() - self.pcap_pull = True - - async def run_observer(self) -> None: - while True: - # TODO: Implement, need to restart w/ new out file (no append) and keep pull manifest, much like `screen` - await asyncio.sleep(120) - - async def stop(self): - self.logger.info("Stopping android pcap proc") - self.pcap_proc.stop_command() - await self.pull_packet_capture() diff --git a/src/tools/interop/idt/capture/platform/android/streams/screen/__init__.py b/src/tools/interop/idt/capture/platform/android/streams/screen/__init__.py deleted file mode 100644 index 1170a57700a7f7..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/streams/screen/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .screen import ScreenRecorder - -__all__ = ["ScreenRecorder"] diff --git a/src/tools/interop/idt/capture/platform/android/streams/screen/screen.py b/src/tools/interop/idt/capture/platform/android/streams/screen/screen.py deleted file mode 100644 index e190e7cf212c27..00000000000000 --- a/src/tools/interop/idt/capture/platform/android/streams/screen/screen.py +++ /dev/null @@ -1,100 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import asyncio -import os -from typing import TYPE_CHECKING - -from utils.artifact import create_standard_log_name, log - -from ..base import AndroidStream - -if TYPE_CHECKING: - from capture.platform.android import Android - -logger = log.get_logger(__file__) - - -class ScreenRecorder(AndroidStream): - - def __init__(self, platform: "Android"): - self.screen_artifact = None - self.screen_phone_out_path = None - self.screen_command = None - self.screen_proc = None - self.logger = logger - self.platform = platform - self.screen_check_command = "shell dumpsys deviceidle | grep mScreenOn" - self.screen_pull = False - self.file_counter = 0 - self.pull_commands: [str] = [] - self.manifest_file = os.path.join(platform.artifact_dir, "screen_manifest.txt") - - def check_screen(self) -> bool: - screen_cmd_output = self.platform.run_adb_command( - self.screen_check_command, capture_output=True) - return "mScreenOn=true" == screen_cmd_output.get_captured_output().strip() - - async def prepare_screen_recording(self) -> None: - screen_on = self.check_screen() - while not screen_on: - await asyncio.sleep(3) - screen_on = self.check_screen() - if not screen_on: - self.logger.error("Please turn the screen on so screen recording can start or check connection!") - - def update_commands(self) -> None: - self.screen_artifact = create_standard_log_name("screencast" + str(self.file_counter), - "mp4", - parent=self.platform.artifact_dir) - self.screen_phone_out_path = f"/sdcard/Movies/{os.path.basename(self.screen_artifact)}" - self.screen_command = f"shell screenrecord --bugreport {self.screen_phone_out_path}" - screen_pull_command = f"pull {self.screen_phone_out_path} {self.screen_artifact}\n" - self.pull_commands.append(screen_pull_command) - with open(self.manifest_file, "a+") as manifest: - manifest.write(screen_pull_command) - self.file_counter += 1 - - async def start(self): - await self.prepare_screen_recording() - if self.check_screen(): - self.screen_pull = True - self.update_commands() - self.screen_proc = self.platform.get_adb_background_command(self.screen_command) - self.screen_proc.start_command() - self.logger.info(f"New screen recording file started {self.screen_phone_out_path} {self.screen_artifact}") - - async def run_observer(self) -> None: - while True: - if not self.screen_proc.command_is_running(): - self.logger.warning(f"Screen recording proc needs restart (may be normal) {self.platform.device_id}") - await self.start() - await asyncio.sleep(4) - - async def pull_screen_recording(self) -> None: - if self.screen_pull: - self.logger.info("Attempting to pull screen recording") - await asyncio.sleep(3) - with open(self.manifest_file) as manifest: - for line in manifest: - self.platform.run_adb_command(line) - self.screen_pull = False - - async def stop(self): - self.logger.info("Stopping screen proc") - self.screen_proc.stop_command() - await self.pull_screen_recording() diff --git a/src/tools/interop/idt/config.py b/src/tools/interop/idt/config.py deleted file mode 100644 index f084d4918516c4..00000000000000 --- a/src/tools/interop/idt/config.py +++ /dev/null @@ -1,22 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging - -enable_color = True -log_level = logging.INFO -py_major_version = 3 -py_minor_version = 11 diff --git a/src/tools/interop/idt/discovery/__init__.py b/src/tools/interop/idt/discovery/__init__.py deleted file mode 100644 index b83e5dfe0e1f50..00000000000000 --- a/src/tools/interop/idt/discovery/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .ble import MatterBleScanner -from .dnssd import MatterDnssdListener - -__all__ = [ - 'MatterBleScanner', - 'MatterDnssdListener' -] diff --git a/src/tools/interop/idt/discovery/ble.py b/src/tools/interop/idt/discovery/ble.py deleted file mode 100644 index 9549c74614de9a..00000000000000 --- a/src/tools/interop/idt/discovery/ble.py +++ /dev/null @@ -1,118 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import asyncio -import datetime -import os -import sys -import time - -from bleak import AdvertisementData, BleakScanner, BLEDevice -from bleak.exc import BleakDBusError -from utils import log -from utils.log import border_print - -logger = log.get_logger(__file__) - - -class MatterBleScanner: - - def __init__(self, artifact_dir: str): - self.artifact_dir = artifact_dir - self.logger = logger - self.devices_seen_last_time: set[str] = set() - self.devices_seen_this_time: set[str] = set() - self.throttle_seconds = 1 - self.error_seconds = 5 - - def parse_vid_pid(self, loggable_data: str) -> str: - try: - vid = loggable_data[8:10] + loggable_data[6:8] - pid = loggable_data[12:14] + loggable_data[10:12] - except IndexError: - self.logger.warning("Error parsing vid / pid from BLE ad data") - return "" - return f"VID: {vid} PID: {pid}" - - def write_device_log(self, device_name: str, to_write: str) -> None: - log_file_name = os.path.join(self.artifact_dir, f"{device_name}.txt") - with open(log_file_name, "a+") as log_file: - ts = datetime.datetime.now().isoformat(sep=' ', timespec='milliseconds') - to_write = f"{ts}\n{to_write}\n\n" - log_file.write(to_write) - self.logger.info(to_write) - - @staticmethod - def is_matter_device(service_uuid: str) -> bool: - is_matter_device = service_uuid.startswith("0000fff6") - return is_matter_device - - def handle_device_states(self) -> None: - for device_id in self.devices_seen_last_time - self.devices_seen_this_time: - to_log = f"LOST {device_id}\n" - self.write_device_log(device_id, to_log) - self.devices_seen_last_time = self.devices_seen_this_time - self.devices_seen_this_time = set() - - def log_ble_discovery( - self, - name: str, - bin_service_data: bytes, - ble_device: BLEDevice, - rssi: int) -> None: - hex_service_data = bin_service_data.hex() - if self.is_matter_device(name): - device_id = f"{ble_device.name}_{ble_device.address}" - self.devices_seen_this_time.add(device_id) - if device_id not in self.devices_seen_last_time: - to_log = "DISCOVERED\n" - to_log += f"BLE DEVICE NAME: {ble_device.name}\n" - to_log += f"BLE ADDR: {ble_device.address}\n" - to_log += f"NAME: {name}\n" - to_log += f"HEX SERVICE DATA: {hex_service_data}\n" - to_log += f"RSSI {rssi}\n" - to_log += self.parse_vid_pid(hex_service_data) - self.write_device_log(device_id, to_log) - - async def browse(self, scanner: BleakScanner) -> None: - devices: dict[str, tuple[BLEDevice, AdvertisementData]] = await scanner.discover(return_adv=True) - for device in devices.values(): - ble_device = device[0] - ad_data = device[1] - for name, bin_service_data in ad_data.service_data.items(): - self.log_ble_discovery( - name, bin_service_data, ble_device, ad_data.rssi) - self.handle_device_states() - - async def browser_task(self, scanner) -> None: - while True: - try: - await asyncio.sleep(self.throttle_seconds) - await self.browse(scanner) - except BleakDBusError as e: - self.logger.critical(e) - time.sleep(self.error_seconds) - - async def browse_interactive(self) -> None: - scanner = BleakScanner() - self.logger.warning( - "Scanning BLE\nDCL Lookup: https://webui.dcl.csa-iot.org/\n") - border_print("Press enter to stop!", important=True) - task = asyncio.create_task(self.browser_task(scanner)) - await asyncio.get_event_loop().run_in_executor( - None, sys.stdin.readline) - task.cancel() diff --git a/src/tools/interop/idt/discovery/dnssd.py b/src/tools/interop/idt/discovery/dnssd.py deleted file mode 100644 index 04dd8de3494eda..00000000000000 --- a/src/tools/interop/idt/discovery/dnssd.py +++ /dev/null @@ -1,354 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import asyncio -import os -import traceback -from dataclasses import dataclass -from textwrap import dedent -from typing import Callable - -from probe.ip_utils import get_addr_type -from utils.artifact import create_standard_log_name, log -from utils.log import add_border, border_print -from zeroconf import ServiceBrowser, ServiceInfo, ServiceListener, Zeroconf - -logger = log.get_logger(__file__) - - -@dataclass() -class MdnsTypeInfo: - type: str - description: str - - -commissioner = MdnsTypeInfo( - "COMMISSIONER", - "This is a service for a Matter commissioner aka. controller" -) -commissionable = MdnsTypeInfo( - "COMMISSIONABLE / EXTENDED DISCOVERY", - "This is a service to be used in the commissioning process and provides more info about the device." -) -operational = MdnsTypeInfo( - "OPERATIONAL", - "This is a service for a commissioned Matter device. It exposes limited info about the device." -) -border_router = MdnsTypeInfo( - "THREAD BORDER ROUTER", - "This is a service for a thread border router; may be used for thread+Matter devices." -) - -_MDNS_TYPES = { - "_matterd._udp.local.": commissioner, - "_matterc._udp.local.": commissionable, - "_matter._tcp.local.": operational, - "_meshcop._udp.local.": border_router, -} - - -@dataclass() -class RecordParser: - readable_name: str - explanation: str - parse: Callable[[str], str] - - -# TODO: Meshcop parser - -class MatterTxtRecordParser: - - def __init__(self): - self.parsers = { - "D": RecordParser("Discriminator", - dedent("\ - Differentiates this instance of the device from others w/ same VID/PID that might be \n\ - in the environment."), - MatterTxtRecordParser.parse_d), # To hex - "VP": RecordParser("VID/PID", - "The Vendor ID and Product ID (each are two bytes of hex) that identify this product.", - MatterTxtRecordParser.parse_vp), # Split + to hex - "CM": RecordParser("Commissioning mode", - "Whether the device is in commissioning mode or not.", - MatterTxtRecordParser.parse_cm), # Decode - "DT": RecordParser("Device type", - "Application type for this end device.", - MatterTxtRecordParser.parse_dt), # Decode - "DN": RecordParser("Device name", - "Manufacturer provided device name. MAY match NodeLabel in Basic info cluster.", - MatterTxtRecordParser.parse_pass_through), # None - "RI": RecordParser("Rotating identifier", - "Vendor specific, non-trackable per-device ID.", - MatterTxtRecordParser.parse_pass_through), # None - "PH": RecordParser("Pairing hint", - dedent("\ - Given the current device state, follow these instructions to make the device \n\ - commissionable."), - MatterTxtRecordParser.parse_ph), # Decode - "PI": RecordParser("Pairing instructions", - dedent("\ - Used with the Pairing hint. If the Pairing hint mentions N, this is the \n\ - value of N."), - MatterTxtRecordParser.parse_pass_through), # None - # General records - "SII": RecordParser("Session idle interval", - "Message Reliability Protocol retry interval while the device is idle in milliseconds.", - MatterTxtRecordParser.parse_pass_through), # None - "SAI": RecordParser("Session active interval", - dedent("\ - Message Reliability Protocol retry interval while the device is active \n\ - in milliseconds."), - MatterTxtRecordParser.parse_pass_through), # None - "SAT": RecordParser("Session active threshold", - "Duration of time this device stays active after last activity in milliseconds.", - MatterTxtRecordParser.parse_pass_through), # None - "T": RecordParser("Supports TCP", - "Whether this device supports TCP client and or Server.", - MatterTxtRecordParser.parse_t), # Decode - } - self.unparsed_records = "" - self.parsed_records = "" - - def parse_single_record(self, key: str, value: str): - parser: RecordParser = self.parsers[key] - self.parsed_records += add_border(parser.readable_name + "\n") - self.parsed_records += parser.explanation + "\n\n" - try: - self.parsed_records += "PARSED VALUE: " + parser.parse(value) + "\n" - except Exception: - logger.error("Exception parsing TXT record, appending raw value") - logger.error(traceback.format_exc()) - self.parsed_records += f"RAW VALUE: {value}\n" - - def get_output(self) -> str: - unparsed_exp = "\nThe following TXT records were not parsed or explained:\n" - parsed_exp = "\nThe following was discovered about this device via TXT records:\n" - ret = "" - if self.unparsed_records: - ret += unparsed_exp + self.unparsed_records - if self.parsed_records: - ret += parsed_exp + self.parsed_records - return ret - - def parse_records(self, info: ServiceInfo) -> str: - if info.properties is not None: - for name, value in info.properties.items(): - try: - name = name.decode("utf-8") - except UnicodeDecodeError: - name = str(name) - try: - value = value.decode("utf-8") - except UnicodeDecodeError: - value = str(value) - if name not in self.parsers: - self.unparsed_records += f"KEY: {name} VALUE: {value}\n" - else: - self.parse_single_record(name, value) - return self.get_output() - - @staticmethod - def parse_pass_through(txt_value: str) -> str: - return txt_value - - @staticmethod - def parse_d(txt_value: str) -> str: - return hex(int(txt_value)) - - @staticmethod - def parse_vp(txt_value: str) -> str: - vid, pid = txt_value.split("+") - vid, pid = hex(int(vid)), hex(int(pid)) - return f"VID: {vid}, PID: {pid}" - - @staticmethod - def parse_cm(txt_value: str) -> str: - cm = int(txt_value) - mode_descriptions = [ - "Not in commissioning mode", - "In passcode commissioning mode (standard mode)", - "In dynamic passcode commissioning mode", - ] - return mode_descriptions[cm] - - @staticmethod - def parse_dt(txt_value: str) -> str: - application_device_types = { - # lighting - "0x100": "On/Off Light", - "0x101": "Dimmable Light", - "0x10C": "Color Temperature Light", - "0x10D": "Extended Color Light", - # smart plugs/outlets and other actuators - "0x10A": "On/Off Plug-in Unit", - "0x10B": "Dimmable Plug-In Unit", - "0x303": "Pump", - # switches and controls - "0x103": "On/Off Light Switch", - "0x104": "Dimmer Switch", - "0x105": "Color Dimmer Switch", - "0x840": "Control Bridge", - "0x304": "Pump Controller", - "0xF": "Generic Switch", - # sensors - "0x15": "Contact Sensor", - "0x106": "Light Sensor", - "0x107": "Occupancy Sensor", - "0x302": "Temperature Sensor", - "0x305": "Pressure Sensor", - "0x306": "Flow Sensor", - "0x307": "Humidity Sensor", - "0x850": "On/Off Sensor", - # closures - "0xA": "Door Lock", - "0xB": "Door Lock Controller", - "0x202": "Window Covering", - "0x203": "Window Covering Controller", - # HVAC - "0x300": "Heating/Cooling Unit", - "0x301": "Thermostat", - "0x2B": "Fan", - # media - "0x28": "Basic Video Player", - "0x23": "Casting Video Player", - "0x22": "Speaker", - "0x24": "Content App", - "0x29": "Casting Video Client", - "0x2A": "Video Remote Control", - # generic - "0x27": "Mode Select", - } - return application_device_types[hex((int(txt_value))).upper().replace("0X", "0x")] - - @staticmethod - def parse_ph(txt_value: str) -> str: - pairing_hints = [ - "Power Cycle", - "Custom commissioning flow", - "Use existing administrator (already commissioned)", - "Use settings menu on device", - "Use the PI TXT record hint", - "Read the manual", - "Press the reset button", - "Press Reset Button with application of power", - "Press Reset Button for N seconds", - "Press Reset Button until light blinks", - "Press Reset Button for N seconds with application of power", - "Press Reset Button until light blinks with application of power", - "Press Reset Button N times", - "Press Setup Button", - "Press Setup Button with application of power", - "Press Setup Button for N seconds", - "Press Setup Button until light blinks", - "Press Setup Button for N seconds with application of power", - "Press Setup Button until light blinks with application of power", - "Press Setup Button N times", - ] - ret = "\n" - b_arr = [int(b) for b in bin(int(txt_value))[2:]][::-1] - for i in range(0, len(b_arr)): - b = b_arr[i] - if b: - ret += pairing_hints[i] + "\n" - return ret - - @staticmethod - def parse_t(txt_value: str) -> str: - return "TCP supported" if int(txt_value) else "TCP not supported" - - -class MatterDnssdListener(ServiceListener): - - def __init__(self, artifact_dir: str) -> None: - super().__init__() - self.artifact_dir = artifact_dir - self.logger = logger - self.discovered_matter_devices: [str, ServiceInfo] = {} - - def write_log(self, line: str, log_name: str) -> None: - with open(self.create_device_log_name(log_name), "a+") as log_file: - log_file.write(line) - - def create_device_log_name(self, device_name) -> str: - return os.path.join( - self.artifact_dir, - create_standard_log_name(f"{device_name}_dnssd", "txt")) - - @staticmethod - def log_addr(info: ServiceInfo) -> str: - ret = add_border("This device has the following IP addresses\n") - for addr in info.parsed_scoped_addresses(): - ret += f"{get_addr_type(addr)}: {addr}\n" - return ret - - def handle_service_info( - self, - zc: Zeroconf, - type_: str, - name: str, - delta_type: str) -> None: - info = zc.get_service_info(type_, name) - self.discovered_matter_devices[name] = info - to_log = f"{name}\n" - update_str = f"\nSERVICE {delta_type}\n" - to_log += ("*" * (len(update_str) - 2)) + update_str - to_log += _MDNS_TYPES[type_].type + "\n" - to_log += _MDNS_TYPES[type_].description + "\n" - to_log += f"A/SRV TTL: {str(info.host_ttl)}\n" - to_log += f"PTR/TXT TTL: {str(info.other_ttl)}\n" - txt_parser = MatterTxtRecordParser() - to_log += txt_parser.parse_records(info) - to_log += self.log_addr(info) - self.logger.info(to_log) - self.write_log(to_log, name) - - def add_service(self, zc: Zeroconf, type_: str, name: str) -> None: - self.handle_service_info(zc, type_, name, "ADDED") - - def update_service(self, zc: Zeroconf, type_: str, name: str) -> None: - self.handle_service_info(zc, type_, name, "UPDATED") - - def remove_service(self, zc: Zeroconf, type_: str, name: str) -> None: - to_log = f"Service {name} removed\n" - to_log += _MDNS_TYPES[type_].type + "\n" - to_log += _MDNS_TYPES[type_].description - if name in self.discovered_matter_devices: - del self.discovered_matter_devices[name] - self.logger.warning(to_log) - self.write_log(to_log, name) - - def browse_interactive(self) -> None: - zc = Zeroconf() - ServiceBrowser(zc, list(_MDNS_TYPES.keys()), self) - try: - self.logger.warning( - dedent("\ - \n\ - Browsing Matter DNS-SD\n\ - DCL Lookup: https://webui.dcl.csa-iot.org/\n\ - See spec section 4.3 for details of Matter TXT records.\n")) - border_print("Press enter to stop!", important=True) - input("") - finally: - zc.close() - - async def browse_once(self, browse_time_seconds: int) -> Zeroconf: - zc = Zeroconf() - ServiceBrowser(zc, list(_MDNS_TYPES.keys()), self) - await asyncio.sleep(browse_time_seconds) - zc.close() - return zc diff --git a/src/tools/interop/idt/idt.py b/src/tools/interop/idt/idt.py deleted file mode 100644 index 9ddb1ddd90c37f..00000000000000 --- a/src/tools/interop/idt/idt.py +++ /dev/null @@ -1,217 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import argparse -import asyncio -import os -import shutil -import sys -from pathlib import Path - -import probe.runner as probe_runner -from capture import PacketCaptureRunner, controller -from discovery import MatterBleScanner, MatterDnssdListener -from utils.artifact import create_file_timestamp, safe_mkdir -from utils.host_platform import get_available_interfaces, verify_host_dependencies -from utils.log import border_print - -import config - -splash = '''\x1b[0m -\x1b[32;1m┌────────┐\x1b[33;20m▪\x1b[32;1m \x1b[34;1m┌──────┐ \x1b[33;20m• \x1b[35;1m┌──────────┐ \x1b[33;20m● -\x1b[32;1m│░░░░░░░░│ \x1b[34;1m│░░░░░░└┐ \x1b[33;20m゚\x1b[35;1m│░░░░░░░░░░│ -\x1b[32;1m└──┐░░┌──┘\x1b[33;20m۰\x1b[32;1m \x1b[34;1m│░░┌┐░░░│ \x1b[35;1m└───┐░░┌───┘ -\x1b[32;1m │░░│ \x1b[34;1m│░░│└┐░░│\x1b[33;20m▫ \x1b[35;1m \x1b[33;20m۰\x1b[35;1m │░░│ \x1b[33;20m。 -\x1b[32;1m \x1b[33;20m•\x1b[32;1m │░░│ \x1b[33;20m● \x1b[34;1m│░░│┌┘░░│ \x1b[35;1m │░░│ -\x1b[32;1m┌──┘░░└──┐ \x1b[34;1m│░░└┘░░░│ \x1b[35;1m │░░│ \x1b[33;20m• -\x1b[32;1m│░░░░░░░░│ \x1b[34;1m│░░░░░░┌┘\x1b[33;20m۰ \x1b[35;1m \x1b[33;20m▪\x1b[35;1m │░░│ -\x1b[32;1m└────────┘\x1b[33;20m•\x1b[32;1m \x1b[34;1m└──────┘\x1b[33;20m。 \x1b[35;1m └──┘ \x1b[33;20m▫ -\x1b[32;1m✰ Interop\x1b[34;1m ✰ Debugging\x1b[35;1m ✰ Tool -\x1b[0m''' - - -class InteropDebuggingTool: - - def __init__(self) -> None: - if config.enable_color: - print(splash) - self.artifact_dir = None - create_artifact_dir = True - if len(sys.argv) == 1: - create_artifact_dir = False - elif sys.argv[1] != "capture" and sys.argv[1] != "discover": - create_artifact_dir = False - elif len(sys.argv) >= 3 and (sys.argv[2] == "-h" or sys.argv[2] == "--help"): - create_artifact_dir = False - - verify_host_dependencies(["adb", "tcpdump"]) - - if not os.environ['IDT_OUTPUT_DIR']: - print('Missing required env vars! Use /scripts!!!') - sys.exit(1) - - self.artifact_dir_parent = os.path.join( - Path(__file__).resolve().parent, - os.environ['IDT_OUTPUT_DIR']) - artifact_timestamp = create_file_timestamp() - self.artifact_dir = os.path.join( - self.artifact_dir_parent, - f'idt_{artifact_timestamp}') - if create_artifact_dir: - safe_mkdir(self.artifact_dir) - border_print(f"Using artifact dir {self.artifact_dir}") - - self.available_platforms = controller.list_available_platforms() - self.available_platforms_default = 'Android' if 'Android' in self.available_platforms else None - self.platform_required = self.available_platforms_default is None - - self.available_ecosystems = controller.list_available_ecosystems() - self.available_ecosystems_default = 'ALL' - self.available_ecosystems.append(self.available_ecosystems_default) - - self.available_net_interfaces = get_available_interfaces() - self.available_net_interfaces_default = "any" if "any" in self.available_net_interfaces else None - self.pcap_artifact_dir = os.path.join(self.artifact_dir, "pcap") - self.net_interface_required = self.available_net_interfaces_default is None - - self.ble_artifact_dir = os.path.join(self.artifact_dir, "ble") - self.dnssd_artifact_dir = os.path.join(self.artifact_dir, "dnssd") - self.prober_dir = os.path.join(self.artifact_dir, "probes") - - self.process_args() - - def process_args(self) -> None: - parser = argparse.ArgumentParser( - prog="idt", - description="Interop Debugging Tool for Matter") - - subparsers = parser.add_subparsers(title="subcommands") - - discover_parser = subparsers.add_parser( - "discover", help="Discover all Matter devices") - discover_parser.set_defaults(func=self.command_discover) - discover_parser.add_argument( - "--type", - "-t", - help="Specify the type of discovery to execute", - required=True, - choices=[ - "ble", - "b", - "dnssd", - "d"]) - - capture_parser = subparsers.add_parser( - "capture", - help="Capture all information of interest while running a manual test") - - platform_help = "Run capture for a particular platform" - if self.available_platforms_default: - platform_help += f" (default {self.available_platforms_default})" - capture_parser.add_argument("--platform", - "-p", - help=platform_help, - required=self.platform_required, - choices=self.available_platforms, - default=self.available_platforms_default) - - capture_parser.add_argument( - "--ecosystem", - "-e", - help="Run capture for a particular ecosystem or ALL ecosystems (default ALL)", - required=False, - choices=self.available_ecosystems, - default=self.available_ecosystems_default) - - capture_parser.add_argument("--pcap", - "-c", - help="Run packet capture (default t)", - required=False, - choices=['t', 'f'], - default='t') - - interface_help = "Specify packet capture interface" - if self.available_net_interfaces_default: - interface_help += f" (default {self.available_net_interfaces_default})" - capture_parser.add_argument( - "--interface", - "-i", - help=interface_help, - required=self.net_interface_required, - choices=self.available_net_interfaces, - default=self.available_net_interfaces_default) - - capture_parser.set_defaults(func=self.command_capture) - - prober_parser = subparsers.add_parser("probe", - help="Probe the environment for Matter and general networking info") - prober_parser.set_defaults(func=self.command_probe) - - args, unknown = parser.parse_known_args() - if not hasattr(args, 'func'): - parser.print_help() - else: - args.func(args) - - def command_discover(self, args: argparse.Namespace) -> None: - if args.type[0] == "b": - safe_mkdir(self.ble_artifact_dir) - scanner = MatterBleScanner(self.ble_artifact_dir) - asyncio.run(scanner.browse_interactive()) - self.zip_artifacts() - else: - safe_mkdir(self.dnssd_artifact_dir) - MatterDnssdListener(self.dnssd_artifact_dir).browse_interactive() - self.zip_artifacts() - - def zip_artifacts(self) -> None: - zip_basename = os.path.basename(self.artifact_dir) - archive_file = shutil.make_archive(zip_basename, - 'zip', - root_dir=self.artifact_dir) - output_zip = shutil.move(archive_file, self.artifact_dir_parent) - border_print(f'Output zip: {output_zip}') - - def command_capture(self, args: argparse.Namespace) -> None: - pcap = args.pcap == 't' - pcap_runner = None if not pcap else PacketCaptureRunner( - self.pcap_artifact_dir, args.interface) - if pcap: - border_print("Starting pcap") - safe_mkdir(self.pcap_artifact_dir) - pcap_runner.start_pcap() - asyncio.run(controller.init_ecosystems(args.platform, - args.ecosystem, - self.artifact_dir)) - asyncio.run(controller.start()) - asyncio.run(controller.run_analyzers()) - if pcap: - border_print("Stopping pcap") - pcap_runner.stop_pcap() - asyncio.run(controller.stop()) - asyncio.run(controller.probe()) - border_print("Checking error report") - controller.write_error_report(self.artifact_dir) - border_print("Compressing artifacts...") - self.zip_artifacts() - - def command_probe(self, args: argparse.Namespace) -> None: - border_print("Starting generic Matter prober for local environment!") - safe_mkdir(self.dnssd_artifact_dir) - safe_mkdir(self.prober_dir) - probe_runner.run_probes(self.prober_dir, self.dnssd_artifact_dir) - self.zip_artifacts() diff --git a/src/tools/interop/idt/probe/__init__.py b/src/tools/interop/idt/probe/__init__.py deleted file mode 100644 index f44dcd97c812ad..00000000000000 --- a/src/tools/interop/idt/probe/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from dataclasses import dataclass - - -@dataclass(repr=True) -class ProbeTarget: - name: str - ip: str - port: str diff --git a/src/tools/interop/idt/probe/config.py b/src/tools/interop/idt/probe/config.py deleted file mode 100644 index 150e4079e23e31..00000000000000 --- a/src/tools/interop/idt/probe/config.py +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -ping_count = 4 -dnssd_browsing_time_seconds = 4 diff --git a/src/tools/interop/idt/probe/ip_utils.py b/src/tools/interop/idt/probe/ip_utils.py deleted file mode 100644 index ca1e39ebf75f91..00000000000000 --- a/src/tools/interop/idt/probe/ip_utils.py +++ /dev/null @@ -1,50 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import ipaddress - - -def is_ipv4(ip: str) -> bool: - try: - ipaddress.IPv4Address(ip) - return True - except ipaddress.AddressValueError: - return False - - -def is_ipv6_ll(ip: str) -> bool: - try: - return ipaddress.IPv6Address(ip).is_link_local - except ipaddress.AddressValueError: - return False - - -def is_ipv6(ip: str) -> bool: - try: - ipaddress.IPv6Address(ip) - return True - except ipaddress.AddressValueError: - return False - - -def get_addr_type(ip: str) -> str: - if is_ipv4(ip): - return "V4" - elif is_ipv6_ll(ip): - return "V6 Link Local" - elif is_ipv6(ip): - return "V6" diff --git a/src/tools/interop/idt/probe/linux.py b/src/tools/interop/idt/probe/linux.py deleted file mode 100644 index 05a8adb4410e28..00000000000000 --- a/src/tools/interop/idt/probe/linux.py +++ /dev/null @@ -1,48 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import probe.probe as p -from utils.host_platform import get_ll_interface -from utils.log import get_logger - -from . import config - -logger = get_logger(__file__) - - -class ProberLinuxHost(p.GenericMatterProber): - - def __init__(self, artifact_dir: str, dnssd_artifact_dir: str) -> None: - # TODO: Parity with macOS - super().__init__(artifact_dir, dnssd_artifact_dir) - self.logger = logger - self.ll_int = get_ll_interface() - - def discover_targets_by_neighbor(self) -> None: - pass - - def probe_v4(self, ipv4: str, port: str) -> None: - self.run_command(f"ping -c {config.ping_count} {ipv4}") - - def probe_v6(self, ipv6: str, port: str) -> None: - self.run_command(f"ping -c {config.ping_count} -6 {ipv6}") - - def probe_v6_ll(self, ipv6_ll: str, port: str) -> None: - self.run_command(f"ping -c {config.ping_count} -6 {ipv6_ll}%{self.ll_int}") - - def get_general_details(self) -> None: - pass diff --git a/src/tools/interop/idt/probe/mac.py b/src/tools/interop/idt/probe/mac.py deleted file mode 100644 index b13e5d50fa46ce..00000000000000 --- a/src/tools/interop/idt/probe/mac.py +++ /dev/null @@ -1,56 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import probe.probe as p -from utils.host_platform import get_ll_interface -from utils.log import get_logger - -from . import ProbeTarget, config - -logger = get_logger(__file__) - - -class ProberMacHost(p.GenericMatterProber): - - def __init__(self, artifact_dir: str, dnssd_artifact_dir: str) -> None: - # TODO: Build out additional probes - super().__init__(artifact_dir, dnssd_artifact_dir) - self.logger = logger - self.ll_int = get_ll_interface() - - def discover_targets_by_neighbor(self) -> None: - pass - - def probe_v4(self, target: ProbeTarget) -> None: - self.logger.info("Ping IPv4") - self.run_command(f"ping -c {config.ping_count} {target.ip}") - - def probe_v6(self, target: ProbeTarget) -> None: - self.logger.info("Ping IPv6") - self.run_command(f"ping6 -c {config.ping_count} {target.ip}") - - def probe_v6_ll(self, target: ProbeTarget) -> None: - self.logger.info("Ping IPv6 Link Local") - self.run_command(f"ping6 -c {config.ping_count} -I {self.ll_int} {target.ip}") - - def get_general_details(self) -> None: - self.logger.info("Host interfaces") - self.run_command("ifconfig") - self.logger.info("v4 routes from host") - self.run_command("netstat -r -f inet -n") - self.logger.info("v6 routes from host") - self.run_command("netstat -r -f inet6 -n") diff --git a/src/tools/interop/idt/probe/probe.py b/src/tools/interop/idt/probe/probe.py deleted file mode 100644 index 6fcc92ad0428fb..00000000000000 --- a/src/tools/interop/idt/probe/probe.py +++ /dev/null @@ -1,100 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import asyncio -import os.path -from abc import ABC, abstractmethod - -from discovery import MatterDnssdListener -from discovery.dnssd import ServiceInfo -from utils.artifact import create_standard_log_name -from utils.log import get_logger -from utils.shell import Bash - -from . import ProbeTarget, config -from .ip_utils import is_ipv4, is_ipv6, is_ipv6_ll - -logger = get_logger(__file__) - - -class GenericMatterProber(ABC): - - def __init__(self, artifact_dir: str, dnssd_artifact_dir: str) -> None: - self.artifact_dir = artifact_dir - self.dnssd_artifact_dir = dnssd_artifact_dir - self.logger = logger - self.targets: [GenericMatterProber.ProbeTarget] = [] - self.output = os.path.join(self.artifact_dir, - create_standard_log_name("generic_probes", "txt")) - self.suffix = f"2>&1 | tee -a {self.output}" - - def run_command(self, cmd: str, capture_output=False) -> Bash: - cmd = f"{cmd} {self.suffix}" - self.logger.debug(cmd) - bash = Bash(cmd, sync=True, capture_output=capture_output) - bash.start_command() - return bash - - @abstractmethod - def probe_v4(self, target: ProbeTarget) -> None: - raise NotImplementedError - - @abstractmethod - def probe_v6(self, target: ProbeTarget) -> None: - raise NotImplementedError - - @abstractmethod - def probe_v6_ll(self, target: ProbeTarget) -> None: - raise NotImplementedError - - @abstractmethod - def discover_targets_by_neighbor(self) -> None: - raise NotImplementedError - - @abstractmethod - def get_general_details(self) -> None: - raise NotImplementedError - - def discover_targets_by_browsing(self) -> None: - browser = MatterDnssdListener(self.dnssd_artifact_dir) - asyncio.run(browser.browse_once(config.dnssd_browsing_time_seconds)) - for name in browser.discovered_matter_devices: - info: ServiceInfo = browser.discovered_matter_devices[name] - for addr in info.parsed_scoped_addresses(): - self.targets.append(ProbeTarget(name, addr, info.port)) - - def probe_single_target(self, target: ProbeTarget) -> None: - if is_ipv4(target.ip): - self.logger.debug(f"Probing v4 {target.ip}") - self.probe_v4(target) - elif is_ipv6_ll(target.ip): - self.logger.debug(f"Probing v6 ll {target.ip}") - self.probe_v6_ll(target) - elif is_ipv6(target.ip): - self.logger.debug(f"Probing v6 {target.ip}") - self.probe_v6(target) - - def probe_targets(self) -> None: - for target in self.targets: - self.logger.info(f"Probing target {target}") - self.probe_single_target(target) - - def probe(self) -> None: - self.discover_targets_by_browsing() - self.discover_targets_by_neighbor() - self.probe_targets() - self.get_general_details() diff --git a/src/tools/interop/idt/probe/runner.py b/src/tools/interop/idt/probe/runner.py deleted file mode 100644 index ac373178a0ef69..00000000000000 --- a/src/tools/interop/idt/probe/runner.py +++ /dev/null @@ -1,28 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from utils.host_platform import is_mac - -from .linux import ProberLinuxHost -from .mac import ProberMacHost - - -def run_probes(artifact_dir: str, dnssd_dir: str) -> None: - if is_mac(): - ProberMacHost(artifact_dir, dnssd_dir).probe() - else: - ProberLinuxHost(artifact_dir, dnssd_dir).probe() diff --git a/src/tools/interop/idt/requirements.txt b/src/tools/interop/idt/requirements.txt deleted file mode 100644 index dac2cdf0b7cae5..00000000000000 --- a/src/tools/interop/idt/requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -zeroconf==0.74.0 -bleak==0.21.1 -psutil==5.9.6 -termcolor==2.3.0 diff --git a/src/tools/interop/idt/res/plugin_demo/ecosystem/demo_ext_ecosystem/__init__.py b/src/tools/interop/idt/res/plugin_demo/ecosystem/demo_ext_ecosystem/__init__.py deleted file mode 100644 index a91fcfe2f739d9..00000000000000 --- a/src/tools/interop/idt/res/plugin_demo/ecosystem/demo_ext_ecosystem/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .demo_ext_ecosystem import DemoExtEcosystem - -__all__ = [ - 'DemoExtEcosystem' -] diff --git a/src/tools/interop/idt/res/plugin_demo/ecosystem/demo_ext_ecosystem/demo_ext_ecosystem.py b/src/tools/interop/idt/res/plugin_demo/ecosystem/demo_ext_ecosystem/demo_ext_ecosystem.py deleted file mode 100644 index 11fe43f0204332..00000000000000 --- a/src/tools/interop/idt/res/plugin_demo/ecosystem/demo_ext_ecosystem/demo_ext_ecosystem.py +++ /dev/null @@ -1,35 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from capture.base import EcosystemCapture - - -class DemoExtEcosystem(EcosystemCapture): - - def __init__(self, platform, artifact_dir: str) -> None: - self.artifact_dir = artifact_dir - self.platform = platform - self.message = "in the demo external ecosystem" - - async def start_capture(self) -> None: - print("Start capture " + self.message) - - async def stop_capture(self) -> None: - print("Stop capture " + self.message) - - async def analyze_capture(self) -> None: - print("Analyze capture " + self.message) diff --git a/src/tools/interop/idt/scripts/activate.sh b/src/tools/interop/idt/scripts/activate.sh deleted file mode 100644 index 8b3469cb0acdc4..00000000000000 --- a/src/tools/interop/idt/scripts/activate.sh +++ /dev/null @@ -1,25 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -sudo docker run \ - -it \ - --mount source="$PWD"/idt,target=/idt,type=bind \ - --privileged \ - -v /dev/bus/usb:/dev/bus/usb \ - -v /var/run/dbus:/var/run/dbus \ - --net=host \ - idt diff --git a/src/tools/interop/idt/scripts/alias.sh b/src/tools/interop/idt/scripts/alias.sh deleted file mode 100644 index e7b598bc3de5da..00000000000000 --- a/src/tools/interop/idt/scripts/alias.sh +++ /dev/null @@ -1,52 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -if [[ $SHELL == "/bin/zsh" ]]; then - echo "idt using zsh config" - export IDT_SRC_PARENT="$(dirname "$0")/../.." -else - echo "idt using bash config" - export IDT_SRC_PARENT="$(dirname "${BASH_SOURCE[0]:-$0}")/../.." -fi - -export IDT_OUTPUT_DIR="IDT_ARTIFACTS" - -alias idt_dir="echo \"idt dir $IDT_SRC_PARENT\"" -idt_dir -alias idt_go="cd \"$IDT_SRC_PARENT\"" - -alias idt_activate="idt_go && source idt/scripts/activate.sh" -alias idt_bootstrap="idt_go && source idt/scripts/bootstrap.sh" -alias idt_build="idt_go && source idt/scripts/build.sh" -alias idt_clean="idt_go && source idt/scripts/clean.sh" -alias idt_connect="idt_go && source idt/scripts/connect.sh" -alias idt_fetch_artifacts="idt_go && source idt/scripts/fetch_artifacts.sh" -alias idt_prune_docker="idt_go && source idt/scripts/prune_docker.sh" -alias idt_push="idt_go && source idt/scripts/push.sh" -alias idt_vars="idt_go && source idt/scripts/vars.sh" -alias idt_clean_artifacts="idt_go && source idt/scripts/clean_artifacts.sh" -alias idt_clean_all="idt_go && source idt/scripts/clean_all.sh" -alias idt_create_vars="idt_go && source idt/scripts/create_vars.sh" -alias idt_check_child="idt_go && source idt/scripts/check_child.sh" -alias idt_clean_child="idt_go && source idt/scripts/clean_child.sh" - -alias idt="idt_go && \ -if [ -z $PYTHONPYCACHEPREFIX ]; then export PYTHONPYCACHEPREFIX=$IDT_SRC_PARENT/idt/pycache; fi && \ -if [ -z $VIRTUAL_ENV]; then source idt/scripts/py_venv.sh; fi && \ -python3 idt " - -echo "idt commands available! type idt and press tab twice to see available commands." diff --git a/src/tools/interop/idt/scripts/bootstrap.sh b/src/tools/interop/idt/scripts/bootstrap.sh deleted file mode 100644 index 234798787b0655..00000000000000 --- a/src/tools/interop/idt/scripts/bootstrap.sh +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -sudo apt-get update -sudo apt-get install -y docker.io diff --git a/src/tools/interop/idt/scripts/build.sh b/src/tools/interop/idt/scripts/build.sh deleted file mode 100644 index 6b97c9aa99e781..00000000000000 --- a/src/tools/interop/idt/scripts/build.sh +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -sudo docker build idt -t idt diff --git a/src/tools/interop/idt/scripts/check_child.sh b/src/tools/interop/idt/scripts/check_child.sh deleted file mode 100644 index 8a54cd2e65f6db..00000000000000 --- a/src/tools/interop/idt/scripts/check_child.sh +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -sudo ps -axf | grep -E "(tcpd|adb)" diff --git a/src/tools/interop/idt/scripts/clean.sh b/src/tools/interop/idt/scripts/clean.sh deleted file mode 100644 index 056532db4e4108..00000000000000 --- a/src/tools/interop/idt/scripts/clean.sh +++ /dev/null @@ -1,24 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -source idt/scripts/vars.sh -if [[ "$(hostname)" == "$PIHOST" ]]; then - echo "Target env detected, cleaning" - sudo rm -R idt -else - echo "Not in the target env, so not cleaning" -fi diff --git a/src/tools/interop/idt/scripts/clean_all.sh b/src/tools/interop/idt/scripts/clean_all.sh deleted file mode 100644 index d7703ab29d57cc..00000000000000 --- a/src/tools/interop/idt/scripts/clean_all.sh +++ /dev/null @@ -1,23 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -cd idt -sudo rm -R venv/ -sudo rm -R pycache/ -sudo rm -R IDT_ARTIFACTS/ -sudo find . -type d -name "BUILD" -delete -cd .. diff --git a/src/tools/interop/idt/scripts/clean_artifacts.sh b/src/tools/interop/idt/scripts/clean_artifacts.sh deleted file mode 100644 index d6a0a3a01f49cf..00000000000000 --- a/src/tools/interop/idt/scripts/clean_artifacts.sh +++ /dev/null @@ -1,20 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -cd idt -sudo rm -R "$IDT_OUTPUT_DIR" -cd .. diff --git a/src/tools/interop/idt/scripts/clean_child.sh b/src/tools/interop/idt/scripts/clean_child.sh deleted file mode 100644 index fc4b2e21e438d0..00000000000000 --- a/src/tools/interop/idt/scripts/clean_child.sh +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -sudo killall tcpdump -sudo killall adb diff --git a/src/tools/interop/idt/scripts/compilers.sh b/src/tools/interop/idt/scripts/compilers.sh deleted file mode 100644 index ee50284fd6f489..00000000000000 --- a/src/tools/interop/idt/scripts/compilers.sh +++ /dev/null @@ -1,21 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -sudo apt-get install gcc-arm-linux-gnueabi -sudo apt-get install gcc-aarch64-linux-gnu -sudo apt-get install byacc -sudo apt-get install flex diff --git a/src/tools/interop/idt/scripts/connect.sh b/src/tools/interop/idt/scripts/connect.sh deleted file mode 100644 index 05d232628d851a..00000000000000 --- a/src/tools/interop/idt/scripts/connect.sh +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -source idt/scripts/vars.sh -ssh "$PIUSER@$PIHOST" diff --git a/src/tools/interop/idt/scripts/create_vars.sh b/src/tools/interop/idt/scripts/create_vars.sh deleted file mode 100644 index 44d7a4228150b6..00000000000000 --- a/src/tools/interop/idt/scripts/create_vars.sh +++ /dev/null @@ -1,22 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -read -p "Enter RPi host name " pihost -read -p "Enter RPi user name " piuser - -echo "export PIHOST=\"$pihost\"" >"$IDT_SRC_PARENT"/idt/scripts/vars.sh -echo "export PIUSER=\"$piuser\"" >>"$IDT_SRC_PARENT"/idt/scripts/vars.sh diff --git a/src/tools/interop/idt/scripts/fetch_artifacts.sh b/src/tools/interop/idt/scripts/fetch_artifacts.sh deleted file mode 100644 index 49e90274cf2415..00000000000000 --- a/src/tools/interop/idt/scripts/fetch_artifacts.sh +++ /dev/null @@ -1,22 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -source idt/scripts/vars.sh -idt_go -scp -r "$PIUSER@$PIHOST:/home/$PIUSER/idt/$IDT_OUTPUT_DIR" . -cd "$IDT_OUTPUT_DIR" -ls diff --git a/src/tools/interop/idt/scripts/prune_docker.sh b/src/tools/interop/idt/scripts/prune_docker.sh deleted file mode 100644 index 19a44c2041352c..00000000000000 --- a/src/tools/interop/idt/scripts/prune_docker.sh +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -sudo docker system prune -a diff --git a/src/tools/interop/idt/scripts/push.sh b/src/tools/interop/idt/scripts/push.sh deleted file mode 100644 index 5a3d9295e0e4bd..00000000000000 --- a/src/tools/interop/idt/scripts/push.sh +++ /dev/null @@ -1,45 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -source idt/scripts/vars.sh -if [[ -d idt/venv ]]; then - echo "TEMP MOVING venv" - mv idt/venv TEMPvenv -fi -if [[ -d "idt/$IDT_OUTPUT_DIR" ]]; then - echo "TEMP MOVING IDT_OUTPUT_DIR" - mv "idt/$IDT_OUTPUT_DIR" "TEMP""$IDT_OUTPUT_DIR" -fi -if [[ -d idt/pycache ]]; then - echo "TEMP moving pycache" - mv idt/pycache TEMPpycache -fi - -scp -r ./idt/* "$PIUSER@$PIHOST:/home/$PIUSER"/idt - -if [[ -d TEMPvenv ]]; then - mv TEMPvenv idt/venv - echo "venv restored" -fi -if [[ -d "TEMP"$IDT_OUTPUT_DIR ]]; then - mv "TEMP""$IDT_OUTPUT_DIR" "idt/$IDT_OUTPUT_DIR" - echo "IDT_OUTPUT_DIR restored" -fi -if [[ -d "idt/$IDT_OUTPUT_DIR" ]]; then - echo "pycache restored" - mv TEMPpycache idt/pycache -fi diff --git a/src/tools/interop/idt/scripts/py_venv.sh b/src/tools/interop/idt/scripts/py_venv.sh deleted file mode 100644 index 3105cbdd391116..00000000000000 --- a/src/tools/interop/idt/scripts/py_venv.sh +++ /dev/null @@ -1,26 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -cd idt -if [ -d venv ]; then - source venv/bin/activate -else - python3 -m venv venv - source venv/bin/activate - pip install -r requirements.txt -fi -cd .. diff --git a/src/tools/interop/idt/scripts/setup_shell.sh b/src/tools/interop/idt/scripts/setup_shell.sh deleted file mode 100644 index 48eb0c925393dd..00000000000000 --- a/src/tools/interop/idt/scripts/setup_shell.sh +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -echo "source $PWD/idt/scripts/alias.sh" >>~/.bashrc -echo "source $PWD/idt/scripts/alias.sh" >>~/.zshrc diff --git a/src/tools/interop/idt/scripts/vars.sh b/src/tools/interop/idt/scripts/vars.sh deleted file mode 100644 index 5133e8d726c977..00000000000000 --- a/src/tools/interop/idt/scripts/vars.sh +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -export PIHOST="pi-host" -export PIUSER="pi-user" diff --git a/src/tools/interop/idt/utils/__init__.py b/src/tools/interop/idt/utils/__init__.py deleted file mode 100644 index 43ab9acb8a5558..00000000000000 --- a/src/tools/interop/idt/utils/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from . import artifact, host_platform, log, shell - -__all__ = [ - 'artifact', - 'host_platform', - 'log', - 'shell', -] diff --git a/src/tools/interop/idt/utils/artifact.py b/src/tools/interop/idt/utils/artifact.py deleted file mode 100644 index 8749b1ab84880b..00000000000000 --- a/src/tools/interop/idt/utils/artifact.py +++ /dev/null @@ -1,39 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import os -import time -from pathlib import Path - -from . import log - -logger = log.get_logger(__file__) - - -def create_file_timestamp() -> str: - """Conventional file timestamp suffix""" - return time.strftime("%Y%m%d_%H%M%S") - - -def create_standard_log_name(name: str, ext: str, parent: str = "") -> str: - """Returns the name argument wrapped as a standard log name""" - ts = create_file_timestamp() - return os.path.join(parent, f'idt_{ts}_{name}.{ext}') - - -def safe_mkdir(dir_name: str) -> None: - Path(dir_name).mkdir(parents=True, exist_ok=True) diff --git a/src/tools/interop/idt/utils/host_platform.py b/src/tools/interop/idt/utils/host_platform.py deleted file mode 100644 index fd6425666104d9..00000000000000 --- a/src/tools/interop/idt/utils/host_platform.py +++ /dev/null @@ -1,90 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import os -import platform as host_platform -import sys - -from utils import log -from utils.log import border_print -from utils.shell import Bash - -import config - -logger = log.get_logger(__file__) - - -def is_mac(): - p = host_platform.platform().lower() - return "darwin" in p or "mac" in p - - -def get_ll_interface(): - # TODO: Makes too many assumptions - if is_mac(): - return "en0" - net_interface_path = "/sys/class/net/" - available_net_interfaces = os.listdir(net_interface_path) \ - if os.path.exists(net_interface_path) \ - else [] - for interface in available_net_interfaces: - if "wl" in interface: - return interface - - -def get_available_interfaces(): - net_interface_path = "/sys/class/net/" - available_net_interfaces = os.listdir(net_interface_path) \ - if os.path.exists(net_interface_path) \ - else [] - available_net_interfaces.append("any") - return available_net_interfaces - - -def command_is_available(cmd_name) -> bool: - cmd = Bash(f"which {cmd_name}", sync=True, capture_output=True) - cmd.start_command() - return cmd.finished_success() - - -def verify_host_dependencies(deps: [str]) -> None: - if not command_is_available("which"): - # TODO: Check $PATH explicitly as well - logger.critical("which is required to verify host dependencies, exiting as its not available!") - sys.exit(1) - missing_deps = [] - for dep in deps: - logger.info(f"Verifying host dependency {dep}") - if not command_is_available(dep): - missing_deps.append(dep) - if missing_deps: - for missing_dep in missing_deps: - border_print(f"Missing dependency, please install {missing_dep}!", important=True) - sys.exit(1) - - -def verify_py_version() -> None: - py_version_major = sys.version_info[0] - py_version_minor = sys.version_info[1] - have = f"{py_version_major}.{py_version_minor}" - need = f"{config.py_major_version}.{config.py_minor_version}" - if not (py_version_major == config.py_major_version - and py_version_minor >= config.py_minor_version): - logger.critical( - f"IDT requires python >= {need} but you have {have}") - logger.critical("Please install the correct version, delete idt/venv, and re-run!") - sys.exit(1) diff --git a/src/tools/interop/idt/utils/log.py b/src/tools/interop/idt/utils/log.py deleted file mode 100644 index 73dc4e0d876f65..00000000000000 --- a/src/tools/interop/idt/utils/log.py +++ /dev/null @@ -1,79 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import logging -from typing import TextIO - -from termcolor import colored - -import config - -_CONFIG_LEVEL = config.log_level - -_FORMAT_PRE_FSTRING = "%(asctime)s %(levelname)s {%(module)s} [%(funcName)s] " -_FORMAT_PRE = colored(_FORMAT_PRE_FSTRING, "blue") if config.enable_color else _FORMAT_PRE_FSTRING -_FORMAT_POST = "%(message)s" -_FORMAT_NO_COLOR = _FORMAT_PRE_FSTRING+_FORMAT_POST - -FORMATS = { - logging.DEBUG: _FORMAT_PRE + colored(_FORMAT_POST, "blue"), - logging.INFO: _FORMAT_PRE + colored(_FORMAT_POST, "green"), - logging.WARNING: _FORMAT_PRE + colored(_FORMAT_POST, "yellow"), - logging.ERROR: _FORMAT_PRE + colored(_FORMAT_POST, "red", attrs=["bold"]), - logging.CRITICAL: _FORMAT_PRE + colored(_FORMAT_POST, "red", "on_yellow", attrs=["bold"]), -} - - -class LoggingFormatter(logging.Formatter): - - def format(self, record): - log_fmt = FORMATS.get(record.levelno) if config.enable_color else _FORMAT_NO_COLOR - formatter = logging.Formatter(log_fmt) - return formatter.format(record) - - -def get_logger(logger_name) -> logging.Logger: - logger = logging.getLogger(logger_name) - logger.setLevel(_CONFIG_LEVEL) - ch = logging.StreamHandler() - ch.setLevel(_CONFIG_LEVEL) - ch.setFormatter(LoggingFormatter()) - logger.addHandler(ch) - logger.propagate = False - return logger - - -def border_print(to_print: str, important: bool = False) -> None: - len_borders = len(to_print) - border = f"\n{'_' * len_borders}\n" - i_border = f"\n{'!' * len_borders}\n" if important else "" - to_print = f"{border}{i_border}{to_print}{i_border}{border}" - if config.enable_color: - to_print = colored(to_print, "magenta") - print(to_print) - - -def print_and_write(to_print: str, file: TextIO) -> None: - if config.enable_color: - print(colored(to_print, "green")) - else: - print(to_print) - file.write(to_print) - - -def add_border(to_print: str) -> str: - return '\n' + '*' * len(to_print) + '\n' + to_print diff --git a/src/tools/interop/idt/utils/shell.py b/src/tools/interop/idt/utils/shell.py deleted file mode 100644 index e2b0d27a58d800..00000000000000 --- a/src/tools/interop/idt/utils/shell.py +++ /dev/null @@ -1,122 +0,0 @@ -# -# Copyright (c) 2023 Project CHIP Authors -# All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import multiprocessing -import shlex -import subprocess - -import psutil - -from . import log - -logger = log.get_logger(__file__) - - -class Bash: - - def __init__(self, command: str, sync: bool = False, - capture_output: bool = False, - cwd: str = None) -> None: - """ - Run a bash command as a sub process - :param command: Command to run - :param sync: If True, wait for command to terminate upon start_command() - :param capture_output: Only applies to sync; if True, store and suppress stdout and stderr - :param cwd: Set working directory of command - """ - self.logger = logger - self.command: str = command - self.sync = sync - self.capture_output = capture_output - self.cwd = cwd - - self.args: list[str] = [] - self._init_args() - self.proc: None | subprocess.CompletedProcess | subprocess.Popen = None - - def _init_args(self) -> None: - command_escaped = self.command.replace('"', '\"') - self.args = shlex.split(f'/bin/bash -c "{command_escaped}"') - - def command_is_running(self) -> bool: - return self.proc is not None and self.proc.poll() is None - - def get_captured_output(self) -> str: - return "" if not self.capture_output or not self.sync \ - else self.proc.stdout.decode().strip() - - def start_command(self) -> None: - if self.proc is None: - if self.sync: - self.proc = subprocess.run(self.args, capture_output=self.capture_output, cwd=self.cwd) - else: - self.proc = subprocess.Popen(self.args, cwd=self.cwd, stdin=subprocess.PIPE) - else: - self.logger.warning(f'"{self.command}" start requested more than once for same Bash instance!') - - def term_with_sudo(self, proc: multiprocessing.Process) -> None: - self.logger.debug(f"SIGTERM {proc.pid} with sudo") - Bash(f"sudo kill {proc.pid}", sync=True).start_command() - - def kill_with_sudo(self, proc: multiprocessing.Process) -> None: - self.logger.debug(f"SIGKILL {proc.pid} with sudo") - Bash(f"sudo kill -9 {proc.pid}", sync=True).start_command() - - def term(self, proc: multiprocessing.Process) -> None: - if "sudo" in self.command: - self.term_with_sudo(proc) - else: - proc.terminate() - - def kill(self, proc: multiprocessing.Process) -> None: - if "sudo" in self.command: - self.kill_with_sudo(proc) - else: - proc.kill() - - def stop_single_proc(self, proc: multiprocessing.Process) -> None: - self.logger.debug(f"Killing process {proc.pid}") - try: - self.logger.debug("Sending SIGTERM") - self.term(proc) - proc.wait(3) - except psutil.TimeoutExpired: - self.logger.error("SIGTERM timeout expired") - try: - self.logger.debug("Sending SIGKILL") - self.kill(proc) - proc.wait(3) - except psutil.TimeoutExpired: - self.logger.critical(f"SIGKILL timeout expired, could not kill pid {proc.pid}") - - def stop_command(self) -> None: - if self.command_is_running(): - psutil_proc = psutil.Process(self.proc.pid) - suffix = f"{psutil_proc.pid} for command {self.command}" - self.logger.debug(f"Stopping children of {suffix}") - for child_proc in psutil_proc.children(recursive=True): - self.stop_single_proc(child_proc) - self.logger.debug(f"Killing root proc {suffix}") - self.stop_single_proc(psutil_proc) - else: - self.logger.warning(f'{self.command} stop requested while not running') - - def finished_success(self) -> bool: - if not self.sync: - return not self.command_is_running() and self.proc.returncode == 0 - else: - return self.proc is not None and self.proc.returncode == 0 diff --git a/src/transport/SecureSession.h b/src/transport/SecureSession.h index b18cc05b4ce716..c5e04628f17c3f 100644 --- a/src/transport/SecureSession.h +++ b/src/transport/SecureSession.h @@ -22,7 +22,7 @@ #pragma once #include -#include +#include #include #include #include diff --git a/src/transport/UnauthenticatedSessionTable.h b/src/transport/UnauthenticatedSessionTable.h index f5ba35df533de5..1c3ff7ed55586a 100644 --- a/src/transport/UnauthenticatedSessionTable.h +++ b/src/transport/UnauthenticatedSessionTable.h @@ -16,7 +16,7 @@ */ #pragma once -#include +#include #include #include #include diff --git a/src/transport/raw/BLE.h b/src/transport/raw/BLE.h index 548af414b2fffe..5e9da499664329 100644 --- a/src/transport/raw/BLE.h +++ b/src/transport/raw/BLE.h @@ -24,12 +24,9 @@ #pragma once -#include - #include -#include -#include +#include #include #include #include diff --git a/third_party/nxp/rt_sdk/rt_sdk.gni b/third_party/nxp/rt_sdk/rt_sdk.gni index 9063361f7b9d4d..eb44f01802ce14 100644 --- a/third_party/nxp/rt_sdk/rt_sdk.gni +++ b/third_party/nxp/rt_sdk/rt_sdk.gni @@ -562,11 +562,7 @@ template("rt_sdk") { } if (chip_enable_wifi) { - if (!w8801_transceiver) { - defines += [ "CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION=1" ] - } else { - defines += [ "CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION=0" ] - } + defines += [ "CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION=1" ] } # Now add our "system-header" include dirs diff --git a/third_party/ti_simplelink_sdk/ti_simplelink_sdk.gni b/third_party/ti_simplelink_sdk/ti_simplelink_sdk.gni index 0698af16536e51..af3e810d67e6bf 100644 --- a/third_party/ti_simplelink_sdk/ti_simplelink_sdk.gni +++ b/third_party/ti_simplelink_sdk/ti_simplelink_sdk.gni @@ -305,8 +305,8 @@ template("ti_simplelink_sdk") { configs -= [ "${build_root}/config/compiler:std_default" ] configs += [ ":${sdk_target_name}_posix_config" ] sources = [ + "${chip_root}/src/platform/cc13xx_26xx/memory.c", "${ti_simplelink_sdk_root}/source/ti/posix/freertos/clock.c", - "${ti_simplelink_sdk_root}/source/ti/posix/freertos/memory.c", "${ti_simplelink_sdk_root}/source/ti/posix/freertos/mqueue.c", "${ti_simplelink_sdk_root}/source/ti/posix/freertos/pthread.c", "${ti_simplelink_sdk_root}/source/ti/posix/freertos/pthread_barrier.c", @@ -521,8 +521,8 @@ template("ti_simplelink_sdk") { ] sources = [ + "${chip_root}/src/platform/cc13xx_26xx/TI_heap_wrapper.c", "${chip_root}/src/platform/cc13xx_26xx/chipOBleProfile.c", - "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/freertos/TI_heap_wrapper.c", "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/freertos/bget.c", "${ti_simplelink_sdk_root}/source/ti/ble5stack/common/cc26xx/rcosc/rcosc_calibration.c", "${ti_simplelink_sdk_root}/source/ti/dmm/apps/common/ble_remote_display/stack/osal_icall_ble.c",