diff --git a/src/BUILD.gn b/src/BUILD.gn index d455a596b4e346..13f09beab2d4df 100644 --- a/src/BUILD.gn +++ b/src/BUILD.gn @@ -96,7 +96,6 @@ if (chip_build_tests) { if (chip_device_platform != "efr32") { tests += [ "${chip_root}/src/app/tests", - "${chip_root}/src/app/tests:tests_nltest", "${chip_root}/src/credentials/tests", "${chip_root}/src/lib/format/tests", "${chip_root}/src/lib/support/tests", diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index 41f083e1735924..7c07564b77024e 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -141,6 +141,8 @@ chip_test_suite("tests") { output_name = "libAppTests" test_sources = [ + "TestAclAttribute.cpp", + "TestAclEvent.cpp", "TestAttributeAccessInterfaceCache.cpp", "TestAttributePathExpandIterator.cpp", "TestAttributePathParams.cpp", @@ -150,11 +152,16 @@ chip_test_suite("tests") { "TestBasicCommandPathRegistry.cpp", "TestBindingTable.cpp", "TestBuilderParser.cpp", + "TestCommandInteraction.cpp", "TestCommandPathParams.cpp", "TestConcreteAttributePath.cpp", "TestDataModelSerialization.cpp", "TestDefaultOTARequestorStorage.cpp", + "TestEventLoggingNoUTCTime.cpp", + "TestEventOverflow.cpp", "TestEventPathParams.cpp", + "TestFabricScopedEventLogging.cpp", + "TestInteractionModelEngine.cpp", "TestMessageDef.cpp", "TestNullable.cpp", "TestNumericAttributeTraits.cpp", @@ -162,25 +169,17 @@ chip_test_suite("tests") { "TestPendingNotificationMap.cpp", "TestPendingResponseTrackerImpl.cpp", "TestPowerSourceCluster.cpp", + "TestReadInteraction.cpp", + "TestReportScheduler.cpp", + "TestReportingEngine.cpp", "TestStatusIB.cpp", "TestStatusResponseMessage.cpp", "TestTestEventTriggerDelegate.cpp", "TestTimeSyncDataProvider.cpp", + "TestTimedHandler.cpp", + "TestWriteInteraction.cpp", ] - if (!chip_fake_platform) { - test_sources += [ "TestFailSafeContext.cpp" ] - } - - # DefaultICDClientStorage assumes that raw AES key is used by the application - if (chip_crypto != "psa") { - test_sources += [ "TestDefaultICDClientStorage.cpp" ] - } - - if (chip_persist_subscriptions) { - test_sources += [ "TestSimpleSubscriptionResumptionStorage.cpp" ] - } - cflags = [ "-Wconversion" ] public_deps = [ @@ -199,6 +198,7 @@ chip_test_suite("tests") { "${chip_root}/src/lib/core:string-builder-adapters", "${chip_root}/src/lib/support:test_utils", "${chip_root}/src/lib/support:testing", + "${chip_root}/src/lib/support/tests:pw-test-macros", ] if (chip_device_platform != "android") { @@ -211,27 +211,29 @@ chip_test_suite("tests") { ":scenes-table-test-srcs", ] } -} -chip_test_suite_using_nltest("tests_nltest") { - output_name = "libAppTestsNL" + if (chip_config_network_layer_ble && + (chip_device_platform == "linux" || chip_device_platform == "darwin")) { + test_sources += [ "TestCommissioningWindowManager.cpp" ] + public_deps += [ + "${chip_root}/src/app/server", + "${chip_root}/src/messaging/tests/echo:common", + ] + } - test_sources = [ - "TestAclAttribute.cpp", - "TestAclEvent.cpp", - "TestCommandInteraction.cpp", - "TestEventLoggingNoUTCTime.cpp", - "TestEventOverflow.cpp", - "TestFabricScopedEventLogging.cpp", - "TestInteractionModelEngine.cpp", - "TestReadInteraction.cpp", - "TestReportScheduler.cpp", - "TestReportingEngine.cpp", - "TestTimedHandler.cpp", - "TestWriteInteraction.cpp", - ] + if (!chip_fake_platform) { + test_sources += [ "TestFailSafeContext.cpp" ] + } + + # DefaultICDClientStorage assumes that raw AES key is used by the application + if (chip_crypto != "psa") { + test_sources += [ "TestDefaultICDClientStorage.cpp" ] + } + + if (chip_persist_subscriptions) { + test_sources += [ "TestSimpleSubscriptionResumptionStorage.cpp" ] + } - # # On NRF platforms, the allocation of a large number of pbufs in this test # to exercise chunking causes it to run out of memory. For now, disable it there. # @@ -248,33 +250,4 @@ chip_test_suite_using_nltest("tests_nltest") { chip_device_platform != "openiotsdk" && chip_device_platform != "fake") { test_sources += [ "TestEventLogging.cpp" ] } - - cflags = [ "-Wconversion" ] - - public_deps = [ - ":app-test-stubs", - ":binding-test-srcs", - ":operational-state-test-srcs", - ":ota-requestor-test-srcs", - ":time-sync-data-provider-test-srcs", - "${chip_root}/src/app", - "${chip_root}/src/app/common:cluster-objects", - "${chip_root}/src/app/icd/client:manager", - "${chip_root}/src/app/tests:helpers", - "${chip_root}/src/app/util/mock:mock_ember", - "${chip_root}/src/lib/core", - "${chip_root}/src/lib/support:test_utils", - "${chip_root}/src/lib/support:testing", - "${chip_root}/src/lib/support:testing_nlunit", - "${nlunit_test_root}:nlunit-test", - ] - - if (chip_config_network_layer_ble && - (chip_device_platform == "linux" || chip_device_platform == "darwin")) { - test_sources += [ "TestCommissionManager.cpp" ] - public_deps += [ - "${chip_root}/src/app/server", - "${chip_root}/src/messaging/tests/echo:common", - ] - } } diff --git a/src/app/tests/TestAclAttribute.cpp b/src/app/tests/TestAclAttribute.cpp index 1c928515dc5d74..8ff88967deb5b0 100644 --- a/src/app/tests/TestAclAttribute.cpp +++ b/src/app/tests/TestAclAttribute.cpp @@ -16,6 +16,9 @@ * limitations under the License. */ +#include +#include + #include #include #include @@ -34,11 +37,8 @@ #include #include #include -#include -#include #include #include -#include #include #include @@ -73,18 +73,6 @@ class TestDeviceTypeResolver : public AccessControl::DeviceTypeResolver bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) override { return false; } } gDeviceTypeResolver; -class TestAccessContext : public chip::Test::AppContext -{ -public: - // Performs setup for each individual test in the test suite - void SetUp() override - { - chip::Test::AppContext::SetUp(); - Access::GetAccessControl().Finish(); - Access::GetAccessControl().Init(GetTestAccessControlDelegate(), gDeviceTypeResolver); - } -}; - class MockInteractionModelApp : public chip::app::ReadClient::Callback { public: @@ -121,29 +109,50 @@ class MockInteractionModelApp : public chip::app::ReadClient::Callback namespace chip { namespace app { -class TestAclAttribute +class TestAclAttribute : public ::testing::Test { public: - static void TestACLDeniedAttribute(nlTestSuite * apSuite, void * apContext); + static void SetUpTestSuite() + { + + mpTestContext = new chip::Test::AppContext; + mpTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + delete mpTestContext; + } + + void SetUp() override + { + mpTestContext->SetUp(); + + Access::GetAccessControl().Finish(); + Access::GetAccessControl().Init(GetTestAccessControlDelegate(), gDeviceTypeResolver); + } + void TearDown() override { mpTestContext->TearDown(); } + + static chip::Test::AppContext * mpTestContext; }; +chip::Test::AppContext * TestAclAttribute::mpTestContext = nullptr; + // Read Client sends a malformed subscribe request, interaction model engine fails to parse the request and generates a status // report to client, and client is closed. -void TestAclAttribute::TestACLDeniedAttribute(nlTestSuite * apSuite, void * apContext) +TEST_F(TestAclAttribute, TestACLDeniedAttribute) { - TestAccessContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; @@ -155,22 +164,21 @@ void TestAclAttribute::TestACLDeniedAttribute(nlTestSuite * apSuite, void * apCo attributePathParams[1].mClusterId = chip::Test::kTestDeniedClusterId1; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(InvalidAction)); - NL_TEST_ASSERT(apSuite, !delegate.mGotReport); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); + EXPECT_FALSE(delegate.mGotReport); delegate.mError = CHIP_NO_ERROR; delegate.mGotReport = false; } { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; @@ -181,22 +189,21 @@ void TestAclAttribute::TestACLDeniedAttribute(nlTestSuite * apSuite, void * apCo attributePathParams[1].mClusterId = chip::Test::kTestDeniedClusterId2; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(InvalidAction)); - NL_TEST_ASSERT(apSuite, !delegate.mGotReport); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); + EXPECT_FALSE(delegate.mGotReport); delegate.mError = CHIP_NO_ERROR; delegate.mGotReport = false; } { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; @@ -208,49 +215,23 @@ void TestAclAttribute::TestACLDeniedAttribute(nlTestSuite * apSuite, void * apCo attributePathParams[1].mClusterId = chip::Test::kTestClusterId; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(delegate.mError, CHIP_NO_ERROR); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); delegate.mError = CHIP_NO_ERROR; delegate.mGotReport = false; } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } } // namespace app } // namespace chip - -namespace { - -const nlTest sTests[] = { - NL_TEST_DEF("TestACLDeniedAttribute", chip::app::TestAclAttribute::TestACLDeniedAttribute), - NL_TEST_SENTINEL(), -}; - -nlTestSuite sSuite = { - "TestAclAttribute", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestAccessContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestAccessContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestAccessContext, SetUp), - NL_TEST_WRAP_METHOD(TestAccessContext, TearDown), -}; - -} // namespace - -int TestAclAttribute() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestAclAttribute) diff --git a/src/app/tests/TestAclEvent.cpp b/src/app/tests/TestAclEvent.cpp index 8f377cc263e9bd..014625ad628b65 100644 --- a/src/app/tests/TestAclEvent.cpp +++ b/src/app/tests/TestAclEvent.cpp @@ -16,6 +16,11 @@ * limitations under the License. */ +#include + +#include +#include + #include #include #include @@ -31,15 +36,10 @@ #include #include #include -#include -#include #include #include -#include #include -#include - namespace { using namespace chip; using namespace chip::Access; @@ -48,7 +48,6 @@ uint8_t gDebugEventBuffer[128]; uint8_t gInfoEventBuffer[128]; uint8_t gCritEventBuffer[128]; chip::app::CircularEventBuffer gCircularEventBuffer[3]; -chip::ClusterId kTestClusterId1 = 100; chip::ClusterId kTestClusterId2 = 7; chip::EndpointId kTestEndpointId = 1; chip::EventId kTestEventIdDebug = 1; @@ -62,7 +61,7 @@ class TestAccessControlDelegate : public AccessControl::Delegate CHIP_ERROR Check(const SubjectDescriptor & subjectDescriptor, const chip::Access::RequestPath & requestPath, Privilege requestPrivilege) override { - if (requestPath.cluster == kTestClusterId1) + if (requestPath.cluster == chip::Test::kTestDeniedClusterId2) { return CHIP_ERROR_ACCESS_DENIED; } @@ -82,42 +81,6 @@ class TestDeviceTypeResolver : public AccessControl::DeviceTypeResolver bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) override { return false; } } gDeviceTypeResolver; -class TestContext : public chip::Test::AppContext -{ -public: - // Performs setup for each individual test in the test suite - void SetUp() override - { - const chip::app::LogStorageResources logStorageResources[] = { - { &gDebugEventBuffer[0], sizeof(gDebugEventBuffer), chip::app::PriorityLevel::Debug }, - { &gInfoEventBuffer[0], sizeof(gInfoEventBuffer), chip::app::PriorityLevel::Info }, - { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, - }; - - chip::Test::AppContext::SetUp(); - - CHIP_ERROR err = CHIP_NO_ERROR; - // TODO: use ASSERT_EQ, once transition to pw_unit_test is complete - VerifyOrDieWithMsg((err = mEventCounter.Init(0)) == CHIP_NO_ERROR, AppServer, - "Init EventCounter failed: %" CHIP_ERROR_FORMAT, err.Format()); - chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), - gCircularEventBuffer, logStorageResources, &mEventCounter); - - Access::GetAccessControl().Finish(); - Access::GetAccessControl().Init(GetTestAccessControlDelegate(), gDeviceTypeResolver); - } - - // Performs teardown for each individual test in the test suite - void TearDown() override - { - chip::app::EventManagement::DestroyEventManagement(); - chip::Test::AppContext::TearDown(); - } - -private: - chip::MonotonicallyIncreasingCounter mEventCounter; -}; - class TestEventGenerator : public chip::app::EventLoggingDelegate { public: @@ -136,12 +99,11 @@ class TestEventGenerator : public chip::app::EventLoggingDelegate int32_t mStatus; }; -void GenerateEvents(nlTestSuite * apSuite, void * apContext) +void GenerateEvents() { - CHIP_ERROR err = CHIP_NO_ERROR; chip::EventNumber eid1, eid2; chip::app::EventOptions options1; - options1.mPath = { kTestEndpointId, kTestClusterId1, kTestEventIdDebug }; + options1.mPath = { kTestEndpointId, chip::Test::kTestDeniedClusterId2, kTestEventIdDebug }; options1.mPriority = chip::app::PriorityLevel::Info; chip::app::EventOptions options2; @@ -152,11 +114,10 @@ void GenerateEvents(nlTestSuite * apSuite, void * apContext) ChipLogDetail(DataManagement, "Generating Events"); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options1, eid1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options1, eid1), CHIP_NO_ERROR); + testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options2, eid2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options2, eid2), CHIP_NO_ERROR); } class MockInteractionModelApp : public chip::app::ReadClient::Callback @@ -210,87 +171,129 @@ class MockInteractionModelApp : public chip::app::ReadClient::Callback namespace chip { namespace app { -class TestAclEvent + +class TestAclEvent : public ::testing::Test { public: - static void TestReadRoundtripWithEventStatusIBInEventReport(nlTestSuite * apSuite, void * apContext); + static void SetUpTestSuite() + { + + mpTestContext = new chip::Test::AppContext; + mpTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + delete mpTestContext; + } + + // Performs setup for each individual test in the test suite + void SetUp() override + { + const chip::app::LogStorageResources logStorageResources[] = { + { &gDebugEventBuffer[0], sizeof(gDebugEventBuffer), chip::app::PriorityLevel::Debug }, + { &gInfoEventBuffer[0], sizeof(gInfoEventBuffer), chip::app::PriorityLevel::Info }, + { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, + }; + + mpTestContext->SetUp(); + + ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); + chip::app::EventManagement::CreateEventManagement(&mpTestContext->GetExchangeManager(), ArraySize(logStorageResources), + gCircularEventBuffer, logStorageResources, &mEventCounter); + + Access::GetAccessControl().Finish(); + Access::GetAccessControl().Init(GetTestAccessControlDelegate(), gDeviceTypeResolver); + } + + // Performs teardown for each individual test in the test suite + void TearDown() override + { + chip::app::EventManagement::DestroyEventManagement(); + mpTestContext->TearDown(); + } + + static chip::Test::AppContext * mpTestContext; + +private: + chip::MonotonicallyIncreasingCounter mEventCounter; }; -void TestAclEvent::TestReadRoundtripWithEventStatusIBInEventReport(nlTestSuite * apSuite, void * apContext) +chip::Test::AppContext * TestAclEvent::mpTestContext = nullptr; + +TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_FALSE(rm->TestGetCountRetransTable()); - GenerateEvents(apSuite, apContext); + GenerateEvents(); auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); // A custom AccessControl::Delegate has been installed that grants privilege to any cluster except the test cluster. // When reading events with concrete paths without enough privilege, we will get a EventStatusIB { chip::app::EventPathParams eventPathParams[1]; eventPathParams[0].mEndpointId = kTestEndpointId; - eventPathParams[0].mClusterId = kTestClusterId1; + eventPathParams[0].mClusterId = chip::Test::kTestDeniedClusterId2; eventPathParams[0].mEventId = kTestEventIdDebug; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mEventPathParamsListSize = 1; readPrepareParams.mEventNumber.SetValue(1); MockInteractionModelApp delegate; - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_FALSE(delegate.mGotEventResponse); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, delegate.mNumReadEventFailureStatusReceived == 1); - NL_TEST_ASSERT(apSuite, delegate.mLastStatusReceived.mStatus == Protocols::InteractionModel::Status::UnsupportedAccess); - NL_TEST_ASSERT(apSuite, !delegate.mReadError); + EXPECT_TRUE(delegate.mGotEventResponse); + EXPECT_TRUE(delegate.mNumReadEventFailureStatusReceived); + EXPECT_EQ(delegate.mLastStatusReceived.mStatus, Protocols::InteractionModel::Status::UnsupportedAccess); + EXPECT_FALSE(delegate.mReadError); } - GenerateEvents(apSuite, apContext); + GenerateEvents(); // When reading events with withcard paths without enough privilege for reading all events, we will exclude all events without // enough priviledge when generating the report. { chip::app::EventPathParams eventPathParams[1]; eventPathParams[0].mEndpointId = kTestEndpointId; - eventPathParams[0].mClusterId = kTestClusterId1; + eventPathParams[0].mClusterId = chip::Test::kTestDeniedClusterId2; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mEventPathParamsListSize = 1; readPrepareParams.mEventNumber.SetValue(1); MockInteractionModelApp delegate; - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_FALSE(delegate.mGotEventResponse); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, delegate.mNumReadEventFailureStatusReceived == 0); - NL_TEST_ASSERT(apSuite, !delegate.mReadError); + mpTestContext->DrainAndServiceIO(); + EXPECT_FALSE(delegate.mGotEventResponse); + EXPECT_FALSE(delegate.mNumReadEventFailureStatusReceived); + EXPECT_FALSE(delegate.mReadError); } - GenerateEvents(apSuite, apContext); + GenerateEvents(); // When reading events with withcard paths where the partial don't have enough privilege, we will exclude those partial // when generating the report. @@ -298,97 +301,60 @@ void TestAclEvent::TestReadRoundtripWithEventStatusIBInEventReport(nlTestSuite * chip::app::EventPathParams eventPathParams[1]; eventPathParams[0].mEndpointId = kTestEndpointId; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mEventPathParamsListSize = 1; readPrepareParams.mEventNumber.SetValue(1); MockInteractionModelApp delegate; - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_FALSE(delegate.mGotEventResponse); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, delegate.mNumReadEventFailureStatusReceived == 0); - NL_TEST_ASSERT(apSuite, !delegate.mReadError); + mpTestContext->DrainAndServiceIO(); + EXPECT_TRUE(delegate.mGotEventResponse); + EXPECT_FALSE(delegate.mNumReadEventFailureStatusReceived); + EXPECT_FALSE(delegate.mReadError); } - GenerateEvents(apSuite, apContext); + GenerateEvents(); // When reading events with two concrete paths where one has enough priviledge, another don't have , we will get a EventStatusIB // and eventDataIB { chip::app::EventPathParams eventPathParams[2]; eventPathParams[0].mEndpointId = kTestEndpointId; - eventPathParams[0].mClusterId = kTestClusterId1; + eventPathParams[0].mClusterId = chip::Test::kTestDeniedClusterId2; eventPathParams[0].mEventId = kTestEventIdDebug; eventPathParams[1].mEndpointId = kTestEndpointId; eventPathParams[1].mClusterId = kTestClusterId2; eventPathParams[1].mEventId = kTestEventIdCritical; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mEventPathParamsListSize = 1; readPrepareParams.mEventNumber.SetValue(1); MockInteractionModelApp delegate; - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_FALSE(delegate.mGotEventResponse); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, delegate.mNumReadEventFailureStatusReceived == 1); - NL_TEST_ASSERT(apSuite, !delegate.mReadError); + mpTestContext->DrainAndServiceIO(); + EXPECT_TRUE(delegate.mGotEventResponse); + EXPECT_TRUE(delegate.mNumReadEventFailureStatusReceived); + EXPECT_FALSE(delegate.mReadError); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_FALSE(engine->GetNumActiveReadClients()); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_FALSE(mpTestContext->GetExchangeManager().GetNumActiveExchanges()); } } // namespace app } // namespace chip - -namespace { - -/** - * Test Suite. It lists all the test functions. - */ - -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("TestReadRoundtripWithEventStatusIBInEventReport", chip::app::TestAclEvent::TestReadRoundtripWithEventStatusIBInEventReport), - NL_TEST_SENTINEL() -}; -// clang-format on - -// clang-format off -nlTestSuite sSuite = -{ - "TestAclEvent", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; -// clang-format on - -} // namespace - -int TestAclEvent() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestAclEvent) diff --git a/src/app/tests/TestBufferedReadCallback.cpp b/src/app/tests/TestBufferedReadCallback.cpp index 6079c21b50b49f..91836675db25f4 100644 --- a/src/app/tests/TestBufferedReadCallback.cpp +++ b/src/app/tests/TestBufferedReadCallback.cpp @@ -15,6 +15,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include #include "app-common/zap-generated/ids/Attributes.h" #include "lib/core/TLVTags.h" @@ -26,10 +27,9 @@ #include #include #include -#include -#include -#include -#include + +#include +#include using TestContext = chip::Test::AppContext; using namespace chip::app; @@ -37,8 +37,6 @@ using namespace chip; namespace { -nlTestSuite * gSuite = nullptr; - struct ValidationInstruction { enum ProcessingType @@ -67,6 +65,40 @@ struct ValidationInstruction using InstructionListType = std::vector; +class TestBufferedReadCallback : public ::testing::Test +{ +public: + static void SetUpTestSuite() + { + mpTestContext = new TestContext; + mpTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + if (mpTestContext != nullptr) + { + delete mpTestContext; + } + } + void SetUp() override + { + if (mpTestContext != nullptr) + { + mpTestContext->SetUp(); + } + } + void TearDown() override + { + if (mpTestContext != nullptr) + { + mpTestContext->TearDown(); + } + } + static TestContext * mpTestContext; +}; +TestContext * TestBufferedReadCallback::mpTestContext = nullptr; + class DataSeriesValidator : public BufferedReadCallback::Callback { public: @@ -117,12 +149,12 @@ void DataSeriesValidator::OnAttributeData(const ConcreteDataAttributePath & aPat ChipLogProgress(DataManagement, "\t\t -- Validating A"); Clusters::UnitTesting::Attributes::Int8u::TypeInfo::Type value; - NL_TEST_ASSERT(gSuite, - aPath.mEndpointId == 0 && aPath.mClusterId == Clusters::UnitTesting::Id && - aPath.mAttributeId == Clusters::UnitTesting::Attributes::Int8u::Id && - aPath.mListOp == ConcreteDataAttributePath::ListOperation::NotList); - NL_TEST_ASSERT(gSuite, DataModel::Decode(*apData, value) == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, value == mCurrentInstruction); + EXPECT_EQ(aPath.mEndpointId, 0u); + EXPECT_EQ(aPath.mClusterId, Clusters::UnitTesting::Id); + EXPECT_EQ(aPath.mAttributeId, Clusters::UnitTesting::Attributes::Int8u::Id); + EXPECT_EQ(aPath.mListOp, ConcreteDataAttributePath::ListOperation::NotList); + EXPECT_EQ(DataModel::Decode(*apData, value), CHIP_NO_ERROR); + EXPECT_EQ(value, mCurrentInstruction); break; } @@ -130,12 +162,12 @@ void DataSeriesValidator::OnAttributeData(const ConcreteDataAttributePath & aPat ChipLogProgress(DataManagement, "\t\t -- Validating B"); Clusters::UnitTesting::Attributes::Int32u::TypeInfo::Type value; - NL_TEST_ASSERT(gSuite, - aPath.mEndpointId == 0 && aPath.mClusterId == Clusters::UnitTesting::Id && - aPath.mAttributeId == Clusters::UnitTesting::Attributes::Int32u::Id && - aPath.mListOp == ConcreteDataAttributePath::ListOperation::NotList); - NL_TEST_ASSERT(gSuite, DataModel::Decode(*apData, value) == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, value == mCurrentInstruction); + EXPECT_EQ(aPath.mEndpointId, 0u); + EXPECT_EQ(aPath.mClusterId, Clusters::UnitTesting::Id); + EXPECT_EQ(aPath.mAttributeId, Clusters::UnitTesting::Attributes::Int32u::Id); + EXPECT_EQ(aPath.mListOp, ConcreteDataAttributePath::ListOperation::NotList); + EXPECT_EQ(DataModel::Decode(*apData, value), CHIP_NO_ERROR); + EXPECT_EQ(value, mCurrentInstruction); break; } @@ -145,13 +177,13 @@ void DataSeriesValidator::OnAttributeData(const ConcreteDataAttributePath & aPat Clusters::UnitTesting::Attributes::ListStructOctetString::TypeInfo::DecodableType value; size_t len; - NL_TEST_ASSERT(gSuite, - aPath.mEndpointId == 0 && aPath.mClusterId == Clusters::UnitTesting::Id && - aPath.mAttributeId == Clusters::UnitTesting::Attributes::ListStructOctetString::Id && - aPath.mListOp == ConcreteDataAttributePath::ListOperation::ReplaceAll); - NL_TEST_ASSERT(gSuite, DataModel::Decode(*apData, value) == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, value.ComputeSize(&len) == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, len == 0); + EXPECT_EQ(aPath.mEndpointId, 0u); + EXPECT_EQ(aPath.mClusterId, Clusters::UnitTesting::Id); + EXPECT_EQ(aPath.mAttributeId, Clusters::UnitTesting::Attributes::ListStructOctetString::Id); + EXPECT_EQ(aPath.mListOp, ConcreteDataAttributePath::ListOperation::ReplaceAll); + EXPECT_EQ(DataModel::Decode(*apData, value), CHIP_NO_ERROR); + EXPECT_EQ(value.ComputeSize(&len), CHIP_NO_ERROR); + EXPECT_EQ(len, 0u); break; } @@ -172,13 +204,13 @@ void DataSeriesValidator::OnAttributeData(const ConcreteDataAttributePath & aPat Clusters::UnitTesting::Attributes::ListStructOctetString::TypeInfo::DecodableType value; size_t len; - NL_TEST_ASSERT(gSuite, - aPath.mEndpointId == 0 && aPath.mClusterId == Clusters::UnitTesting::Id && - aPath.mAttributeId == Clusters::UnitTesting::Attributes::ListStructOctetString::Id && - aPath.mListOp == ConcreteDataAttributePath::ListOperation::ReplaceAll); - NL_TEST_ASSERT(gSuite, DataModel::Decode(*apData, value) == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, value.ComputeSize(&len) == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, len == expectedListLength); + EXPECT_EQ(aPath.mEndpointId, 0u); + EXPECT_EQ(aPath.mClusterId, Clusters::UnitTesting::Id); + EXPECT_EQ(aPath.mAttributeId, Clusters::UnitTesting::Attributes::ListStructOctetString::Id); + EXPECT_EQ(aPath.mListOp, ConcreteDataAttributePath::ListOperation::ReplaceAll); + EXPECT_EQ(DataModel::Decode(*apData, value), CHIP_NO_ERROR); + EXPECT_EQ(value.ComputeSize(&len), CHIP_NO_ERROR); + EXPECT_EQ(len, expectedListLength); auto iter = value.begin(); @@ -186,11 +218,11 @@ void DataSeriesValidator::OnAttributeData(const ConcreteDataAttributePath & aPat while (iter.Next() && index < expectedListLength) { auto & iterValue = iter.GetValue(); - NL_TEST_ASSERT(gSuite, iterValue.member1 == (index)); + EXPECT_EQ(iterValue.member1, (index)); index++; } - NL_TEST_ASSERT(gSuite, iter.GetStatus() == CHIP_NO_ERROR); + EXPECT_EQ(iter.GetStatus(), CHIP_NO_ERROR); break; } @@ -200,13 +232,13 @@ void DataSeriesValidator::OnAttributeData(const ConcreteDataAttributePath & aPat Clusters::UnitTesting::Attributes::ListInt8u::TypeInfo::DecodableType value; size_t len; - NL_TEST_ASSERT(gSuite, - aPath.mEndpointId == 0 && aPath.mClusterId == Clusters::UnitTesting::Id && - aPath.mAttributeId == Clusters::UnitTesting::Attributes::ListInt8u::Id && - aPath.mListOp == ConcreteDataAttributePath::ListOperation::ReplaceAll); - NL_TEST_ASSERT(gSuite, DataModel::Decode(*apData, value) == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, value.ComputeSize(&len) == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, len == 0); + EXPECT_EQ(aPath.mEndpointId, 0u); + EXPECT_EQ(aPath.mClusterId, Clusters::UnitTesting::Id); + EXPECT_EQ(aPath.mAttributeId, Clusters::UnitTesting::Attributes::ListInt8u::Id); + EXPECT_EQ(aPath.mListOp, ConcreteDataAttributePath::ListOperation::ReplaceAll); + EXPECT_EQ(DataModel::Decode(*apData, value), CHIP_NO_ERROR); + EXPECT_EQ(value.ComputeSize(&len), CHIP_NO_ERROR); + EXPECT_EQ(len, 0u); break; } @@ -226,14 +258,13 @@ void DataSeriesValidator::OnAttributeData(const ConcreteDataAttributePath & aPat Clusters::UnitTesting::Attributes::ListInt8u::TypeInfo::DecodableType value; size_t len; - - NL_TEST_ASSERT(gSuite, - aPath.mEndpointId == 0 && aPath.mClusterId == Clusters::UnitTesting::Id && - aPath.mAttributeId == Clusters::UnitTesting::Attributes::ListInt8u::Id && - aPath.mListOp == ConcreteDataAttributePath::ListOperation::ReplaceAll); - NL_TEST_ASSERT(gSuite, DataModel::Decode(*apData, value) == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, value.ComputeSize(&len) == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, len == expectedListLength); + EXPECT_EQ(aPath.mEndpointId, 0u); + EXPECT_EQ(aPath.mClusterId, Clusters::UnitTesting::Id); + EXPECT_EQ(aPath.mAttributeId, Clusters::UnitTesting::Attributes::ListInt8u::Id); + EXPECT_EQ(aPath.mListOp, ConcreteDataAttributePath::ListOperation::ReplaceAll); + EXPECT_EQ(DataModel::Decode(*apData, value), CHIP_NO_ERROR); + EXPECT_EQ(value.ComputeSize(&len), CHIP_NO_ERROR); + EXPECT_EQ(len, expectedListLength); auto iter = value.begin(); @@ -241,33 +272,33 @@ void DataSeriesValidator::OnAttributeData(const ConcreteDataAttributePath & aPat while (iter.Next() && index < expectedListLength) { auto & iterValue = iter.GetValue(); - NL_TEST_ASSERT(gSuite, iterValue == (index)); + EXPECT_EQ(iterValue, (index)); index++; } - NL_TEST_ASSERT(gSuite, iter.GetStatus() == CHIP_NO_ERROR); + EXPECT_EQ(iter.GetStatus(), CHIP_NO_ERROR); break; } case ValidationInstruction::kListAttributeC_Error: { ChipLogProgress(DataManagement, "\t\t -- Validating C|e"); - NL_TEST_ASSERT(gSuite, - aPath.mEndpointId == 0 && aPath.mClusterId == Clusters::UnitTesting::Id && - aPath.mAttributeId == Clusters::UnitTesting::Attributes::ListStructOctetString::Id && - aPath.mListOp == ConcreteDataAttributePath::ListOperation::ReplaceAll); - NL_TEST_ASSERT(gSuite, aStatus.mStatus == Protocols::InteractionModel::Status::Failure); + EXPECT_EQ(aPath.mEndpointId, 0u); + EXPECT_EQ(aPath.mClusterId, Clusters::UnitTesting::Id); + EXPECT_EQ(aPath.mAttributeId, Clusters::UnitTesting::Attributes::ListStructOctetString::Id); + EXPECT_EQ(aPath.mListOp, ConcreteDataAttributePath::ListOperation::ReplaceAll); + EXPECT_EQ(aStatus.mStatus, Protocols::InteractionModel::Status::Failure); break; } case ValidationInstruction::kListAttributeD_Error: { ChipLogProgress(DataManagement, "\t\t -- Validating D|e"); - NL_TEST_ASSERT(gSuite, - aPath.mEndpointId == 0 && aPath.mClusterId == Clusters::UnitTesting::Id && - aPath.mAttributeId == Clusters::UnitTesting::Attributes::ListInt8u::Id && - aPath.mListOp == ConcreteDataAttributePath::ListOperation::ReplaceAll); - NL_TEST_ASSERT(gSuite, aStatus.mStatus == Protocols::InteractionModel::Status::Failure); + EXPECT_EQ(aPath.mEndpointId, 0u); + EXPECT_EQ(aPath.mClusterId, Clusters::UnitTesting::Id); + EXPECT_EQ(aPath.mAttributeId, Clusters::UnitTesting::Attributes::ListInt8u::Id); + EXPECT_EQ(aPath.mListOp, ConcreteDataAttributePath::ListOperation::ReplaceAll); + EXPECT_EQ(aStatus.mStatus, Protocols::InteractionModel::Status::Failure); break; } @@ -321,7 +352,7 @@ void DataSeriesGenerator::Generate() Clusters::UnitTesting::Attributes::Int8u::TypeInfo::Type value = index; path.mAttributeId = Clusters::UnitTesting::Attributes::Int8u::Id; path.mListOp = ConcreteDataAttributePath::ListOperation::NotList; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), value) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), value), CHIP_NO_ERROR); break; } @@ -331,7 +362,7 @@ void DataSeriesGenerator::Generate() Clusters::UnitTesting::Attributes::Int32u::TypeInfo::Type value = index; path.mAttributeId = Clusters::UnitTesting::Attributes::Int32u::Id; path.mListOp = ConcreteDataAttributePath::ListOperation::NotList; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), value) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), value), CHIP_NO_ERROR); break; } @@ -341,7 +372,7 @@ void DataSeriesGenerator::Generate() Clusters::UnitTesting::Attributes::ListStructOctetString::TypeInfo::Type value; path.mAttributeId = Clusters::UnitTesting::Attributes::ListStructOctetString::Id; path.mListOp = ConcreteDataAttributePath::ListOperation::ReplaceAll; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), value) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), value), CHIP_NO_ERROR); break; } @@ -361,7 +392,7 @@ void DataSeriesGenerator::Generate() path.mAttributeId = Clusters::UnitTesting::Attributes::ListStructOctetString::Id; path.mListOp = ConcreteDataAttributePath::ListOperation::ReplaceAll; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), value) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), value), CHIP_NO_ERROR); break; } @@ -371,7 +402,7 @@ void DataSeriesGenerator::Generate() Clusters::UnitTesting::Attributes::ListInt8u::TypeInfo::Type value; path.mAttributeId = Clusters::UnitTesting::Attributes::ListInt8u::Id; path.mListOp = ConcreteDataAttributePath::ListOperation::ReplaceAll; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), value) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), value), CHIP_NO_ERROR); break; } @@ -391,7 +422,7 @@ void DataSeriesGenerator::Generate() path.mAttributeId = Clusters::UnitTesting::Attributes::ListInt8u::Id; path.mListOp = ConcreteDataAttributePath::ListOperation::ReplaceAll; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), value) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), value), CHIP_NO_ERROR); break; } @@ -426,11 +457,11 @@ void DataSeriesGenerator::Generate() path.mAttributeId = Clusters::UnitTesting::Attributes::ListStructOctetString::Id; path.mListOp = ConcreteDataAttributePath::ListOperation::ReplaceAll; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), value) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), value), CHIP_NO_ERROR); writer.Finalize(&handle); reader.Init(std::move(handle)); - NL_TEST_ASSERT(gSuite, reader.Next() == CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(), CHIP_NO_ERROR); callback->OnAttributeData(path, &reader, status); } @@ -449,11 +480,11 @@ void DataSeriesGenerator::Generate() listItem.member1 = (uint64_t) i; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), listItem) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), listItem), CHIP_NO_ERROR); writer.Finalize(&handle); reader.Init(std::move(handle)); - NL_TEST_ASSERT(gSuite, reader.Next() == CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(), CHIP_NO_ERROR); callback->OnAttributeData(path, &reader, status); } @@ -469,11 +500,11 @@ void DataSeriesGenerator::Generate() path.mAttributeId = Clusters::UnitTesting::Attributes::ListInt8u::Id; path.mListOp = ConcreteDataAttributePath::ListOperation::ReplaceAll; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), value) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), value), CHIP_NO_ERROR); writer.Finalize(&handle); reader.Init(std::move(handle)); - NL_TEST_ASSERT(gSuite, reader.Next() == CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(), CHIP_NO_ERROR); callback->OnAttributeData(path, &reader, status); } @@ -488,11 +519,11 @@ void DataSeriesGenerator::Generate() path.mAttributeId = Clusters::UnitTesting::Attributes::ListInt8u::Id; path.mListOp = ConcreteDataAttributePath::ListOperation::AppendItem; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), (uint8_t) (i)) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), (uint8_t) (i)), CHIP_NO_ERROR); writer.Finalize(&handle); reader.Init(std::move(handle)); - NL_TEST_ASSERT(gSuite, reader.Next() == CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(), CHIP_NO_ERROR); callback->OnAttributeData(path, &reader, status); } @@ -507,7 +538,7 @@ void DataSeriesGenerator::Generate() { writer.Finalize(&handle); reader.Init(std::move(handle)); - NL_TEST_ASSERT(gSuite, reader.Next() == CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(), CHIP_NO_ERROR); callback->OnAttributeData(path, &reader, status); } @@ -524,10 +555,10 @@ void RunAndValidateSequence(std::vector instructionList) DataSeriesGenerator generator(bufferedCallback, instructionList); generator.Generate(); - NL_TEST_ASSERT(gSuite, validator.mCurrentInstruction == instructionList.size()); + EXPECT_EQ(validator.mCurrentInstruction, instructionList.size()); } -void TestBufferedSequences(nlTestSuite * apSuite, void * apContext) +TEST_F(TestBufferedReadCallback, TestBufferedSequences) { ChipLogProgress(DataManagement, "Validating various sequences of attribute data IBs..."); @@ -599,30 +630,4 @@ void TestBufferedSequences(nlTestSuite * apSuite, void * apContext) }); } -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("TestBufferedSequences", TestBufferedSequences), - NL_TEST_SENTINEL() -}; - -nlTestSuite theSuite = -{ - "TestBufferedReadCallback", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; - -} -// clang-format on - -int TestBufferedReadCallback() -{ - gSuite = &theSuite; - return chip::ExecuteTestsWithContext(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestBufferedReadCallback) +} // namespace diff --git a/src/app/tests/TestClusterStateCache.cpp b/src/app/tests/TestClusterStateCache.cpp index 3247af55bccd03..b4f41df2278b14 100644 --- a/src/app/tests/TestClusterStateCache.cpp +++ b/src/app/tests/TestClusterStateCache.cpp @@ -16,6 +16,9 @@ * limitations under the License. */ +#include +#include + #include "app-common/zap-generated/ids/Attributes.h" #include "app-common/zap-generated/ids/Clusters.h" #include "lib/core/TLVTags.h" @@ -30,11 +33,9 @@ #include #include #include -#include -#include -#include -#include -#include + +#include +#include using TestContext = chip::Test::AppContext; using namespace chip::app; @@ -42,8 +43,6 @@ using namespace chip; namespace { -nlTestSuite * gSuite = nullptr; - struct AttributeInstruction { enum AttributeType @@ -109,6 +108,27 @@ uint8_t AttributeInstruction::sInstructionId = 0; using AttributeInstructionListType = std::vector; +class TestClusterStateCache : public ::testing::Test +{ +public: + static void SetUpTestSuite() + { + mpTestContext = new TestContext; + mpTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + delete mpTestContext; + } + + void SetUp() override { mpTestContext->SetUp(); } + void TearDown() override { mpTestContext->TearDown(); } + + static TestContext * mpTestContext; +}; +TestContext * TestClusterStateCache::mpTestContext = nullptr; + class ForwardedDataCallbackValidator final { public: @@ -130,7 +150,7 @@ class ForwardedDataCallbackValidator final void ValidateData(TLV::TLVReader & aData, bool isListOperation) { - NL_TEST_ASSERT(gSuite, !mExpectedBuffers.empty()); + EXPECT_FALSE(mExpectedBuffers.empty()); if (!mExpectedBuffers.empty() > 0) { auto buffer = mExpectedBuffers.front(); @@ -139,15 +159,15 @@ class ForwardedDataCallbackValidator final if (isListOperation) { // List operation will attach end of container - NL_TEST_ASSERT(gSuite, length < aData.GetRemainingLength()); + EXPECT_LT(length, aData.GetRemainingLength()); } else { - NL_TEST_ASSERT(gSuite, length == aData.GetRemainingLength()); + EXPECT_EQ(length, aData.GetRemainingLength()); } if (length <= aData.GetRemainingLength() && length > 0) { - NL_TEST_ASSERT(gSuite, memcmp(aData.GetReadPoint(), buffer.data(), length) == 0); + EXPECT_EQ(memcmp(aData.GetReadPoint(), buffer.data(), length), 0); if (memcmp(aData.GetReadPoint(), buffer.data(), length) != 0) { ChipLogProgress(DataManagement, "Failed"); @@ -156,7 +176,7 @@ class ForwardedDataCallbackValidator final } } - void ValidateNoData() { NL_TEST_ASSERT(gSuite, mExpectedBuffers.empty()); } + void ValidateNoData() { EXPECT_TRUE(mExpectedBuffers.empty()); } private: std::vector> mExpectedBuffers; @@ -205,7 +225,7 @@ void DataSeriesGenerator::Generate(ForwardedDataCallbackValidator & dataCallback ChipLogProgress(DataManagement, "\t -- Generating A"); Clusters::UnitTesting::Attributes::Int16u::TypeInfo::Type value = instruction.mInstructionId; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), value) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), value), CHIP_NO_ERROR); break; } @@ -216,7 +236,7 @@ void DataSeriesGenerator::Generate(ForwardedDataCallbackValidator & dataCallback uint8_t buf[] = { 'h', 'e', 'l', 'l', 'o' }; value = buf; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), value) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), value), CHIP_NO_ERROR); break; } @@ -226,7 +246,7 @@ void DataSeriesGenerator::Generate(ForwardedDataCallbackValidator & dataCallback Clusters::UnitTesting::Attributes::StructAttr::TypeInfo::Type value; value.a = instruction.mInstructionId; value.b = true; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), value) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), value), CHIP_NO_ERROR); break; } @@ -245,7 +265,7 @@ void DataSeriesGenerator::Generate(ForwardedDataCallbackValidator & dataCallback path.mListOp = ConcreteDataAttributePath::ListOperation::ReplaceAll; value = buf; - NL_TEST_ASSERT(gSuite, DataModel::Encode(writer, TLV::AnonymousTag(), value) == CHIP_NO_ERROR); + EXPECT_EQ(DataModel::Encode(writer, TLV::AnonymousTag(), value), CHIP_NO_ERROR); break; } @@ -257,7 +277,7 @@ void DataSeriesGenerator::Generate(ForwardedDataCallbackValidator & dataCallback writer.Finalize(handle); TLV::ScopedBufferTLVReader reader; reader.Init(std::move(handle), writtenLength); - NL_TEST_ASSERT(gSuite, reader.Next() == CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(), CHIP_NO_ERROR); dataCallbackValidator.SetExpectation(reader, instruction.mEndpointId, instruction.mAttributeType); callback->OnAttributeData(path, &reader, status); } @@ -287,12 +307,12 @@ class CacheValidator : public ClusterStateCache::Callback ChipLogProgress(DataManagement, "\t\t -- Validating OnAttributeData callback"); // Ensure that the provided path is one that we're expecting to find auto iter = mExpectedAttributes.find(aPath); - NL_TEST_ASSERT(gSuite, iter != mExpectedAttributes.end()); + ASSERT_NE(iter, mExpectedAttributes.end()); if (aStatus.IsSuccess()) { // Verify that the apData is passed as nonnull - NL_TEST_ASSERT(gSuite, apData != nullptr); + ASSERT_NE(apData, nullptr); if (apData) { mDataCallbackValidator.ValidateData(*apData, aPath.IsListOperation()); @@ -325,8 +345,8 @@ class CacheValidator : public ClusterStateCache::Callback } else { - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, v == instruction.mInstructionId); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(v, instruction.mInstructionId); } break; @@ -344,8 +364,8 @@ class CacheValidator : public ClusterStateCache::Callback } else { - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, strncmp((char *) v.data(), "hello", v.size()) == 0); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(strncmp((char *) v.data(), "hello", v.size()), 0); } break; @@ -363,8 +383,8 @@ class CacheValidator : public ClusterStateCache::Callback } else { - NL_TEST_ASSERT(gSuite, v.a == instruction.mInstructionId); - NL_TEST_ASSERT(gSuite, v.b == true); + EXPECT_EQ(v.a, instruction.mInstructionId); + EXPECT_TRUE(v.b); } break; @@ -385,22 +405,22 @@ class CacheValidator : public ClusterStateCache::Callback auto listIter = v.begin(); while (listIter.Next()) { - NL_TEST_ASSERT(gSuite, listIter.GetValue().member1 == instruction.mInstructionId); + EXPECT_EQ(listIter.GetValue().member1, instruction.mInstructionId); } - NL_TEST_ASSERT(gSuite, listIter.GetStatus() == CHIP_NO_ERROR); + EXPECT_EQ(listIter.GetStatus(), CHIP_NO_ERROR); } break; } } - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); if (gotStatus) { ChipLogProgress(DataManagement, "\t\t -- Validating status"); - NL_TEST_ASSERT(gSuite, instruction.mValueType == AttributeInstruction::kStatus); + EXPECT_EQ(instruction.mValueType, AttributeInstruction::kStatus); } } @@ -408,29 +428,28 @@ class CacheValidator : public ClusterStateCache::Callback ClusterStateCache * cache) { std::list statusList; - NL_TEST_ASSERT(gSuite, cache->Get(path.mEndpointId, path.mClusterId, clusterValue, statusList) == CHIP_NO_ERROR); + EXPECT_EQ(cache->Get(path.mEndpointId, path.mClusterId, clusterValue, statusList), CHIP_NO_ERROR); if (instruction.mValueType == AttributeInstruction::kData) { - NL_TEST_ASSERT(gSuite, statusList.size() == 0); + EXPECT_EQ(statusList.size(), 0u); switch (instruction.mAttributeType) { case AttributeInstruction::kAttributeA: ChipLogProgress(DataManagement, "\t\t -- Validating A (Cluster Obj)"); - NL_TEST_ASSERT(gSuite, clusterValue.int16u == instruction.mInstructionId); + EXPECT_EQ(clusterValue.int16u, instruction.mInstructionId); break; case AttributeInstruction::kAttributeB: ChipLogProgress(DataManagement, "\t\t -- Validating B (Cluster Obj)"); - NL_TEST_ASSERT(gSuite, - strncmp((char *) clusterValue.octetString.data(), "hello", clusterValue.octetString.size()) == 0); + EXPECT_EQ(strncmp((char *) clusterValue.octetString.data(), "hello", clusterValue.octetString.size()), 0); break; case AttributeInstruction::kAttributeC: ChipLogProgress(DataManagement, "\t\t -- Validating C (Cluster Obj)"); - NL_TEST_ASSERT(gSuite, clusterValue.structAttr.a == instruction.mInstructionId); - NL_TEST_ASSERT(gSuite, clusterValue.structAttr.b == true); + EXPECT_EQ(clusterValue.structAttr.a, instruction.mInstructionId); + EXPECT_TRUE(clusterValue.structAttr.b); break; case AttributeInstruction::kAttributeD: @@ -439,22 +458,22 @@ class CacheValidator : public ClusterStateCache::Callback auto listIter = clusterValue.listStructOctetString.begin(); while (listIter.Next()) { - NL_TEST_ASSERT(gSuite, listIter.GetValue().member1 == instruction.mInstructionId); + EXPECT_EQ(listIter.GetValue().member1, instruction.mInstructionId); } - NL_TEST_ASSERT(gSuite, listIter.GetStatus() == CHIP_NO_ERROR); + EXPECT_EQ(listIter.GetStatus(), CHIP_NO_ERROR); break; } } else { - NL_TEST_ASSERT(gSuite, statusList.size() == 1); + EXPECT_EQ(statusList.size(), 1u); auto status = statusList.front(); - NL_TEST_ASSERT(gSuite, status.mPath.mEndpointId == instruction.mEndpointId); - NL_TEST_ASSERT(gSuite, status.mPath.mClusterId == Clusters::UnitTesting::Id); - NL_TEST_ASSERT(gSuite, status.mPath.mAttributeId == instruction.GetAttributeId()); - NL_TEST_ASSERT(gSuite, status.mStatus.mStatus == Protocols::InteractionModel::Status::Failure); + EXPECT_EQ(status.mPath.mEndpointId, instruction.mEndpointId); + EXPECT_EQ(status.mPath.mClusterId, Clusters::UnitTesting::Id); + EXPECT_EQ(status.mPath.mAttributeId, instruction.GetAttributeId()); + EXPECT_EQ(status.mStatus.mStatus, Protocols::InteractionModel::Status::Failure); } } @@ -464,7 +483,7 @@ class CacheValidator : public ClusterStateCache::Callback // Ensure that the provided path is one that we're expecting to find auto iter = mExpectedAttributes.find(path); - NL_TEST_ASSERT(gSuite, iter != mExpectedAttributes.end()); + ASSERT_NE(iter, mExpectedAttributes.end()); // Once retrieved, let's erase it from the expected set so that we can catch duplicates coming back // as well as validating that we've seen all attributes at the end. @@ -489,22 +508,22 @@ class CacheValidator : public ClusterStateCache::Callback void OnClusterChanged(ClusterStateCache * cache, EndpointId endpointId, ClusterId clusterId) override { auto iter = mExpectedClusters.find(std::make_tuple(endpointId, clusterId)); - NL_TEST_ASSERT(gSuite, iter != mExpectedClusters.end()); + ASSERT_NE(iter, mExpectedClusters.end()); mExpectedClusters.erase(iter); } void OnEndpointAdded(ClusterStateCache * cache, EndpointId endpointId) override { auto iter = mExpectedEndpoints.find(endpointId); - NL_TEST_ASSERT(gSuite, iter != mExpectedEndpoints.end()); + ASSERT_NE(iter, mExpectedEndpoints.end()); mExpectedEndpoints.erase(iter); } void OnReportEnd() override { - NL_TEST_ASSERT(gSuite, mExpectedAttributes.size() == 0); - NL_TEST_ASSERT(gSuite, mExpectedClusters.size() == 0); - NL_TEST_ASSERT(gSuite, mExpectedEndpoints.size() == 0); + EXPECT_EQ(mExpectedAttributes.size(), 0u); + EXPECT_EQ(mExpectedClusters.size(), 0u); + EXPECT_EQ(mExpectedEndpoints.size(), 0u); } // @@ -556,14 +575,13 @@ void RunAndValidateSequence(AttributeInstructionListType list) TLV::TLVWriter writer; writer.Init(buf); DataVersionFilterIBs::Builder builder; - CHIP_ERROR err = builder.Init(&writer); - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(builder.Init(&writer), CHIP_NO_ERROR); bool encodedDataVersionList = false; - err = cache.GetBufferedCallback().OnUpdateDataVersionFilterList(builder, pathSpan, encodedDataVersionList); // We had nothing to encode so far. - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, !encodedDataVersionList); + EXPECT_EQ(cache.GetBufferedCallback().OnUpdateDataVersionFilterList(builder, pathSpan, encodedDataVersionList), + CHIP_NO_ERROR); + EXPECT_FALSE(encodedDataVersionList); } DataSeriesGenerator generator(&cache.GetBufferedCallback(), list); @@ -576,28 +594,24 @@ void RunAndValidateSequence(AttributeInstructionListType list) do { Platform::ScopedMemoryBuffer buf; - if (!buf.Calloc(bufferSize)) - { - NL_TEST_ASSERT(gSuite, false); - break; - } + ASSERT_TRUE(buf.Calloc(bufferSize)); TLV::TLVWriter writer; writer.Init(buf.Get(), bufferSize); DataVersionFilterIBs::Builder builder; CHIP_ERROR err = builder.Init(&writer); - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR || err == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_TRUE(err == CHIP_NO_ERROR || err == CHIP_ERROR_BUFFER_TOO_SMALL); if (err == CHIP_NO_ERROR) { // We had enough space to start the list. Now try encoding the data // version filters. bool encodedDataVersionList = false; - err = cache.GetBufferedCallback().OnUpdateDataVersionFilterList(builder, pathSpan, encodedDataVersionList); // We should be rolling back properly if we run out of space. - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, builder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(cache.GetBufferedCallback().OnUpdateDataVersionFilterList(builder, pathSpan, encodedDataVersionList), + CHIP_NO_ERROR); + EXPECT_EQ(builder.GetError(), CHIP_NO_ERROR); if (writer.GetRemainingFreeLength() > 40) { @@ -625,7 +639,7 @@ void RunAndValidateSequence(AttributeInstructionListType list) * E1:A1 --- Endpoint 1, Attribute A, Version 1 * */ -void TestCache(nlTestSuite * apSuite, void * apContext) +TEST_F(TestClusterStateCache, TestCache) { ChipLogProgress(DataManagement, "Validating various sequences of attribute data IBs..."); @@ -684,30 +698,4 @@ void TestCache(nlTestSuite * apSuite, void * apContext) AttributeInstruction(AttributeInstruction::kAttributeB, 0, AttributeInstruction::kData) }); } -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("TestCache", TestCache), - NL_TEST_SENTINEL() -}; - -nlTestSuite theSuite = -{ - "TestClusterStateCache", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; - -} -// clang-format on - -int TestClusterStateCache() -{ - gSuite = &theSuite; - return chip::ExecuteTestsWithContext(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestClusterStateCache) +} // namespace diff --git a/src/app/tests/TestCommandInteraction.cpp b/src/app/tests/TestCommandInteraction.cpp index 2a5791ba839423..22c7ccc1a9e9b4 100644 --- a/src/app/tests/TestCommandInteraction.cpp +++ b/src/app/tests/TestCommandInteraction.cpp @@ -23,46 +23,45 @@ */ #include +#include + +#include +#include #include #include #include #include #include +#include #include #include #include #include #include #include -#include -#include #include +#include #include #include #include -#include #include #include #include #include -#include - using TestContext = chip::Test::AppContext; using namespace chip::Protocols; namespace { -void CheckForInvalidAction(nlTestSuite * apSuite, chip::Test::MessageCapturer & messageLog) +void CheckForInvalidAction(chip::Test::MessageCapturer & messageLog) { - NL_TEST_ASSERT(apSuite, messageLog.MessageCount() == 1); - NL_TEST_ASSERT(apSuite, messageLog.IsMessageType(0, chip::Protocols::InteractionModel::MsgType::StatusResponse)); + EXPECT_EQ(messageLog.MessageCount(), 1u); + EXPECT_TRUE(messageLog.IsMessageType(0, chip::Protocols::InteractionModel::MsgType::StatusResponse)); CHIP_ERROR status; - NL_TEST_ASSERT(apSuite, - chip::app::StatusResponse::ProcessStatusResponse(std::move(messageLog.MessagePayload(0)), status) == - CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, status == CHIP_IM_GLOBAL_STATUS(InvalidAction)); + EXPECT_EQ(chip::app::StatusResponse::ProcessStatusResponse(std::move(messageLog.MessagePayload(0)), status), CHIP_NO_ERROR); + EXPECT_EQ(status, CHIP_IM_GLOBAL_STATUS(InvalidAction)); } } // anonymous namespace @@ -76,9 +75,6 @@ size_t commandDispatchedCount = 0; bool sendResponse = true; bool asyncCommand = false; -// Allow us to do test asserts from arbitrary places. -nlTestSuite * gSuite = nullptr; - constexpr EndpointId kTestEndpointId = 1; constexpr ClusterId kTestClusterId = 3; constexpr CommandId kTestCommandIdWithData = 4; @@ -92,12 +88,12 @@ const app::CommandSender::TestOnlyMarker kCommandSenderTestOnlyMarker; class SimpleTLVPayload : public app::DataModel::EncodableToTLV { public: - CHIP_ERROR EncodeTo(TLV::TLVWriter & writer, TLV::Tag tag) const override + CHIP_ERROR EncodeTo(TLV::TLVWriter & aWriter, TLV::Tag aTag) const override { TLV::TLVType outerType; - ReturnErrorOnFailure(writer.StartContainer(tag, TLV::kTLVType_Structure, outerType)); - ReturnErrorOnFailure(writer.PutBoolean(chip::TLV::ContextTag(1), true)); - return writer.EndContainer(outerType); + ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outerType)); + ReturnErrorOnFailure(aWriter.PutBoolean(chip::TLV::ContextTag(1), true)); + return aWriter.EndContainer(outerType); } }; @@ -107,6 +103,12 @@ namespace app { CommandHandler::Handle asyncCommandHandle; +enum class ForcedSizeBufferLengthHint +{ + kSizeBetween0and255, + kSizeGreaterThan255, +}; + struct ForcedSizeBuffer { chip::Platform::ScopedMemoryBufferWithSize mBuffer; @@ -133,10 +135,33 @@ struct ForcedSizeBuffer } }; -enum class ForcedSizeBufferLengthHint +struct Fields { - kSizeBetween0and255, - kSizeGreaterThan255, + static constexpr chip::CommandId GetCommandId() { return 4; } + CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const + { + TLV::TLVType outerContainerType; + ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outerContainerType)); + ReturnErrorOnFailure(aWriter.PutBoolean(TLV::ContextTag(1), true)); + return aWriter.EndContainer(outerContainerType); + } +}; + +struct BadFields +{ + static constexpr chip::CommandId GetCommandId() { return 4; } + CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const + { + TLV::TLVType outerContainerType; + uint8_t data[36] = { 0 }; + ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outerContainerType)); + // Just encode something bad to return a failure state here. + for (uint8_t i = 1; i < UINT8_MAX; i++) + { + ReturnErrorOnFailure(app::DataModel::Encode(aWriter, TLV::ContextTag(i), ByteSpan(data))); + } + return aWriter.EndContainer(outerContainerType); + } }; InteractionModel::Status ServerClusterCommandExists(const ConcreteCommandPath & aRequestCommandPath) @@ -178,26 +203,24 @@ void DispatchSingleClusterCommand(const ConcreteCommandPath & aRequestCommandPat } TLV::TLVType outerContainerType; - CHIP_ERROR err = aReader.EnterContainer(outerContainerType); - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(aReader.EnterContainer(outerContainerType), CHIP_NO_ERROR); - err = aReader.Next(); + CHIP_ERROR err = aReader.Next(); if (aRequestCommandPath.mCommandId == kTestCommandIdNoData) { - NL_TEST_ASSERT(gSuite, err == CHIP_ERROR_END_OF_TLV); + EXPECT_EQ(err, CHIP_ERROR_END_OF_TLV); } else { - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, aReader.GetTag() == TLV::ContextTag(1)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(aReader.GetTag(), TLV::ContextTag(1)); + bool val; - err = aReader.Get(val); - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(gSuite, val); + EXPECT_EQ(aReader.Get(val), CHIP_NO_ERROR); + EXPECT_TRUE(val); } - err = aReader.ExitContainer(outerContainerType); - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(aReader.ExitContainer(outerContainerType), CHIP_NO_ERROR); if (asyncCommand) { @@ -330,66 +353,49 @@ class MockCommandHandlerCallback : public CommandHandlerImpl::Callback int onFinalCalledTimes = 0; } mockCommandHandlerDelegate; -class TestCommandInteraction +class TestCommandInteraction : public ::testing::Test { public: - static void TestCommandSenderWithWrongState(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerWithWrongState(nlTestSuite * apSuite, void * apContext); - static void TestCommandSenderWithSendCommand(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerWithSendEmptyCommand(nlTestSuite * apSuite, void * apContext); - static void TestCommandSenderWithProcessReceivedMsg(nlTestSuite * apSuite, void * apContext); - static void TestCommandSenderExtendableApiWithProcessReceivedMsg(nlTestSuite * apSuite, void * apContext); - static void TestCommandSenderExtendableApiWithProcessReceivedMsgContainingInvalidCommandRef(nlTestSuite * apSuite, - void * apContext); - static void TestCommandHandlerWithOnInvokeReceivedNotExistCommand(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerEncodeSimpleCommandData(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerCommandDataEncoding(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerCommandEncodeFailure(nlTestSuite * apSuite, void * apContext); - static void TestCommandInvalidMessage1(nlTestSuite * apSuite, void * apContext); - static void TestCommandInvalidMessage2(nlTestSuite * apSuite, void * apContext); - static void TestCommandInvalidMessage3(nlTestSuite * apSuite, void * apContext); - static void TestCommandInvalidMessage4(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerInvalidMessageSync(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerCommandEncodeExternalFailure(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerEncodeSimpleStatusCode(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerWithoutResponderCallingAddStatus(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerWithoutResponderCallingAddResponse(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerWithoutResponderCallingDirectPrepareFinishCommandApis(nlTestSuite * apSuite, void * apContext); - - static void TestCommandHandlerWithOnInvokeReceivedEmptyDataMsg(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerRejectMultipleIdenticalCommands(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerRejectsMultipleCommandsWithIdenticalCommandRef(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerRejectMultipleCommandsWhenHandlerOnlySupportsOne(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandlerAcceptMultipleCommands(nlTestSuite * apSuite, void * apContext); - static void TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsStatusResponse(nlTestSuite * apSuite, - void * apContext); - static void TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponsePrimative(nlTestSuite * apSuite, - void * apContext); - static void TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponse(nlTestSuite * apSuite, - void * apContext); - -#if CONFIG_BUILD_FOR_HOST_UNIT_TEST - static void TestCommandHandlerReleaseWithExchangeClosed(nlTestSuite * apSuite, void * apContext); -#endif + static void SetUpTestSuite() + { + mpTestContext = new TestContext; + mpTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + delete mpTestContext; + } - static void TestCommandSenderLegacyCallbackUnsupportedCommand(nlTestSuite * apSuite, void * apContext); - static void TestCommandSenderExtendableCallbackUnsupportedCommand(nlTestSuite * apSuite, void * apContext); - static void TestCommandSenderLegacyCallbackBuildingBatchCommandFails(nlTestSuite * apSuite, void * apContext); - static void TestCommandSenderExtendableCallbackBuildingBatchDuplicateCommandRefFails(nlTestSuite * apSuite, void * apContext); - static void TestCommandSenderExtendableCallbackBuildingBatchCommandSuccess(nlTestSuite * apSuite, void * apContext); - static void TestCommandSenderCommandSuccessResponseFlow(nlTestSuite * apSuite, void * apContext); - static void TestCommandSenderCommandAsyncSuccessResponseFlow(nlTestSuite * apSuite, void * apContext); - static void TestCommandSenderCommandFailureResponseFlow(nlTestSuite * apSuite, void * apContext); - static void TestCommandSenderCommandSpecificResponseFlow(nlTestSuite * apSuite, void * apContext); + void SetUp() override { mpTestContext->SetUp(); } + void TearDown() override { mpTestContext->TearDown(); } - static void TestCommandSenderAbruptDestruction(nlTestSuite * apSuite, void * apContext); + static TestContext * mpTestContext; static size_t GetNumActiveCommandResponderObjects() { return chip::app::InteractionModelEngine::GetInstance()->mCommandResponderObjs.Allocated(); } -private: + void TestCommandInvalidMessage1(); + void TestCommandInvalidMessage2(); + void TestCommandInvalidMessage3(); + void TestCommandInvalidMessage4(); + void TestCommandSender_WithSendCommand(); + void TestCommandSender_WithProcessReceivedMsg(); + void TestCommandSender_ExtendableApiWithProcessReceivedMsg(); + void TestCommandSender_ExtendableApiWithProcessReceivedMsgContainingInvalidCommandRef(); + void TestCommandHandler_WithoutResponderCallingAddStatus(); + void TestCommandHandler_WithoutResponderCallingAddResponse(); + void TestCommandHandler_WithoutResponderCallingDirectPrepareFinishCommandApis(); + void TestCommandHandler_RejectsMultipleCommandsWithIdenticalCommandRef(); + void TestCommandHandler_RejectMultipleCommandsWhenHandlerOnlySupportsOne(); + void TestCommandHandler_AcceptMultipleCommands(); + void TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsStatusResponse(); + void TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponsePrimative(); + void TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponse(); + void TestCommandHandler_ReleaseWithExchangeClosed(); + /** * With the introduction of batch invoke commands, CommandHandler keeps track of incoming * ConcreteCommandPath and the associated CommandRefs. These are normally populated @@ -414,28 +420,25 @@ class TestCommandInteraction // Generate an invoke request. If aCommandId is kTestCommandIdWithData, a // payload will be included. Otherwise no payload will be included. - static void GenerateInvokeRequest(nlTestSuite * apSuite, void * apContext, System::PacketBufferHandle & aPayload, - bool aIsTimedRequest, CommandId aCommandId, ClusterId aClusterId = kTestClusterId, - EndpointId aEndpointId = kTestEndpointId); + static void GenerateInvokeRequest(System::PacketBufferHandle & aPayload, bool aIsTimedRequest, CommandId aCommandId, + ClusterId aClusterId = kTestClusterId, EndpointId aEndpointId = kTestEndpointId); // Generate an invoke response. If aCommandId is kTestCommandIdWithData, a // 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, + static void GenerateInvokeResponse(System::PacketBufferHandle & aPayload, CommandId aCommandId, + ClusterId aClusterId = kTestClusterId, 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, - CommandId aCommandId = kTestCommandIdWithData); - static void AddInvokeResponseData(nlTestSuite * apSuite, void * apContext, CommandHandler * apCommandHandler, - bool aNeedStatusCode, CommandId aResponseCommandId = kTestCommandIdWithData, - CommandId aRequestCommandId = kTestCommandIdWithData); - static uint32_t GetAddResponseDataOverheadSizeForPath(nlTestSuite * apSuite, const ConcreteCommandPath & aRequestCommandPath, + static void AddInvokeRequestData(CommandSender * apCommandSender, CommandId aCommandId = kTestCommandIdWithData); + static void AddInvalidInvokeRequestData(CommandSender * apCommandSender, CommandId aCommandId = kTestCommandIdWithData); + static void AddInvokeResponseData(CommandHandler * apCommandHandler, bool aNeedStatusCode, + CommandId aResponseCommandId = kTestCommandIdWithData, + CommandId aRequestCommandId = kTestCommandIdWithData); + static uint32_t GetAddResponseDataOverheadSizeForPath(const ConcreteCommandPath & aRequestCommandPath, ForcedSizeBufferLengthHint aBufferSizeHint); - static void FillCurrentInvokeResponseBuffer(nlTestSuite * apSuite, CommandHandlerImpl * apCommandHandler, + static void FillCurrentInvokeResponseBuffer(CommandHandlerImpl * apCommandHandler, const ConcreteCommandPath & aRequestCommandPath, uint32_t aSizeToLeaveInBuffer); - static void ValidateCommandHandlerEncodeInvokeResponseMessage(nlTestSuite * apSuite, void * apContext, bool aNeedStatusCode); + static void ValidateCommandHandlerEncodeInvokeResponseMessage(bool aNeedStatusCode); }; +TestContext * TestCommandInteraction::mpTestContext = nullptr; class TestExchangeDelegate : public Messaging::ExchangeDelegate { @@ -453,162 +456,141 @@ CommandPathParams MakeTestCommandPath(CommandId aCommandId = kTestCommandIdWithD return CommandPathParams(kTestEndpointId, 0, kTestClusterId, aCommandId, (chip::app::CommandPathFlags::kEndpointIdValid)); } -void TestCommandInteraction::GenerateInvokeRequest(nlTestSuite * apSuite, void * apContext, System::PacketBufferHandle & aPayload, - bool aIsTimedRequest, CommandId aCommandId, ClusterId aClusterId, - EndpointId aEndpointId) +void TestCommandInteraction::GenerateInvokeRequest(System::PacketBufferHandle & aPayload, bool aIsTimedRequest, + CommandId aCommandId, ClusterId aClusterId, EndpointId aEndpointId) { - CHIP_ERROR err = CHIP_NO_ERROR; InvokeRequestMessage::Builder invokeRequestMessageBuilder; System::PacketBufferTLVWriter writer; writer.Init(std::move(aPayload)); - err = invokeRequestMessageBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(invokeRequestMessageBuilder.Init(&writer), CHIP_NO_ERROR); invokeRequestMessageBuilder.SuppressResponse(true).TimedRequest(aIsTimedRequest); InvokeRequests::Builder & invokeRequests = invokeRequestMessageBuilder.CreateInvokeRequests(); - NL_TEST_ASSERT(apSuite, invokeRequestMessageBuilder.GetError() == CHIP_NO_ERROR); + ASSERT_EQ(invokeRequestMessageBuilder.GetError(), CHIP_NO_ERROR); CommandDataIB::Builder & commandDataIBBuilder = invokeRequests.CreateCommandData(); - NL_TEST_ASSERT(apSuite, invokeRequests.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(invokeRequests.GetError(), CHIP_NO_ERROR); CommandPathIB::Builder & commandPathBuilder = commandDataIBBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, commandDataIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(commandDataIBBuilder.GetError(), CHIP_NO_ERROR); commandPathBuilder.EndpointId(aEndpointId).ClusterId(aClusterId).CommandId(aCommandId).EndOfCommandPathIB(); - NL_TEST_ASSERT(apSuite, commandPathBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(commandPathBuilder.GetError(), CHIP_NO_ERROR); if (aCommandId == kTestCommandIdWithData) { chip::TLV::TLVWriter * pWriter = commandDataIBBuilder.GetWriter(); chip::TLV::TLVType dummyType = chip::TLV::kTLVType_NotSpecified; - err = pWriter->StartContainer(chip::TLV::ContextTag(chip::to_underlying(CommandDataIB::Tag::kFields)), - chip::TLV::kTLVType_Structure, dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(pWriter->StartContainer(chip::TLV::ContextTag(chip::to_underlying(CommandDataIB::Tag::kFields)), + chip::TLV::kTLVType_Structure, dummyType), + CHIP_NO_ERROR); - err = pWriter->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(pWriter->PutBoolean(chip::TLV::ContextTag(1), true), CHIP_NO_ERROR); - err = pWriter->EndContainer(dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(pWriter->EndContainer(dummyType), CHIP_NO_ERROR); } commandDataIBBuilder.EndOfCommandDataIB(); - NL_TEST_ASSERT(apSuite, commandDataIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(commandDataIBBuilder.GetError(), CHIP_NO_ERROR); invokeRequests.EndOfInvokeRequests(); - NL_TEST_ASSERT(apSuite, invokeRequests.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(invokeRequests.GetError(), CHIP_NO_ERROR); invokeRequestMessageBuilder.EndOfInvokeRequestMessage(); - NL_TEST_ASSERT(apSuite, invokeRequestMessageBuilder.GetError() == CHIP_NO_ERROR); + ASSERT_EQ(invokeRequestMessageBuilder.GetError(), CHIP_NO_ERROR); - err = writer.Finalize(&aPayload); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&aPayload), CHIP_NO_ERROR); } -void TestCommandInteraction::GenerateInvokeResponse(nlTestSuite * apSuite, void * apContext, System::PacketBufferHandle & aPayload, - CommandId aCommandId, ClusterId aClusterId, EndpointId aEndpointId, +void TestCommandInteraction::GenerateInvokeResponse(System::PacketBufferHandle & aPayload, CommandId aCommandId, + ClusterId aClusterId, EndpointId aEndpointId, std::optional aCommandRef) { - CHIP_ERROR err = CHIP_NO_ERROR; InvokeResponseMessage::Builder invokeResponseMessageBuilder; System::PacketBufferTLVWriter writer; writer.Init(std::move(aPayload)); - err = invokeResponseMessageBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(invokeResponseMessageBuilder.Init(&writer), CHIP_NO_ERROR); invokeResponseMessageBuilder.SuppressResponse(true); InvokeResponseIBs::Builder & invokeResponses = invokeResponseMessageBuilder.CreateInvokeResponses(); - NL_TEST_ASSERT(apSuite, invokeResponseMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(invokeResponseMessageBuilder.GetError(), CHIP_NO_ERROR); InvokeResponseIB::Builder & invokeResponseIBBuilder = invokeResponses.CreateInvokeResponse(); - NL_TEST_ASSERT(apSuite, invokeResponses.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(invokeResponses.GetError(), CHIP_NO_ERROR); CommandDataIB::Builder & commandDataIBBuilder = invokeResponseIBBuilder.CreateCommand(); - NL_TEST_ASSERT(apSuite, commandDataIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(commandDataIBBuilder.GetError(), CHIP_NO_ERROR); CommandPathIB::Builder & commandPathBuilder = commandDataIBBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, commandDataIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(commandDataIBBuilder.GetError(), CHIP_NO_ERROR); commandPathBuilder.EndpointId(aEndpointId).ClusterId(aClusterId).CommandId(aCommandId).EndOfCommandPathIB(); - NL_TEST_ASSERT(apSuite, commandPathBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(commandPathBuilder.GetError(), CHIP_NO_ERROR); if (aCommandId == kTestCommandIdWithData) { chip::TLV::TLVWriter * pWriter = commandDataIBBuilder.GetWriter(); chip::TLV::TLVType dummyType = chip::TLV::kTLVType_NotSpecified; - err = pWriter->StartContainer(chip::TLV::ContextTag(chip::to_underlying(CommandDataIB::Tag::kFields)), - chip::TLV::kTLVType_Structure, dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = pWriter->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(pWriter->StartContainer(chip::TLV::ContextTag(chip::to_underlying(CommandDataIB::Tag::kFields)), + chip::TLV::kTLVType_Structure, dummyType), + CHIP_NO_ERROR); + + EXPECT_EQ(pWriter->PutBoolean(chip::TLV::ContextTag(1), true), CHIP_NO_ERROR); - err = pWriter->EndContainer(dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(pWriter->EndContainer(dummyType), CHIP_NO_ERROR); } if (aCommandRef.has_value()) { - NL_TEST_ASSERT(apSuite, commandDataIBBuilder.Ref(*aCommandRef) == CHIP_NO_ERROR); + EXPECT_EQ(commandDataIBBuilder.Ref(*aCommandRef), CHIP_NO_ERROR); } commandDataIBBuilder.EndOfCommandDataIB(); - NL_TEST_ASSERT(apSuite, commandDataIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(commandDataIBBuilder.GetError(), CHIP_NO_ERROR); invokeResponseIBBuilder.EndOfInvokeResponseIB(); - NL_TEST_ASSERT(apSuite, invokeResponseIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(invokeResponseIBBuilder.GetError(), CHIP_NO_ERROR); invokeResponses.EndOfInvokeResponses(); - NL_TEST_ASSERT(apSuite, invokeResponses.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(invokeResponses.GetError(), CHIP_NO_ERROR); invokeResponseMessageBuilder.EndOfInvokeResponseMessage(); - NL_TEST_ASSERT(apSuite, invokeResponseMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(invokeResponseMessageBuilder.GetError(), CHIP_NO_ERROR); - err = writer.Finalize(&aPayload); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&aPayload), CHIP_NO_ERROR); } -void TestCommandInteraction::AddInvokeRequestData(nlTestSuite * apSuite, void * apContext, CommandSender * apCommandSender, - CommandId aCommandId) +void TestCommandInteraction::AddInvokeRequestData(CommandSender * apCommandSender, CommandId aCommandId) { - CHIP_ERROR err = CHIP_NO_ERROR; auto commandPathParams = MakeTestCommandPath(aCommandId); - err = apCommandSender->PrepareCommand(commandPathParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(apCommandSender->PrepareCommand(commandPathParams), CHIP_NO_ERROR); chip::TLV::TLVWriter * writer = apCommandSender->GetCommandDataIBTLVWriter(); - err = writer->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - - err = apCommandSender->FinishCommand(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writer->PutBoolean(chip::TLV::ContextTag(1), true), CHIP_NO_ERROR); + EXPECT_EQ(apCommandSender->FinishCommand(), CHIP_NO_ERROR); } -void TestCommandInteraction::AddInvalidInvokeRequestData(nlTestSuite * apSuite, void * apContext, CommandSender * apCommandSender, - CommandId aCommandId) +void TestCommandInteraction::AddInvalidInvokeRequestData(CommandSender * apCommandSender, CommandId aCommandId) { - CHIP_ERROR err = CHIP_NO_ERROR; auto commandPathParams = MakeTestCommandPath(aCommandId); - err = apCommandSender->PrepareCommand(commandPathParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(apCommandSender->PrepareCommand(commandPathParams), CHIP_NO_ERROR); chip::TLV::TLVWriter * writer = apCommandSender->GetCommandDataIBTLVWriter(); - err = writer->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - + EXPECT_EQ(writer->PutBoolean(chip::TLV::ContextTag(1), true), CHIP_NO_ERROR); apCommandSender->MoveToState(CommandSender::State::AddedCommand); } -void TestCommandInteraction::AddInvokeResponseData(nlTestSuite * apSuite, void * apContext, CommandHandler * apCommandHandler, - bool aNeedStatusCode, CommandId aResponseCommandId, CommandId aRequestCommandId) +void TestCommandInteraction::AddInvokeResponseData(CommandHandler * apCommandHandler, bool aNeedStatusCode, + CommandId aResponseCommandId, CommandId aRequestCommandId) { constexpr EndpointId kTestEndpointId = 1; constexpr ClusterId kTestClusterId = 3; @@ -620,13 +602,11 @@ void TestCommandInteraction::AddInvokeResponseData(nlTestSuite * apSuite, void * else { SimpleTLVPayload payloadWriter; - CHIP_ERROR err = apCommandHandler->AddResponseData(requestCommandPath, aResponseCommandId, payloadWriter); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(apCommandHandler->AddResponseData(requestCommandPath, aResponseCommandId, payloadWriter), CHIP_NO_ERROR); } } -uint32_t TestCommandInteraction::GetAddResponseDataOverheadSizeForPath(nlTestSuite * apSuite, - const ConcreteCommandPath & aRequestCommandPath, +uint32_t TestCommandInteraction::GetAddResponseDataOverheadSizeForPath(const ConcreteCommandPath & aRequestCommandPath, ForcedSizeBufferLengthHint aBufferSizeHint) { BasicCommandPathRegistry<4> basicCommandPathRegistry; @@ -637,213 +617,48 @@ uint32_t TestCommandInteraction::GetAddResponseDataOverheadSizeForPath(nlTestSui ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; - CHIP_ERROR err = basicCommandPathRegistry.Add(requestCommandPath1, std::make_optional(static_cast(1))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(basicCommandPathRegistry.Add(requestCommandPath1, std::make_optional(static_cast(1))), + CHIP_NO_ERROR); + + EXPECT_EQ(basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))), + CHIP_NO_ERROR); + + EXPECT_EQ(commandHandler.AllocateBuffer(), CHIP_NO_ERROR); - err = commandHandler.AllocateBuffer(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); uint32_t remainingSizeBefore = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); // When ForcedSizeBuffer exceeds 255, an extra byte is needed for length, affecting the overhead size required by // AddResponseData. In order to have this accounted for in overhead calculation we set the length to be 256. uint32_t sizeOfForcedSizeBuffer = aBufferSizeHint == ForcedSizeBufferLengthHint::kSizeGreaterThan255 ? 256 : 0; - err = commandHandler.AddResponseData(aRequestCommandPath, ForcedSizeBuffer(sizeOfForcedSizeBuffer)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandHandler.AddResponseData(aRequestCommandPath, ForcedSizeBuffer(sizeOfForcedSizeBuffer)), CHIP_NO_ERROR); uint32_t remainingSizeAfter = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); uint32_t delta = remainingSizeBefore - remainingSizeAfter - sizeOfForcedSizeBuffer; return delta; } -void TestCommandInteraction::FillCurrentInvokeResponseBuffer(nlTestSuite * apSuite, CommandHandlerImpl * apCommandHandler, +void TestCommandInteraction::FillCurrentInvokeResponseBuffer(CommandHandlerImpl * apCommandHandler, const ConcreteCommandPath & aRequestCommandPath, uint32_t aSizeToLeaveInBuffer) { - CHIP_ERROR err = CHIP_NO_ERROR; - - err = apCommandHandler->AllocateBuffer(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(apCommandHandler->AllocateBuffer(), CHIP_NO_ERROR); uint32_t remainingSize = apCommandHandler->mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); // AddResponseData's overhead calculation depends on the size of ForcedSizeBuffer. If the buffer exceeds 255 bytes, an extra // length byte is required. Since tests using FillCurrentInvokeResponseBuffer currently end up with sizeToFill > 255, we // inform the calculation of this expectation. Nonetheless, we also validate this assumption for correctness. - ForcedSizeBufferLengthHint bufferSizeHint = ForcedSizeBufferLengthHint::kSizeGreaterThan255; - uint32_t overheadSizeNeededForAddingResponse = - GetAddResponseDataOverheadSizeForPath(apSuite, aRequestCommandPath, bufferSizeHint); - NL_TEST_ASSERT(apSuite, remainingSize > (aSizeToLeaveInBuffer + overheadSizeNeededForAddingResponse)); + ForcedSizeBufferLengthHint bufferSizeHint = ForcedSizeBufferLengthHint::kSizeGreaterThan255; + uint32_t overheadSizeNeededForAddingResponse = GetAddResponseDataOverheadSizeForPath(aRequestCommandPath, bufferSizeHint); + EXPECT_GT(remainingSize, (aSizeToLeaveInBuffer + overheadSizeNeededForAddingResponse)); uint32_t sizeToFill = remainingSize - aSizeToLeaveInBuffer - overheadSizeNeededForAddingResponse; // Validating assumption. If this fails, it means overheadSizeNeededForAddingResponse is likely too large. - NL_TEST_ASSERT(apSuite, sizeToFill >= 256); - - err = apCommandHandler->AddResponseData(aRequestCommandPath, ForcedSizeBuffer(sizeToFill)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); -} - -void TestCommandInteraction::TestCommandSenderWithWrongState(nlTestSuite * apSuite, void * apContext) -{ - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_INCORRECT_STATE); -} - -void TestCommandInteraction::TestCommandHandlerWithWrongState(nlTestSuite * apSuite, void * apContext) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - ConcreteCommandPath requestCommandPath = { kTestEndpointId, kTestClusterId, kTestCommandIdNoData }; - ConcreteCommandPath responseCommandPath = { kTestEndpointId, kTestClusterId, kTestCommandIdNoData }; - - CommandHandlerWithUnrespondedCommand commandHandler(&mockCommandHandlerDelegate, requestCommandPath, - /* aRef = */ NullOptional); - - { - // This simulates how cluster would call CommandHandler APIs synchronously. There would - // be handle already acquired on the callers behalf. - CommandHandler::Handle handle(&commandHandler); - - const CommandHandlerImpl::InvokeResponseParameters prepareParams(requestCommandPath); - err = commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - } - NL_TEST_ASSERT(apSuite, commandHandler.mMockCommandResponder.mChunks.IsNull()); -} - -void TestCommandInteraction::TestCommandSenderWithSendCommand(nlTestSuite * apSuite, void * apContext) -{ - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); - - System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - - AddInvokeRequestData(apSuite, apContext, &commandSender); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - - ctx.DrainAndServiceIO(); - - GenerateInvokeResponse(apSuite, apContext, buf, kTestCommandIdWithData); - bool moreChunkedMessages = false; - err = commandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, moreChunkedMessages == false); -} - -void TestCommandInteraction::TestCommandHandlerWithSendEmptyCommand(nlTestSuite * apSuite, void * apContext) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - ConcreteCommandPath requestCommandPath = { kTestEndpointId, kTestClusterId, kTestCommandIdNoData }; - ConcreteCommandPath responseCommandPath = { kTestEndpointId, kTestClusterId, kTestCommandIdNoData }; - - CommandHandlerWithUnrespondedCommand commandHandler(&mockCommandHandlerDelegate, requestCommandPath, - /* aRef = */ NullOptional); - - { - // This simulates how cluster would call CommandHandler APIs synchronously. There would - // be handle already acquired on the callers behalf. - CommandHandler::Handle handle(&commandHandler); - - const CommandHandlerImpl::InvokeResponseParameters prepareParams(requestCommandPath); - err = commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = commandHandler.FinishCommand(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - } - NL_TEST_ASSERT(apSuite, !commandHandler.mMockCommandResponder.mChunks.IsNull()); -} - -void TestCommandInteraction::TestCommandSenderWithProcessReceivedMsg(nlTestSuite * apSuite, void * apContext) -{ - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); - - System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); + EXPECT_GE(sizeToFill, 256u); - GenerateInvokeResponse(apSuite, apContext, buf, kTestCommandIdWithData); - bool moreChunkedMessages = false; - err = commandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, moreChunkedMessages == false); + EXPECT_EQ(apCommandHandler->AddResponseData(aRequestCommandPath, ForcedSizeBuffer(sizeToFill)), CHIP_NO_ERROR); } -void TestCommandInteraction::TestCommandSenderExtendableApiWithProcessReceivedMsg(nlTestSuite * apSuite, void * apContext) -{ - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - mockCommandSenderExtendedDelegate.ResetCounter(); - PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager(), - &pendingResponseTracker); - - uint16_t mockCommandRef = 1; - pendingResponseTracker.Add(mockCommandRef); - commandSender.mFinishedCommandCount = 1; - - System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - - GenerateInvokeResponse(apSuite, apContext, buf, kTestCommandIdWithData); - bool moreChunkedMessages = false; - err = commandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, moreChunkedMessages == false); - - commandSender.FlushNoCommandResponse(); - - NL_TEST_ASSERT(apSuite, - mockCommandSenderExtendedDelegate.onResponseCalledTimes == 1 && - mockCommandSenderExtendedDelegate.onFinalCalledTimes == 0 && - mockCommandSenderExtendedDelegate.onNoResponseCalledTimes == 0 && - mockCommandSenderExtendedDelegate.onErrorCalledTimes == 0); -} - -void TestCommandInteraction::TestCommandSenderExtendableApiWithProcessReceivedMsgContainingInvalidCommandRef(nlTestSuite * apSuite, - void * apContext) -{ - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - mockCommandSenderExtendedDelegate.ResetCounter(); - PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager(), - &pendingResponseTracker); - - uint16_t mockCommandRef = 1; - pendingResponseTracker.Add(mockCommandRef); - commandSender.mFinishedCommandCount = 1; - - System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - - uint16_t invalidResponseCommandRef = 2; - GenerateInvokeResponse(apSuite, apContext, buf, kTestCommandIdWithData, kTestClusterId, kTestEndpointId, - std::make_optional(invalidResponseCommandRef)); - bool moreChunkedMessages = false; - err = commandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_KEY_NOT_FOUND); - NL_TEST_ASSERT(apSuite, moreChunkedMessages == false); - - commandSender.FlushNoCommandResponse(); - - NL_TEST_ASSERT(apSuite, - mockCommandSenderExtendedDelegate.onResponseCalledTimes == 0 && - mockCommandSenderExtendedDelegate.onFinalCalledTimes == 0 && - mockCommandSenderExtendedDelegate.onNoResponseCalledTimes == 1 && - mockCommandSenderExtendedDelegate.onErrorCalledTimes == 0); -} - -void TestCommandInteraction::ValidateCommandHandlerEncodeInvokeResponseMessage(nlTestSuite * apSuite, void * apContext, - bool aNeedStatusCode) +void TestCommandInteraction::ValidateCommandHandlerEncodeInvokeResponseMessage(bool aNeedStatusCode) { chip::app::ConcreteCommandPath requestCommandPath(kTestEndpointId, kTestClusterId, kTestCommandIdWithData); CommandHandlerWithUnrespondedCommand commandHandler(&mockCommandHandlerDelegate, requestCommandPath, @@ -854,426 +669,484 @@ void TestCommandInteraction::ValidateCommandHandlerEncodeInvokeResponseMessage(n // be handle already acquired on the callers behalf. CommandHandler::Handle handle(&commandHandler); - AddInvokeResponseData(apSuite, apContext, &commandHandler, aNeedStatusCode); + AddInvokeResponseData(&commandHandler, aNeedStatusCode); } - NL_TEST_ASSERT(apSuite, !commandHandler.mMockCommandResponder.mChunks.IsNull()); + EXPECT_FALSE(commandHandler.mMockCommandResponder.mChunks.IsNull()); } -void TestCommandInteraction::TestCommandHandlerEncodeSimpleCommandData(nlTestSuite * apSuite, void * apContext) -{ - // Send response which has simple command data and command path - ValidateCommandHandlerEncodeInvokeResponseMessage(apSuite, apContext, false /*aNeedStatusCode=false*/); -} - -struct Fields -{ - static constexpr chip::CommandId GetCommandId() { return 4; } - CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const - { - TLV::TLVType outerContainerType; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outerContainerType)); - ReturnErrorOnFailure(aWriter.PutBoolean(TLV::ContextTag(1), true)); - return aWriter.EndContainer(outerContainerType); - } -}; - -struct BadFields -{ - static constexpr chip::CommandId GetCommandId() { return 4; } - CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const - { - TLV::TLVType outerContainerType; - uint8_t data[36] = { 0 }; - ReturnErrorOnFailure(aWriter.StartContainer(aTag, TLV::kTLVType_Structure, outerContainerType)); - // Just encode something bad to return a failure state here. - for (uint8_t i = 1; i < UINT8_MAX; i++) - { - ReturnErrorOnFailure(app::DataModel::Encode(aWriter, TLV::ContextTag(i), ByteSpan(data))); - } - return aWriter.EndContainer(outerContainerType); - } -}; - -void TestCommandInteraction::TestCommandHandlerCommandDataEncoding(nlTestSuite * apSuite, void * apContext) -{ - auto path = MakeTestCommandPath(); - ConcreteCommandPath requestCommandPath(path.mEndpointId, path.mClusterId, path.mCommandId); - CommandHandlerWithUnrespondedCommand commandHandler(nullptr, requestCommandPath, /* aRef = */ NullOptional); - - { - // This simulates how cluster would call CommandHandler APIs synchronously. There would - // be handle already acquired on the callers behalf. - CommandHandler::Handle handle(&commandHandler); - - commandHandler.AddResponse(requestCommandPath, Fields()); - } - NL_TEST_ASSERT(apSuite, !commandHandler.mMockCommandResponder.mChunks.IsNull()); -} - -void TestCommandInteraction::TestCommandHandlerCommandEncodeFailure(nlTestSuite * apSuite, void * apContext) -{ - auto path = MakeTestCommandPath(); - auto requestCommandPath = ConcreteCommandPath(path.mEndpointId, path.mClusterId, path.mCommandId); - CommandHandlerWithUnrespondedCommand commandHandler(nullptr, requestCommandPath, NullOptional); - - { - // This simulates how cluster would call CommandHandler APIs synchronously. There would - // be handle already acquired on the callers behalf. - CommandHandler::Handle handle(&commandHandler); - - commandHandler.AddResponse(requestCommandPath, BadFields()); - } - NL_TEST_ASSERT(apSuite, !commandHandler.mMockCommandResponder.mChunks.IsNull()); -} - -/** - * Helper macro we can use to pretend we got a reply from the server in cases - * when the reply was actually dropped due to us not wanting the client's state - * machine to advance. - * - * When this macro is used, the client has sent a message and is waiting for an - * ack+response, and the server has sent a response that got dropped and is - * waiting for an ack (and maybe a response). - * - * What this macro then needs to do is: - * - * 1. Pretend that the client got an ack (and clear out the corresponding ack - * state). - * 2. Pretend that the client got a message from the server, with the id of the - * message that was dropped, which requires an ack, so the client will send - * that ack in its next message. - * - * This is a macro so we get useful line numbers on assertion failures - */ -#define PretendWeGotReplyFromServer(aSuite, aContext, aClientExchange) \ - { \ - Messaging::ReliableMessageMgr * localRm = (aContext).GetExchangeManager().GetReliableMessageMgr(); \ - Messaging::ExchangeContext * localExchange = aClientExchange; \ - NL_TEST_ASSERT(aSuite, localRm->TestGetCountRetransTable() == 2); \ - \ - localRm->ClearRetransTable(localExchange); \ - NL_TEST_ASSERT(aSuite, localRm->TestGetCountRetransTable() == 1); \ - \ - localRm->EnumerateRetransTable([localExchange](auto * entry) { \ - localExchange->SetPendingPeerAckMessageCounter(entry->retainedBuf.GetMessageCounter()); \ - return Loop::Break; \ - }); \ - } - // Command Sender sends invoke request, command handler drops invoke response, then test injects status response message with // busy to client, client sends out a status response with invalid action. -void TestCommandInteraction::TestCommandInvalidMessage1(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage1) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender); + AddInvokeRequestData(&commandSender); asyncCommand = false; - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 0 && - mockCommandSenderDelegate.onErrorCalledTimes == 0); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 0); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + ASSERT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); StatusResponseMessage::Builder response; response.Init(&writer); response.Status(Protocols::InteractionModel::Status::Busy); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::StatusResponse); - Test::MessageCapturer messageLog(ctx); + chip::Test::MessageCapturer messageLog(*mpTestContext); messageLog.mCaptureStandaloneAcks = false; // Since we are dropping packets, things are not getting acked. Set up our // MRP state to look like what it would have looked like if the packet had // not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, commandSender.mExchangeCtx.Get()); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + PretendWeGotReplyFromServer(*mpTestContext, commandSender.mExchangeCtx.Get()); + + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; - err = commandSender.OnMessageReceived(commandSender.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_IM_GLOBAL_STATUS(Busy)); - NL_TEST_ASSERT(apSuite, mockCommandSenderDelegate.mError == CHIP_IM_GLOBAL_STATUS(Busy)); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 1 && - mockCommandSenderDelegate.onErrorCalledTimes == 1); - NL_TEST_ASSERT(apSuite, commandSender.GetInvokeResponseMessageCount() == 0); + EXPECT_EQ(commandSender.OnMessageReceived(commandSender.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), + CHIP_IM_GLOBAL_STATUS(Busy)); + EXPECT_EQ(mockCommandSenderDelegate.mError, CHIP_IM_GLOBAL_STATUS(Busy)); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 1); + EXPECT_EQ(commandSender.GetInvokeResponseMessageCount(), 0u); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // Client sent status report with invalid action, server's exchange has been closed, so all it sent is an MRP Ack - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - CheckForInvalidAction(apSuite, messageLog); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + CheckForInvalidAction(messageLog); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Command Sender sends invoke request, command handler drops invoke response, then test injects unknown message to client, // client sends out status response with invalid action. -void TestCommandInteraction::TestCommandInvalidMessage2(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage2) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender); + AddInvokeRequestData(&commandSender); asyncCommand = false; - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 0 && - mockCommandSenderDelegate.onErrorCalledTimes == 0); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 0); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + ASSERT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); ReportDataMessage::Builder response; response.Init(&writer); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::ReportData); - Test::MessageCapturer messageLog(ctx); + chip::Test::MessageCapturer messageLog(*mpTestContext); messageLog.mCaptureStandaloneAcks = false; // Since we are dropping packets, things are not getting acked. Set up our // MRP state to look like what it would have looked like if the packet had // not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, commandSender.mExchangeCtx.Get()); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + PretendWeGotReplyFromServer(*mpTestContext, commandSender.mExchangeCtx.Get()); - err = commandSender.OnMessageReceived(commandSender.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_INVALID_MESSAGE_TYPE); - NL_TEST_ASSERT(apSuite, mockCommandSenderDelegate.mError == CHIP_ERROR_INVALID_MESSAGE_TYPE); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 1 && - mockCommandSenderDelegate.onErrorCalledTimes == 1); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; - ctx.DrainAndServiceIO(); + EXPECT_EQ(commandSender.OnMessageReceived(commandSender.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), + CHIP_ERROR_INVALID_MESSAGE_TYPE); + EXPECT_EQ(mockCommandSenderDelegate.mError, CHIP_ERROR_INVALID_MESSAGE_TYPE); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 1); + + mpTestContext->DrainAndServiceIO(); // Client sent status report with invalid action, server's exchange has been closed, so all it sent is an MRP Ack - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - CheckForInvalidAction(apSuite, messageLog); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + CheckForInvalidAction(messageLog); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Command Sender sends invoke request, command handler drops invoke response, then test injects malformed invoke response // message to client, client sends out status response with invalid action. -void TestCommandInteraction::TestCommandInvalidMessage3(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage3) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender); + AddInvokeRequestData(&commandSender); asyncCommand = false; - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 0 && - mockCommandSenderDelegate.onErrorCalledTimes == 0); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 0); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + ASSERT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); InvokeResponseMessage::Builder response; response.Init(&writer); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::InvokeCommandResponse); - Test::MessageCapturer messageLog(ctx); + chip::Test::MessageCapturer messageLog(*mpTestContext); messageLog.mCaptureStandaloneAcks = false; // Since we are dropping packets, things are not getting acked. Set up our // MRP state to look like what it would have looked like if the packet had // not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, commandSender.mExchangeCtx.Get()); + PretendWeGotReplyFromServer(*mpTestContext, commandSender.mExchangeCtx.Get()); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; - err = commandSender.OnMessageReceived(commandSender.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_END_OF_TLV); - NL_TEST_ASSERT(apSuite, mockCommandSenderDelegate.mError == CHIP_ERROR_END_OF_TLV); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 1 && - mockCommandSenderDelegate.onErrorCalledTimes == 1); + EXPECT_EQ(commandSender.OnMessageReceived(commandSender.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), + CHIP_ERROR_END_OF_TLV); + EXPECT_EQ(mockCommandSenderDelegate.mError, CHIP_ERROR_END_OF_TLV); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 1); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // Client sent status report with invalid action, server's exchange has been closed, so all it sent is an MRP Ack - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - CheckForInvalidAction(apSuite, messageLog); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + CheckForInvalidAction(messageLog); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Command Sender sends invoke request, command handler drops invoke response, then test injects malformed status response to // client, client responds to the status response with invalid action. -void TestCommandInteraction::TestCommandInvalidMessage4(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage4) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender); + AddInvokeRequestData(&commandSender); asyncCommand = false; - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 0 && - mockCommandSenderDelegate.onErrorCalledTimes == 0); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + ASSERT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); StatusResponseMessage::Builder response; response.Init(&writer); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::StatusResponse); - Test::MessageCapturer messageLog(ctx); + chip::Test::MessageCapturer messageLog(*mpTestContext); messageLog.mCaptureStandaloneAcks = false; // Since we are dropping packets, things are not getting acked. Set up our // MRP state to look like what it would have looked like if the packet had // not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, commandSender.mExchangeCtx.Get()); + PretendWeGotReplyFromServer(*mpTestContext, commandSender.mExchangeCtx.Get()); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; - err = commandSender.OnMessageReceived(commandSender.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_END_OF_TLV); - NL_TEST_ASSERT(apSuite, mockCommandSenderDelegate.mError == CHIP_ERROR_END_OF_TLV); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 1 && - mockCommandSenderDelegate.onErrorCalledTimes == 1); + EXPECT_EQ(commandSender.OnMessageReceived(commandSender.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), + CHIP_ERROR_END_OF_TLV); + EXPECT_EQ(mockCommandSenderDelegate.mError, CHIP_ERROR_END_OF_TLV); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 1); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // Client sent status report with invalid action, server's exchange has been closed, so all it sent is an MRP Ack - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - CheckForInvalidAction(apSuite, messageLog); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + CheckForInvalidAction(messageLog); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); +} + +TEST_F(TestCommandInteraction, TestCommandSender_WithWrongState) +{ + + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_ERROR_INCORRECT_STATE); +} + +TEST_F(TestCommandInteraction, TestCommandHandler_WithWrongState) +{ + ConcreteCommandPath requestCommandPath = { kTestEndpointId, kTestClusterId, kTestCommandIdNoData }; + ConcreteCommandPath responseCommandPath = { kTestEndpointId, kTestClusterId, kTestCommandIdNoData }; + + CommandHandlerWithUnrespondedCommand commandHandler(&mockCommandHandlerDelegate, requestCommandPath, + /* aRef = */ NullOptional); + + { + // This simulates how cluster would call CommandHandler APIs synchronously. There would + // be handle already acquired on the callers behalf. + CommandHandler::Handle handle(&commandHandler); + + const CommandHandlerImpl::InvokeResponseParameters prepareParams(requestCommandPath); + EXPECT_EQ(commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams), CHIP_NO_ERROR); + } + EXPECT_TRUE(commandHandler.mMockCommandResponder.mChunks.IsNull()); +} + +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandSender_WithSendCommand) +{ + + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + + System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); + + AddInvokeRequestData(&commandSender); + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + + mpTestContext->DrainAndServiceIO(); + + GenerateInvokeResponse(buf, kTestCommandIdWithData); + bool moreChunkedMessages = false; + EXPECT_EQ(commandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages), CHIP_NO_ERROR); + EXPECT_FALSE(moreChunkedMessages); +} + +TEST_F(TestCommandInteraction, TestCommandHandler_WithSendEmptyCommand) +{ + ConcreteCommandPath requestCommandPath = { kTestEndpointId, kTestClusterId, kTestCommandIdNoData }; + ConcreteCommandPath responseCommandPath = { kTestEndpointId, kTestClusterId, kTestCommandIdNoData }; + + CommandHandlerWithUnrespondedCommand commandHandler(&mockCommandHandlerDelegate, requestCommandPath, + /* aRef = */ NullOptional); + + { + // This simulates how cluster would call CommandHandler APIs synchronously. There would + // be handle already acquired on the callers behalf. + CommandHandler::Handle handle(&commandHandler); + + const CommandHandlerImpl::InvokeResponseParameters prepareParams(requestCommandPath); + EXPECT_EQ(commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams), CHIP_NO_ERROR); + EXPECT_EQ(commandHandler.FinishCommand(), CHIP_NO_ERROR); + } + EXPECT_FALSE(commandHandler.mMockCommandResponder.mChunks.IsNull()); +} + +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandSender_WithProcessReceivedMsg) +{ + + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + + System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); + + GenerateInvokeResponse(buf, kTestCommandIdWithData); + bool moreChunkedMessages = false; + + EXPECT_EQ(commandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages), CHIP_NO_ERROR); + EXPECT_FALSE(moreChunkedMessages); +} + +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandSender_ExtendableApiWithProcessReceivedMsg) +{ + + mockCommandSenderExtendedDelegate.ResetCounter(); + PendingResponseTrackerImpl pendingResponseTracker; + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &mpTestContext->GetExchangeManager(), &pendingResponseTracker); + + uint16_t mockCommandRef = 1; + pendingResponseTracker.Add(mockCommandRef); + commandSender.mFinishedCommandCount = 1; + + System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); + + GenerateInvokeResponse(buf, kTestCommandIdWithData); + bool moreChunkedMessages = false; + EXPECT_EQ(commandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages), CHIP_NO_ERROR); + EXPECT_FALSE(moreChunkedMessages); + + commandSender.FlushNoCommandResponse(); + + EXPECT_EQ(mockCommandSenderExtendedDelegate.onResponseCalledTimes, 1); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onFinalCalledTimes, 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onNoResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onErrorCalledTimes, 0); +} + +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandSender_ExtendableApiWithProcessReceivedMsgContainingInvalidCommandRef) +{ + + mockCommandSenderExtendedDelegate.ResetCounter(); + PendingResponseTrackerImpl pendingResponseTracker; + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &mpTestContext->GetExchangeManager(), &pendingResponseTracker); + + uint16_t mockCommandRef = 1; + pendingResponseTracker.Add(mockCommandRef); + + commandSender.mFinishedCommandCount = 1; + + System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); + + uint16_t invalidResponseCommandRef = 2; + GenerateInvokeResponse(buf, kTestCommandIdWithData, kTestClusterId, kTestEndpointId, + std::make_optional(invalidResponseCommandRef)); + bool moreChunkedMessages = false; + EXPECT_EQ(commandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages), CHIP_ERROR_KEY_NOT_FOUND); + EXPECT_FALSE(moreChunkedMessages); + + commandSender.FlushNoCommandResponse(); + + EXPECT_EQ(mockCommandSenderExtendedDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onFinalCalledTimes, 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onNoResponseCalledTimes, 1); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onErrorCalledTimes, 0); +} + +TEST_F(TestCommandInteraction, TestCommandHandlerEncodeSimpleCommandData) +{ + // Send response which has simple command data and command path + ValidateCommandHandlerEncodeInvokeResponseMessage(false /*aNeedStatusCode=false*/); +} + +TEST_F(TestCommandInteraction, TestCommandHandlerCommandDataEncoding) +{ + auto path = MakeTestCommandPath(); + ConcreteCommandPath requestCommandPath(path.mEndpointId, path.mClusterId, path.mCommandId); + CommandHandlerWithUnrespondedCommand commandHandler(nullptr, requestCommandPath, /* aRef = */ NullOptional); + + { + // This simulates how cluster would call CommandHandler APIs synchronously. There would + // be handle already acquired on the callers behalf. + CommandHandler::Handle handle(&commandHandler); + + commandHandler.AddResponse(requestCommandPath, Fields()); + } + EXPECT_FALSE(commandHandler.mMockCommandResponder.mChunks.IsNull()); +} + +TEST_F(TestCommandInteraction, TestCommandHandlerCommandEncodeFailure) +{ + auto path = MakeTestCommandPath(); + auto requestCommandPath = ConcreteCommandPath(path.mEndpointId, path.mClusterId, path.mCommandId); + CommandHandlerWithUnrespondedCommand commandHandler(nullptr, requestCommandPath, NullOptional); + + { + // This simulates how cluster would call CommandHandler APIs synchronously. There would + // be handle already acquired on the callers behalf. + CommandHandler::Handle handle(&commandHandler); + + commandHandler.AddResponse(requestCommandPath, BadFields()); + } + EXPECT_FALSE(commandHandler.mMockCommandResponder.mChunks.IsNull()); } // Command Sender sends malformed invoke request, handler fails to process it and sends status report with invalid action -void TestCommandInteraction::TestCommandHandlerInvalidMessageSync(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerInvalidMessageSync) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); chip::isCommandDispatched = false; - AddInvalidInvokeRequestData(apSuite, apContext, &commandSender); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - - ctx.DrainAndServiceIO(); - - NL_TEST_ASSERT(apSuite, !chip::isCommandDispatched); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 1 && - mockCommandSenderDelegate.onErrorCalledTimes == 1); - NL_TEST_ASSERT(apSuite, mockCommandSenderDelegate.mError == CHIP_IM_GLOBAL_STATUS(InvalidAction)); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + AddInvalidInvokeRequestData(&commandSender); + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + + mpTestContext->DrainAndServiceIO(); + + EXPECT_FALSE(chip::isCommandDispatched); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestCommandInteraction::TestCommandHandlerCommandEncodeExternalFailure(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerCommandEncodeExternalFailure) { - CHIP_ERROR err = CHIP_NO_ERROR; auto path = MakeTestCommandPath(); auto requestCommandPath = ConcreteCommandPath(path.mEndpointId, path.mClusterId, path.mCommandId); CommandHandlerWithUnrespondedCommand commandHandler(nullptr, requestCommandPath, NullOptional); @@ -1283,20 +1156,19 @@ void TestCommandInteraction::TestCommandHandlerCommandEncodeExternalFailure(nlTe // be handle already acquired on the callers behalf. CommandHandler::Handle handle(&commandHandler); - err = commandHandler.AddResponseData(requestCommandPath, BadFields()); - NL_TEST_ASSERT(apSuite, err != CHIP_NO_ERROR); + EXPECT_NE(commandHandler.AddResponseData(requestCommandPath, BadFields()), CHIP_NO_ERROR); commandHandler.AddStatus(requestCommandPath, Protocols::InteractionModel::Status::Failure); } - NL_TEST_ASSERT(apSuite, !commandHandler.mMockCommandResponder.mChunks.IsNull()); + EXPECT_FALSE(commandHandler.mMockCommandResponder.mChunks.IsNull()); } -void TestCommandInteraction::TestCommandHandlerEncodeSimpleStatusCode(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerEncodeSimpleStatusCode) { // Send response which has simple status code and command path - ValidateCommandHandlerEncodeInvokeResponseMessage(apSuite, apContext, true /*aNeedStatusCode=true*/); + ValidateCommandHandlerEncodeInvokeResponseMessage(true /*aNeedStatusCode=true*/); } -void TestCommandInteraction::TestCommandHandlerWithoutResponderCallingAddStatus(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_WithoutResponderCallingAddStatus) { chip::app::ConcreteCommandPath requestCommandPath(kTestEndpointId, kTestClusterId, kTestCommandIdWithData); CommandHandlerImpl commandHandler(&mockCommandHandlerDelegate); @@ -1305,25 +1177,23 @@ void TestCommandInteraction::TestCommandHandlerWithoutResponderCallingAddStatus( // Since calling AddStatus is supposed to be a no-operation when there is no responder, it is // hard to validate. Best way is to check that we are still in an Idle state afterwards - NL_TEST_ASSERT(apSuite, commandHandler.TestOnlyIsInIdleState()); + EXPECT_TRUE(commandHandler.TestOnlyIsInIdleState()); } -void TestCommandInteraction::TestCommandHandlerWithoutResponderCallingAddResponse(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_WithoutResponderCallingAddResponse) { chip::app::ConcreteCommandPath requestCommandPath(kTestEndpointId, kTestClusterId, kTestCommandIdWithData); CommandHandlerImpl commandHandler(&mockCommandHandlerDelegate); uint32_t sizeToFill = 50; // This is an arbitrary number, we need to select a non-zero value. - CHIP_ERROR err = commandHandler.AddResponseData(requestCommandPath, ForcedSizeBuffer(sizeToFill)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandHandler.AddResponseData(requestCommandPath, ForcedSizeBuffer(sizeToFill)), CHIP_NO_ERROR); // Since calling AddResponseData is supposed to be a no-operation when there is no responder, it is // hard to validate. Best way is to check that we are still in an Idle state afterwards - NL_TEST_ASSERT(apSuite, commandHandler.TestOnlyIsInIdleState()); + EXPECT_TRUE(commandHandler.TestOnlyIsInIdleState()); } -void TestCommandInteraction::TestCommandHandlerWithoutResponderCallingDirectPrepareFinishCommandApis(nlTestSuite * apSuite, - void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_WithoutResponderCallingDirectPrepareFinishCommandApis) { chip::app::ConcreteCommandPath requestCommandPath(kTestEndpointId, kTestClusterId, kTestCommandIdWithData); CommandHandlerImpl commandHandler(&mockCommandHandlerDelegate); @@ -1334,23 +1204,21 @@ void TestCommandInteraction::TestCommandHandlerWithoutResponderCallingDirectPrep // these primitives. const CommandHandlerImpl::InvokeResponseParameters prepareParams(requestCommandPath); ConcreteCommandPath responseCommandPath = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; - CHIP_ERROR err = commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams), CHIP_ERROR_INCORRECT_STATE); - NL_TEST_ASSERT(apSuite, commandHandler.GetCommandDataIBTLVWriter() == nullptr); + EXPECT_EQ(commandHandler.GetCommandDataIBTLVWriter(), nullptr); - err = commandHandler.FinishCommand(); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(commandHandler.FinishCommand(), CHIP_ERROR_INCORRECT_STATE); - NL_TEST_ASSERT(apSuite, commandHandler.TestOnlyIsInIdleState()); + EXPECT_TRUE(commandHandler.TestOnlyIsInIdleState()); } -void TestCommandInteraction::TestCommandHandlerWithOnInvokeReceivedNotExistCommand(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandler_WithOnInvokeReceivedNotExistCommand) { System::PacketBufferHandle commandDatabuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); // Use some invalid endpoint / cluster / command. - GenerateInvokeRequest(apSuite, apContext, commandDatabuf, /* aIsTimedRequest = */ false, 0xEF /* command */, - 0xADBE /* cluster */, 0xDE /* endpoint */); + GenerateInvokeRequest(commandDatabuf, /* aIsTimedRequest = */ false, 0xEF /* command */, 0xADBE /* cluster */, + 0xDE /* endpoint */); CommandHandlerImpl commandHandler(&mockCommandHandlerDelegate); chip::isCommandDispatched = false; @@ -1358,13 +1226,13 @@ void TestCommandInteraction::TestCommandHandlerWithOnInvokeReceivedNotExistComma MockCommandResponder mockCommandResponder; InteractionModel::Status status = commandHandler.OnInvokeCommandRequest(mockCommandResponder, std::move(commandDatabuf), false); - NL_TEST_ASSERT(apSuite, status == Protocols::InteractionModel::Status::InvalidAction); - NL_TEST_ASSERT(apSuite, mockCommandResponder.mChunks.IsNull()); + EXPECT_EQ(status, Protocols::InteractionModel::Status::InvalidAction); + EXPECT_TRUE(mockCommandResponder.mChunks.IsNull()); // TODO we can further validate the response is what we expected. - NL_TEST_ASSERT(apSuite, !chip::isCommandDispatched); + EXPECT_FALSE(chip::isCommandDispatched); } -void TestCommandInteraction::TestCommandHandlerWithOnInvokeReceivedEmptyDataMsg(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandler_WithOnInvokeReceivedEmptyDataMsg) { bool allBooleans[] = { true, false }; for (auto messageIsTimed : allBooleans) @@ -1376,78 +1244,68 @@ void TestCommandInteraction::TestCommandHandlerWithOnInvokeReceivedEmptyDataMsg( System::PacketBufferHandle commandDatabuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); chip::isCommandDispatched = false; - GenerateInvokeRequest(apSuite, apContext, commandDatabuf, messageIsTimed, kTestCommandIdNoData); + GenerateInvokeRequest(commandDatabuf, messageIsTimed, kTestCommandIdNoData); MockCommandResponder mockCommandResponder; Protocols::InteractionModel::Status status = commandHandler.OnInvokeCommandRequest(mockCommandResponder, std::move(commandDatabuf), transactionIsTimed); if (messageIsTimed != transactionIsTimed) { - NL_TEST_ASSERT(apSuite, status == Protocols::InteractionModel::Status::TimedRequestMismatch); - NL_TEST_ASSERT(apSuite, mockCommandResponder.mChunks.IsNull()); + EXPECT_EQ(status, Protocols::InteractionModel::Status::TimedRequestMismatch); + EXPECT_TRUE(mockCommandResponder.mChunks.IsNull()); } else { - NL_TEST_ASSERT(apSuite, status == Protocols::InteractionModel::Status::Success); - NL_TEST_ASSERT(apSuite, !mockCommandResponder.mChunks.IsNull()); + EXPECT_EQ(status, Protocols::InteractionModel::Status::Success); + EXPECT_FALSE(mockCommandResponder.mChunks.IsNull()); } - NL_TEST_ASSERT(apSuite, chip::isCommandDispatched == (messageIsTimed == transactionIsTimed)); + EXPECT_TRUE(chip::isCommandDispatched == (messageIsTimed == transactionIsTimed)); } } } -void TestCommandInteraction::TestCommandSenderLegacyCallbackUnsupportedCommand(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandSenderLegacyCallbackUnsupportedCommand) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender, kTestNonExistCommandId); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + AddInvokeRequestData(&commandSender, kTestNonExistCommandId); + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 1 && - mockCommandSenderDelegate.onErrorCalledTimes == 1); - - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 1); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } // Because UnsupportedCommand is a path specific error we will expect it to come via on response when using Extended Path. -void TestCommandInteraction::TestCommandSenderExtendableCallbackUnsupportedCommand(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandSender_ExtendableCallbackUnsupportedCommand) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderExtendedDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderExtendedDelegate, &mpTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender, kTestNonExistCommandId); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + AddInvokeRequestData(&commandSender, kTestNonExistCommandId); + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, - mockCommandSenderExtendedDelegate.onResponseCalledTimes == 1 && - mockCommandSenderExtendedDelegate.onFinalCalledTimes == 1 && - mockCommandSenderExtendedDelegate.onErrorCalledTimes == 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onResponseCalledTimes, 1); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onFinalCalledTimes, 1); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onErrorCalledTimes, 0); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestCommandInteraction::TestCommandSenderLegacyCallbackBuildingBatchCommandFails(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandSenderLegacyCallbackBuildingBatchCommandFails) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); app::CommandSender::PrepareCommandParameters prepareCommandParams; app::CommandSender::FinishCommandParameters finishCommandParams; prepareCommandParams.SetStartDataStruct(true).SetCommandRef(0); @@ -1455,79 +1313,63 @@ void TestCommandInteraction::TestCommandSenderLegacyCallbackBuildingBatchCommand CommandSender::ConfigParameters config; config.SetRemoteMaxPathsPerInvoke(2); - err = commandSender.SetCommandSenderConfig(config); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); + EXPECT_EQ(commandSender.SetCommandSenderConfig(config), CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); // Even though we got an error saying invalid argument we are going to attempt // to add two commands. auto commandPathParams = MakeTestCommandPath(); - err = commandSender.PrepareCommand(commandPathParams, prepareCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandSender.PrepareCommand(commandPathParams, prepareCommandParams), CHIP_NO_ERROR); chip::TLV::TLVWriter * writer = commandSender.GetCommandDataIBTLVWriter(); - err = writer->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = commandSender.FinishCommand(finishCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writer->PutBoolean(chip::TLV::ContextTag(1), true), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.FinishCommand(finishCommandParams), CHIP_NO_ERROR); // Preparing second command. prepareCommandParams.SetCommandRef(1); - err = commandSender.PrepareCommand(commandPathParams, prepareCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(commandSender.PrepareCommand(commandPathParams, prepareCommandParams), CHIP_ERROR_INCORRECT_STATE); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestCommandInteraction::TestCommandSenderExtendableCallbackBuildingBatchDuplicateCommandRefFails(nlTestSuite * apSuite, - void * apContext) +TEST_F(TestCommandInteraction, TestCommandSender_ExtendableCallbackBuildingBatchDuplicateCommandRefFails) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager(), - &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &mpTestContext->GetExchangeManager(), &pendingResponseTracker); app::CommandSender::PrepareCommandParameters prepareCommandParams; app::CommandSender::FinishCommandParameters finishCommandParams; CommandSender::ConfigParameters config; config.SetRemoteMaxPathsPerInvoke(2); - err = commandSender.SetCommandSenderConfig(config); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SetCommandSenderConfig(config), CHIP_NO_ERROR); prepareCommandParams.SetStartDataStruct(true).SetCommandRef(0); finishCommandParams.SetEndDataStruct(true).SetCommandRef(0); auto commandPathParams = MakeTestCommandPath(); - err = commandSender.PrepareCommand(commandPathParams, prepareCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandSender.PrepareCommand(commandPathParams, prepareCommandParams), CHIP_NO_ERROR); chip::TLV::TLVWriter * writer = commandSender.GetCommandDataIBTLVWriter(); - err = writer->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = commandSender.FinishCommand(finishCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writer->PutBoolean(chip::TLV::ContextTag(1), true), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.FinishCommand(finishCommandParams), CHIP_NO_ERROR); // Preparing second command. prepareCommandParams.SetCommandRef(0); - err = commandSender.PrepareCommand(commandPathParams, prepareCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(commandSender.PrepareCommand(commandPathParams, prepareCommandParams), CHIP_ERROR_INVALID_ARGUMENT); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestCommandInteraction::TestCommandSenderExtendableCallbackBuildingBatchCommandSuccess(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandSender_ExtendableCallbackBuildingBatchCommandSuccess) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager(), - &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &mpTestContext->GetExchangeManager(), &pendingResponseTracker); app::CommandSender::PrepareCommandParameters prepareCommandParams; app::CommandSender::FinishCommandParameters finishCommandParams; CommandSender::ConfigParameters config; config.SetRemoteMaxPathsPerInvoke(2); - err = commandSender.SetCommandSenderConfig(config); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SetCommandSenderConfig(config), CHIP_NO_ERROR); // The specific values chosen here are arbitrary. This test primarily verifies that we can // use a larger command reference value followed by a smaller one for subsequent command. @@ -1536,141 +1378,115 @@ void TestCommandInteraction::TestCommandSenderExtendableCallbackBuildingBatchCom prepareCommandParams.SetStartDataStruct(true).SetCommandRef(firstCommandRef); finishCommandParams.SetEndDataStruct(true).SetCommandRef(firstCommandRef); auto commandPathParams = MakeTestCommandPath(); - err = commandSender.PrepareCommand(commandPathParams, prepareCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandSender.PrepareCommand(commandPathParams, prepareCommandParams), CHIP_NO_ERROR); chip::TLV::TLVWriter * writer = commandSender.GetCommandDataIBTLVWriter(); - err = writer->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = commandSender.FinishCommand(finishCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writer->PutBoolean(chip::TLV::ContextTag(1), true), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.FinishCommand(finishCommandParams), CHIP_NO_ERROR); // Preparing second command. prepareCommandParams.SetCommandRef(secondCommandRef); finishCommandParams.SetCommandRef(secondCommandRef); - err = commandSender.PrepareCommand(commandPathParams, prepareCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandSender.PrepareCommand(commandPathParams, prepareCommandParams), CHIP_NO_ERROR); writer = commandSender.GetCommandDataIBTLVWriter(); - err = writer->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = commandSender.FinishCommand(finishCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writer->PutBoolean(chip::TLV::ContextTag(1), true), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.FinishCommand(finishCommandParams), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestCommandInteraction::TestCommandSenderCommandSuccessResponseFlow(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandSenderCommandSuccessResponseFlow) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); + AddInvokeRequestData(&commandSender); + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.GetInvokeResponseMessageCount(), 0u); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, commandSender.GetInvokeResponseMessageCount() == 0); + mpTestContext->DrainAndServiceIO(); - ctx.DrainAndServiceIO(); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 0); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 1 && mockCommandSenderDelegate.onFinalCalledTimes == 1 && - mockCommandSenderDelegate.onErrorCalledTimes == 0); - NL_TEST_ASSERT(apSuite, commandSender.GetInvokeResponseMessageCount() == 1); + EXPECT_EQ(commandSender.GetInvokeResponseMessageCount(), 1u); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestCommandInteraction::TestCommandSenderCommandAsyncSuccessResponseFlow(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandSenderCommandAsyncSuccessResponseFlow) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender); + AddInvokeRequestData(&commandSender); asyncCommand = true; - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 0 && - mockCommandSenderDelegate.onErrorCalledTimes == 0); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 1); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 2); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 1u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 2u); // Decrease CommandHandler refcount and send response asyncCommandHandle = nullptr; - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 1 && mockCommandSenderDelegate.onFinalCalledTimes == 1 && - mockCommandSenderDelegate.onErrorCalledTimes == 0); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 0); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestCommandInteraction::TestCommandSenderCommandSpecificResponseFlow(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandSenderCommandSpecificResponseFlow) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); - - AddInvokeRequestData(apSuite, apContext, &commandSender, kTestCommandIdCommandSpecificResponse); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + AddInvokeRequestData(&commandSender, kTestCommandIdCommandSpecificResponse); + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 1 && mockCommandSenderDelegate.onFinalCalledTimes == 1 && - mockCommandSenderDelegate.onErrorCalledTimes == 0); - - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestCommandInteraction::TestCommandSenderCommandFailureResponseFlow(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandSenderCommandFailureResponseFlow) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); - - AddInvokeRequestData(apSuite, apContext, &commandSender, kTestNonExistCommandId); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); - ctx.DrainAndServiceIO(); + AddInvokeRequestData(&commandSender, kTestNonExistCommandId); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 1 && - mockCommandSenderDelegate.onErrorCalledTimes == 1); - - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 1); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestCommandInteraction::TestCommandSenderAbruptDestruction(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandSenderAbruptDestruction) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; // // Don't send back a response, just keep the CommandHandler @@ -1681,47 +1497,44 @@ void TestCommandInteraction::TestCommandSenderAbruptDestruction(nlTestSuite * ap mockCommandSenderDelegate.ResetCounter(); { - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender, kTestCommandIdCommandSpecificResponse); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); + AddInvokeRequestData(&commandSender, kTestCommandIdCommandSpecificResponse); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // // No callbacks should be invoked yet - let's validate that. // - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 0 && - mockCommandSenderDelegate.onErrorCalledTimes == 0); + EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 0); + EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 1); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 1u); } // // Upon the sender being destructed by the application, our exchange should get cleaned up too. // - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); } -void TestCommandInteraction::TestCommandHandlerRejectMultipleIdenticalCommands(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandler_RejectMultipleIdenticalCommands) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; isCommandDispatched = false; mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager(), - &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &mpTestContext->GetExchangeManager(), &pendingResponseTracker); app::CommandSender::ConfigParameters configParameters; configParameters.SetRemoteMaxPathsPerInvoke(2); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == commandSender.SetCommandSenderConfig(configParameters)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.SetCommandSenderConfig(configParameters)); // Command ID is not important here, since the command handler should reject the commands without handling it. auto commandPathParams = MakeTestCommandPath(kTestCommandIdCommandSpecificResponse); @@ -1731,49 +1544,42 @@ void TestCommandInteraction::TestCommandHandlerRejectMultipleIdenticalCommands(n app::CommandSender::PrepareCommandParameters prepareCommandParams; prepareCommandParams.SetStartDataStruct(true); prepareCommandParams.SetCommandRef(i); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == commandSender.PrepareCommand(commandPathParams, prepareCommandParams)); - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == commandSender.GetCommandDataIBTLVWriter()->PutBoolean(chip::TLV::ContextTag(1), true)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.PrepareCommand(commandPathParams, prepareCommandParams)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.GetCommandDataIBTLVWriter()->PutBoolean(chip::TLV::ContextTag(1), true)); app::CommandSender::FinishCommandParameters finishCommandParams; finishCommandParams.SetEndDataStruct(true); finishCommandParams.SetCommandRef(i); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == commandSender.FinishCommand(finishCommandParams)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.FinishCommand(finishCommandParams)); } - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, - mockCommandSenderExtendedDelegate.onResponseCalledTimes == 0 && - mockCommandSenderExtendedDelegate.onFinalCalledTimes == 1 && - mockCommandSenderExtendedDelegate.onErrorCalledTimes == 1); - NL_TEST_ASSERT(apSuite, !chip::isCommandDispatched); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onFinalCalledTimes, 1); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onErrorCalledTimes, 1); + EXPECT_FALSE(chip::isCommandDispatched); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } #if CONFIG_BUILD_FOR_HOST_UNIT_TEST -void TestCommandInteraction::TestCommandHandlerRejectsMultipleCommandsWithIdenticalCommandRef(nlTestSuite * apSuite, - void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_RejectsMultipleCommandsWithIdenticalCommandRef) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; isCommandDispatched = false; mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager(), - &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &mpTestContext->GetExchangeManager(), &pendingResponseTracker); app::CommandSender::ConfigParameters configParameters; configParameters.SetRemoteMaxPathsPerInvoke(2); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == commandSender.SetCommandSenderConfig(configParameters)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.SetCommandSenderConfig(configParameters)); uint16_t numberOfCommandsToSend = 2; { @@ -1789,16 +1595,15 @@ void TestCommandInteraction::TestCommandHandlerRejectsMultipleCommandsWithIdenti app::CommandSender::PrepareCommandParameters prepareCommandParams; prepareCommandParams.SetStartDataStruct(true); prepareCommandParams.SetCommandRef(i); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == commandSender.PrepareCommand(requestCommandPaths[i], prepareCommandParams)); - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == commandSender.GetCommandDataIBTLVWriter()->PutBoolean(chip::TLV::ContextTag(1), true)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.PrepareCommand(requestCommandPaths[i], prepareCommandParams)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.GetCommandDataIBTLVWriter()->PutBoolean(chip::TLV::ContextTag(1), true)); // TODO fix this comment // We are taking advantage of the fact that the commandRef was set into finishCommandParams during PrepareCommand // But setting it to a different value here, we are overriding what it was supposed to be. app::CommandSender::FinishCommandParameters finishCommandParams; finishCommandParams.SetEndDataStruct(true); finishCommandParams.SetCommandRef(hardcodedCommandRef); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == commandSender.TestOnlyFinishCommand(finishCommandParams)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.TestOnlyFinishCommand(finishCommandParams)); } } @@ -1809,36 +1614,32 @@ void TestCommandInteraction::TestCommandHandlerRejectsMultipleCommandsWithIdenti // Hackery to steal the InvokeRequest buffer from commandSender. System::PacketBufferHandle commandDatabuf; - err = commandSender.Finalize(commandDatabuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandSender.Finalize(commandDatabuf), CHIP_NO_ERROR); mockCommandHandlerDelegate.ResetCounter(); commandDispatchedCount = 0; InteractionModel::Status status = commandHandler.ProcessInvokeRequest(std::move(commandDatabuf), false); - NL_TEST_ASSERT(apSuite, status == InteractionModel::Status::InvalidAction); + EXPECT_EQ(status, InteractionModel::Status::InvalidAction); - NL_TEST_ASSERT(apSuite, commandDispatchedCount == 0); + EXPECT_EQ(commandDispatchedCount, 0u); } #endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST -void TestCommandInteraction::TestCommandHandlerRejectMultipleCommandsWhenHandlerOnlySupportsOne(nlTestSuite * apSuite, - void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_RejectMultipleCommandsWhenHandlerOnlySupportsOne) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; isCommandDispatched = false; mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager(), - &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &mpTestContext->GetExchangeManager(), &pendingResponseTracker); app::CommandSender::ConfigParameters configParameters; configParameters.SetRemoteMaxPathsPerInvoke(2); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == commandSender.SetCommandSenderConfig(configParameters)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.SetCommandSenderConfig(configParameters)); uint16_t numberOfCommandsToSend = 2; { @@ -1852,20 +1653,18 @@ void TestCommandInteraction::TestCommandHandlerRejectMultipleCommandsWhenHandler app::CommandSender::PrepareCommandParameters prepareCommandParams; prepareCommandParams.SetStartDataStruct(true); prepareCommandParams.SetCommandRef(i); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == commandSender.PrepareCommand(requestCommandPaths[i], prepareCommandParams)); - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == commandSender.GetCommandDataIBTLVWriter()->PutBoolean(chip::TLV::ContextTag(1), true)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.PrepareCommand(requestCommandPaths[i], prepareCommandParams)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.GetCommandDataIBTLVWriter()->PutBoolean(chip::TLV::ContextTag(1), true)); app::CommandSender::FinishCommandParameters finishCommandParams; finishCommandParams.SetEndDataStruct(true); finishCommandParams.SetCommandRef(i); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == commandSender.FinishCommand(finishCommandParams)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.FinishCommand(finishCommandParams)); } } // Hackery to steal the InvokeRequest buffer from commandSender. System::PacketBufferHandle commandDatabuf; - err = commandSender.Finalize(commandDatabuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandSender.Finalize(commandDatabuf), CHIP_NO_ERROR); mockCommandHandlerDelegate.ResetCounter(); sendResponse = true; @@ -1874,27 +1673,25 @@ void TestCommandInteraction::TestCommandHandlerRejectMultipleCommandsWhenHandler CommandHandlerImpl commandHandler(&mockCommandHandlerDelegate); MockCommandResponder mockCommandResponder; InteractionModel::Status status = commandHandler.OnInvokeCommandRequest(mockCommandResponder, std::move(commandDatabuf), false); - NL_TEST_ASSERT(apSuite, status == InteractionModel::Status::InvalidAction); - NL_TEST_ASSERT(apSuite, mockCommandResponder.mChunks.IsNull()); + EXPECT_EQ(status, InteractionModel::Status::InvalidAction); + EXPECT_TRUE(mockCommandResponder.mChunks.IsNull()); - NL_TEST_ASSERT(apSuite, commandDispatchedCount == 0); + EXPECT_EQ(commandDispatchedCount, 0u); } -void TestCommandInteraction::TestCommandHandlerAcceptMultipleCommands(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_AcceptMultipleCommands) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; isCommandDispatched = false; mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager(), - &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &mpTestContext->GetExchangeManager(), &pendingResponseTracker); app::CommandSender::ConfigParameters configParameters; configParameters.SetRemoteMaxPathsPerInvoke(2); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == commandSender.SetCommandSenderConfig(configParameters)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.SetCommandSenderConfig(configParameters)); uint16_t numberOfCommandsToSend = 2; { @@ -1908,15 +1705,13 @@ void TestCommandInteraction::TestCommandHandlerAcceptMultipleCommands(nlTestSuit app::CommandSender::PrepareCommandParameters prepareCommandParams; prepareCommandParams.SetStartDataStruct(true); prepareCommandParams.SetCommandRef(i); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == commandSender.PrepareCommand(requestCommandPaths[i], prepareCommandParams)); - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == commandSender.GetCommandDataIBTLVWriter()->PutBoolean(chip::TLV::ContextTag(1), true)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.PrepareCommand(requestCommandPaths[i], prepareCommandParams)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.GetCommandDataIBTLVWriter()->PutBoolean(chip::TLV::ContextTag(1), true)); app::CommandSender::FinishCommandParameters finishCommandParams; finishCommandParams.SetEndDataStruct(true); finishCommandParams.SetCommandRef(i); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == commandSender.FinishCommand(finishCommandParams)); + EXPECT_EQ(CHIP_NO_ERROR, commandSender.FinishCommand(finishCommandParams)); } - commandSender.MoveToState(app::CommandSender::State::AddedCommand); } @@ -1927,21 +1722,19 @@ void TestCommandInteraction::TestCommandHandlerAcceptMultipleCommands(nlTestSuit // Hackery to steal the InvokeRequest buffer from commandSender. System::PacketBufferHandle commandDatabuf; - err = commandSender.Finalize(commandDatabuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandSender.Finalize(commandDatabuf), CHIP_NO_ERROR); sendResponse = true; mockCommandHandlerDelegate.ResetCounter(); commandDispatchedCount = 0; InteractionModel::Status status = commandHandler.ProcessInvokeRequest(std::move(commandDatabuf), false); - NL_TEST_ASSERT(apSuite, status == InteractionModel::Status::Success); + EXPECT_EQ(status, InteractionModel::Status::Success); - NL_TEST_ASSERT(apSuite, commandDispatchedCount == 2); + EXPECT_EQ(commandDispatchedCount, 2u); } -void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsStatusResponse( - nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsStatusResponse) { BasicCommandPathRegistry<4> basicCommandPathRegistry; MockCommandResponder mockCommandResponder; @@ -1952,25 +1745,24 @@ void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhere ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; - CHIP_ERROR err = basicCommandPathRegistry.Add(requestCommandPath1, std::make_optional(static_cast(1))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(basicCommandPathRegistry.Add(requestCommandPath1, std::make_optional(static_cast(1))), + CHIP_NO_ERROR); + EXPECT_EQ(basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))), + CHIP_NO_ERROR); uint32_t sizeToLeave = 0; - FillCurrentInvokeResponseBuffer(apSuite, &commandHandler, requestCommandPath1, sizeToLeave); + FillCurrentInvokeResponseBuffer(&commandHandler, requestCommandPath1, sizeToLeave); uint32_t remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize == sizeToLeave); + EXPECT_EQ(remainingSize, sizeToLeave); - AddInvokeResponseData(apSuite, apContext, &commandHandler, /* aNeedStatusCode = */ true, kTestCommandIdCommandSpecificResponse, + AddInvokeResponseData(&commandHandler, /* aNeedStatusCode = */ true, kTestCommandIdCommandSpecificResponse, kTestCommandIdCommandSpecificResponse); remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize > sizeToLeave); + EXPECT_GT(remainingSize, sizeToLeave); } - -void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponsePrimative( - nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, + TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponsePrimative) { BasicCommandPathRegistry<4> basicCommandPathRegistry; MockCommandResponder mockCommandResponder; @@ -1981,25 +1773,24 @@ void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhere ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; - CHIP_ERROR err = basicCommandPathRegistry.Add(requestCommandPath1, std::make_optional(static_cast(1))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(basicCommandPathRegistry.Add(requestCommandPath1, std::make_optional(static_cast(1))), + CHIP_NO_ERROR); + EXPECT_EQ(basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))), + CHIP_NO_ERROR); uint32_t sizeToLeave = 0; - FillCurrentInvokeResponseBuffer(apSuite, &commandHandler, requestCommandPath1, sizeToLeave); + FillCurrentInvokeResponseBuffer(&commandHandler, requestCommandPath1, sizeToLeave); uint32_t remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize == sizeToLeave); + EXPECT_EQ(remainingSize, sizeToLeave); - AddInvokeResponseData(apSuite, apContext, &commandHandler, /* aNeedStatusCode = */ false, kTestCommandIdCommandSpecificResponse, + AddInvokeResponseData(&commandHandler, /* aNeedStatusCode = */ false, kTestCommandIdCommandSpecificResponse, kTestCommandIdCommandSpecificResponse); remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize > sizeToLeave); + EXPECT_GT(remainingSize, sizeToLeave); } -void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponse(nlTestSuite * apSuite, - void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponse) { BasicCommandPathRegistry<4> basicCommandPathRegistry; MockCommandResponder mockCommandResponder; @@ -2009,22 +1800,21 @@ void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhere ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; - CHIP_ERROR err = basicCommandPathRegistry.Add(requestCommandPath1, std::make_optional(static_cast(1))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(basicCommandPathRegistry.Add(requestCommandPath1, std::make_optional(static_cast(1))), + CHIP_NO_ERROR); + EXPECT_EQ(basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))), + CHIP_NO_ERROR); uint32_t sizeToLeave = 0; - FillCurrentInvokeResponseBuffer(apSuite, &commandHandler, requestCommandPath1, sizeToLeave); + FillCurrentInvokeResponseBuffer(&commandHandler, requestCommandPath1, sizeToLeave); uint32_t remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize == sizeToLeave); + EXPECT_EQ(remainingSize, sizeToLeave); uint32_t sizeToFill = 50; - err = commandHandler.AddResponseData(requestCommandPath2, ForcedSizeBuffer(sizeToFill)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandHandler.AddResponseData(requestCommandPath2, ForcedSizeBuffer(sizeToFill)), CHIP_NO_ERROR); remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize > sizeToLeave); + EXPECT_GT(remainingSize, sizeToLeave); } #if CONFIG_BUILD_FOR_HOST_UNIT_TEST @@ -2032,24 +1822,21 @@ void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhere // This test needs a special unit-test only API being exposed in ExchangeContext to be able to correctly simulate // the release of a session on the exchange. // -void TestCommandInteraction::TestCommandHandlerReleaseWithExchangeClosed(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_ReleaseWithExchangeClosed) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender); + AddInvokeRequestData(&commandSender); asyncCommandHandle = nullptr; asyncCommand = true; - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // Verify that async command handle has been allocated - NL_TEST_ASSERT(apSuite, asyncCommandHandle.Get() != nullptr); + ASSERT_NE(asyncCommandHandle.Get(), nullptr); // Mimic closure of the exchange that would happen on a session release and verify that releasing the handle there-after // is handled gracefully. @@ -2061,79 +1848,3 @@ void TestCommandInteraction::TestCommandHandlerReleaseWithExchangeClosed(nlTestS } // namespace app } // namespace chip - -namespace { -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("TestCommandInvalidMessage1", chip::app::TestCommandInteraction::TestCommandInvalidMessage1), - NL_TEST_DEF("TestCommandInvalidMessage2", chip::app::TestCommandInteraction::TestCommandInvalidMessage2), - NL_TEST_DEF("TestCommandInvalidMessage3", chip::app::TestCommandInteraction::TestCommandInvalidMessage3), - NL_TEST_DEF("TestCommandInvalidMessage4", chip::app::TestCommandInteraction::TestCommandInvalidMessage4), - NL_TEST_DEF("TestCommandSenderWithWrongState", chip::app::TestCommandInteraction::TestCommandSenderWithWrongState), - NL_TEST_DEF("TestCommandHandlerWithWrongState", chip::app::TestCommandInteraction::TestCommandHandlerWithWrongState), - NL_TEST_DEF("TestCommandSenderWithSendCommand", chip::app::TestCommandInteraction::TestCommandSenderWithSendCommand), - NL_TEST_DEF("TestCommandHandlerWithSendEmptyCommand", chip::app::TestCommandInteraction::TestCommandHandlerWithSendEmptyCommand), - NL_TEST_DEF("TestCommandSenderWithProcessReceivedMsg", chip::app::TestCommandInteraction::TestCommandSenderWithProcessReceivedMsg), - NL_TEST_DEF("TestCommandSenderExtendableApiWithProcessReceivedMsg", chip::app::TestCommandInteraction::TestCommandSenderExtendableApiWithProcessReceivedMsg), - NL_TEST_DEF("TestCommandSenderExtendableApiWithProcessReceivedMsgContainingInvalidCommandRef", chip::app::TestCommandInteraction::TestCommandSenderExtendableApiWithProcessReceivedMsgContainingInvalidCommandRef), - NL_TEST_DEF("TestCommandHandlerEncodeSimpleCommandData", chip::app::TestCommandInteraction::TestCommandHandlerEncodeSimpleCommandData), - NL_TEST_DEF("TestCommandHandlerCommandDataEncoding", chip::app::TestCommandInteraction::TestCommandHandlerCommandDataEncoding), - NL_TEST_DEF("TestCommandHandlerCommandEncodeFailure", chip::app::TestCommandInteraction::TestCommandHandlerCommandEncodeFailure), - NL_TEST_DEF("TestCommandHandlerCommandEncodeExternalFailure", chip::app::TestCommandInteraction::TestCommandHandlerCommandEncodeExternalFailure), - NL_TEST_DEF("TestCommandHandlerEncodeSimpleStatusCode", chip::app::TestCommandInteraction::TestCommandHandlerEncodeSimpleStatusCode), - NL_TEST_DEF("TestCommandHandlerWithoutResponderCallingAddStatus", chip::app::TestCommandInteraction::TestCommandHandlerWithoutResponderCallingAddStatus), - NL_TEST_DEF("TestCommandHandlerWithoutResponderCallingAddResponse", chip::app::TestCommandInteraction::TestCommandHandlerWithoutResponderCallingAddResponse), - NL_TEST_DEF("TestCommandHandlerWithoutResponderCallingDirectPrepareFinishCommandApis", chip::app::TestCommandInteraction::TestCommandHandlerWithoutResponderCallingDirectPrepareFinishCommandApis), - NL_TEST_DEF("TestCommandHandlerWithOnInvokeReceivedNotExistCommand", chip::app::TestCommandInteraction::TestCommandHandlerWithOnInvokeReceivedNotExistCommand), - NL_TEST_DEF("TestCommandHandlerWithOnInvokeReceivedEmptyDataMsg", chip::app::TestCommandInteraction::TestCommandHandlerWithOnInvokeReceivedEmptyDataMsg), - NL_TEST_DEF("TestCommandHandlerRejectMultipleIdenticalCommands", chip::app::TestCommandInteraction::TestCommandHandlerRejectMultipleIdenticalCommands), -#if CONFIG_BUILD_FOR_HOST_UNIT_TEST - NL_TEST_DEF("TestCommandHandlerRejectsMultipleCommandsWithIdenticalCommandRef", chip::app::TestCommandInteraction::TestCommandHandlerRejectsMultipleCommandsWithIdenticalCommandRef), -#endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST - NL_TEST_DEF("TestCommandHandlerRejectMultipleCommandsWhenHandlerOnlySupportsOne", chip::app::TestCommandInteraction::TestCommandHandlerRejectMultipleCommandsWhenHandlerOnlySupportsOne), - NL_TEST_DEF("TestCommandHandlerAcceptMultipleCommands", chip::app::TestCommandInteraction::TestCommandHandlerAcceptMultipleCommands), - NL_TEST_DEF("TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsStatusResponse", chip::app::TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsStatusResponse), - NL_TEST_DEF("TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponsePrimative", chip::app::TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponsePrimative), - NL_TEST_DEF("TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponse", chip::app::TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponse), - - -#if CONFIG_BUILD_FOR_HOST_UNIT_TEST - NL_TEST_DEF("TestCommandHandlerReleaseWithExchangeClosed", chip::app::TestCommandInteraction::TestCommandHandlerReleaseWithExchangeClosed), -#endif - NL_TEST_DEF("TestCommandSenderLegacyCallbackUnsupportedCommand", chip::app::TestCommandInteraction::TestCommandSenderLegacyCallbackUnsupportedCommand), - NL_TEST_DEF("TestCommandSenderExtendableCallbackUnsupportedCommand", chip::app::TestCommandInteraction::TestCommandSenderExtendableCallbackUnsupportedCommand), - NL_TEST_DEF("TestCommandSenderLegacyCallbackBuildingBatchCommandFails", chip::app::TestCommandInteraction::TestCommandSenderLegacyCallbackBuildingBatchCommandFails), - NL_TEST_DEF("TestCommandSenderExtendableCallbackBuildingBatchDuplicateCommandRefFails", chip::app::TestCommandInteraction::TestCommandSenderExtendableCallbackBuildingBatchDuplicateCommandRefFails), - NL_TEST_DEF("TestCommandSenderExtendableCallbackBuildingBatchCommandSuccess", chip::app::TestCommandInteraction::TestCommandSenderExtendableCallbackBuildingBatchCommandSuccess), - NL_TEST_DEF("TestCommandSenderCommandSuccessResponseFlow", chip::app::TestCommandInteraction::TestCommandSenderCommandSuccessResponseFlow), - NL_TEST_DEF("TestCommandSenderCommandAsyncSuccessResponseFlow", chip::app::TestCommandInteraction::TestCommandSenderCommandAsyncSuccessResponseFlow), - NL_TEST_DEF("TestCommandSenderCommandSpecificResponseFlow", chip::app::TestCommandInteraction::TestCommandSenderCommandSpecificResponseFlow), - NL_TEST_DEF("TestCommandSenderCommandFailureResponseFlow", chip::app::TestCommandInteraction::TestCommandSenderCommandFailureResponseFlow), - NL_TEST_DEF("TestCommandSenderAbruptDestruction", chip::app::TestCommandInteraction::TestCommandSenderAbruptDestruction), - NL_TEST_DEF("TestCommandHandlerInvalidMessageSync", chip::app::TestCommandInteraction::TestCommandHandlerInvalidMessageSync), - NL_TEST_SENTINEL() -}; -// clang-format on - -// clang-format off -nlTestSuite sSuite = -{ - "TestCommandInteraction", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; -// clang-format on - -} // namespace - -int TestCommandInteraction() -{ - chip::gSuite = &sSuite; - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestCommandInteraction) diff --git a/src/app/tests/TestCommissionManager.cpp b/src/app/tests/TestCommissionManager.cpp deleted file mode 100644 index 188f51aee6a609..00000000000000 --- a/src/app/tests/TestCommissionManager.cpp +++ /dev/null @@ -1,434 +0,0 @@ -/* - * - * Copyright (c) 2021-2022 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 -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace chip::Crypto; - -using chip::CommissioningWindowAdvertisement; -using chip::CommissioningWindowManager; -using chip::Server; - -// Mock function for linking -void InitDataModelHandler() {} - -namespace { -bool sAdminFabricIndexDirty = false; -bool sAdminVendorIdDirty = false; -bool sWindowStatusDirty = false; - -void ResetDirtyFlags() -{ - sAdminFabricIndexDirty = false; - sAdminVendorIdDirty = false; - sWindowStatusDirty = false; -} - -} // namespace - -void MatterReportingAttributeChangeCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, chip::AttributeId attributeId) -{ - using namespace chip::app::Clusters; - using namespace chip::app::Clusters::AdministratorCommissioning::Attributes; - if (endpoint != chip::kRootEndpointId || clusterId != AdministratorCommissioning::Id) - { - return; - } - - switch (attributeId) - { - case WindowStatus::Id: - sWindowStatusDirty = true; - break; - case AdminVendorId::Id: - sAdminVendorIdDirty = true; - break; - case AdminFabricIndex::Id: - sAdminFabricIndexDirty = true; - break; - default: - break; - } -} - -namespace { - -static constexpr int kTestTaskWaitSeconds = 2; - -void InitializeChip(nlTestSuite * suite) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - err = chip::Platform::MemoryInit(); - NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); - err = chip::DeviceLayer::PlatformMgr().InitChipStack(); - NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); - - static chip::DeviceLayer::TestOnlyCommissionableDataProvider commissionableDataProvider; - chip::DeviceLayer::SetCommissionableDataProvider(&commissionableDataProvider); - - static chip::CommonCaseDeviceServerInitParams initParams; - // Report scheduler and timer delegate instance - static chip::app::DefaultTimerDelegate sTimerDelegate; - static chip::app::reporting::ReportSchedulerImpl sReportScheduler(&sTimerDelegate); - initParams.reportScheduler = &sReportScheduler; - static chip::SimpleTestEventTriggerDelegate sSimpleTestEventTriggerDelegate; - initParams.testEventTriggerDelegate = &sSimpleTestEventTriggerDelegate; - (void) initParams.InitializeStaticResourcesBeforeServerInit(); - // Set a randomized server port(slightly shifted from CHIP_PORT) for testing - initParams.operationalServicePort = static_cast(initParams.operationalServicePort + chip::Crypto::GetRandU16() % 20); - - err = chip::Server::GetInstance().Init(initParams); - - NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); - - Server::GetInstance().GetCommissioningWindowManager().CloseCommissioningWindow(); - chip::DeviceLayer::PlatformMgr().StartEventLoopTask(); -} - -void ShutdownChipTest() -{ - chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); - chip::DeviceLayer::PlatformMgr().Shutdown(); - - auto & mdnsAdvertiser = chip::Dnssd::ServiceAdvertiser::Instance(); - mdnsAdvertiser.RemoveServices(); - mdnsAdvertiser.Shutdown(); - - // Server shudown will be called in TearDownTask - - // TODO: At this point UDP endpoits still seem leaked and the sanitizer - // builds will attempt a memory free. As a result, we keep Memory initialized - // so that the global UDPManager can still be destructed without a coredump. - // - // This is likely either a missing shutdown or an actual UDP endpoint leak - // which I have not been able to track down yet. - // - // chip::Platform::MemoryShutdown(); -} - -void CheckCommissioningWindowManagerBasicWindowOpenCloseTask(intptr_t context) -{ - nlTestSuite * suite = reinterpret_cast(context); - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); - - CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); - CHIP_ERROR err = commissionMgr.OpenBasicCommissioningWindow(commissionMgr.MaxCommissioningTimeout(), - CommissioningWindowAdvertisement::kDnssdOnly); - NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(suite, commissionMgr.IsCommissioningWindowOpen()); - NL_TEST_ASSERT(suite, - commissionMgr.CommissioningWindowStatusForCluster() == - chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); - NL_TEST_ASSERT(suite, commissionMgr.GetOpenerFabricIndex().IsNull()); - NL_TEST_ASSERT(suite, commissionMgr.GetOpenerVendorId().IsNull()); - NL_TEST_ASSERT(suite, !chip::DeviceLayer::ConnectivityMgr().IsBLEAdvertisingEnabled()); - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); - - commissionMgr.CloseCommissioningWindow(); - NL_TEST_ASSERT(suite, !commissionMgr.IsCommissioningWindowOpen()); - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); -} - -void CheckCommissioningWindowManagerBasicWindowOpenClose(nlTestSuite * suite, void *) -{ - chip::DeviceLayer::PlatformMgr().ScheduleWork(CheckCommissioningWindowManagerBasicWindowOpenCloseTask, - reinterpret_cast(suite)); - sleep(kTestTaskWaitSeconds); -} - -void CheckCommissioningWindowManagerBasicWindowOpenCloseFromClusterTask(intptr_t context) -{ - nlTestSuite * suite = reinterpret_cast(context); - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); - - CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); - constexpr auto fabricIndex = static_cast(1); - constexpr auto vendorId = static_cast(0xFFF3); - CHIP_ERROR err = commissionMgr.OpenBasicCommissioningWindowForAdministratorCommissioningCluster( - commissionMgr.MaxCommissioningTimeout(), fabricIndex, vendorId); - NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(suite, commissionMgr.IsCommissioningWindowOpen()); - NL_TEST_ASSERT(suite, - commissionMgr.CommissioningWindowStatusForCluster() == - chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kBasicWindowOpen); - NL_TEST_ASSERT(suite, !commissionMgr.GetOpenerFabricIndex().IsNull()); - NL_TEST_ASSERT(suite, commissionMgr.GetOpenerFabricIndex().Value() == fabricIndex); - NL_TEST_ASSERT(suite, !commissionMgr.GetOpenerVendorId().IsNull()); - NL_TEST_ASSERT(suite, commissionMgr.GetOpenerVendorId().Value() == vendorId); - NL_TEST_ASSERT(suite, !chip::DeviceLayer::ConnectivityMgr().IsBLEAdvertisingEnabled()); - NL_TEST_ASSERT(suite, sWindowStatusDirty); - NL_TEST_ASSERT(suite, sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, sAdminVendorIdDirty); - - ResetDirtyFlags(); - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); - - commissionMgr.CloseCommissioningWindow(); - NL_TEST_ASSERT(suite, !commissionMgr.IsCommissioningWindowOpen()); - NL_TEST_ASSERT(suite, commissionMgr.GetOpenerFabricIndex().IsNull()); - NL_TEST_ASSERT(suite, commissionMgr.GetOpenerVendorId().IsNull()); - NL_TEST_ASSERT(suite, sWindowStatusDirty); - NL_TEST_ASSERT(suite, sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, sAdminVendorIdDirty); - - ResetDirtyFlags(); -} - -void CheckCommissioningWindowManagerBasicWindowOpenCloseFromCluster(nlTestSuite * suite, void *) -{ - chip::DeviceLayer::PlatformMgr().ScheduleWork(CheckCommissioningWindowManagerBasicWindowOpenCloseFromClusterTask, - reinterpret_cast(suite)); - sleep(kTestTaskWaitSeconds); -} - -void CheckCommissioningWindowManagerWindowClosedTask(chip::System::Layer *, void * context) -{ - nlTestSuite * suite = static_cast(context); - CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); - NL_TEST_ASSERT(suite, !commissionMgr.IsCommissioningWindowOpen()); - NL_TEST_ASSERT(suite, - commissionMgr.CommissioningWindowStatusForCluster() == - chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); -} - -void CheckCommissioningWindowManagerWindowTimeoutTask(intptr_t context) -{ - nlTestSuite * suite = reinterpret_cast(context); - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); - - CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); - constexpr auto kTimeoutSeconds = chip::System::Clock::Seconds32(1); - constexpr uint16_t kTimeoutMs = 1000; - constexpr unsigned kSleepPadding = 100; - commissionMgr.OverrideMinCommissioningTimeout(kTimeoutSeconds); - CHIP_ERROR err = commissionMgr.OpenBasicCommissioningWindow(kTimeoutSeconds, CommissioningWindowAdvertisement::kDnssdOnly); - NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(suite, commissionMgr.IsCommissioningWindowOpen()); - NL_TEST_ASSERT(suite, - commissionMgr.CommissioningWindowStatusForCluster() == - chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); - NL_TEST_ASSERT(suite, !chip::DeviceLayer::ConnectivityMgr().IsBLEAdvertisingEnabled()); - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); - - chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Milliseconds32(kTimeoutMs + kSleepPadding), - CheckCommissioningWindowManagerWindowClosedTask, suite); -} - -void CheckCommissioningWindowManagerWindowTimeout(nlTestSuite * suite, void *) -{ - chip::DeviceLayer::PlatformMgr().ScheduleWork(CheckCommissioningWindowManagerWindowTimeoutTask, - reinterpret_cast(suite)); - sleep(kTestTaskWaitSeconds); -} - -void SimulateFailedSessionEstablishmentTask(chip::System::Layer *, void * context) -{ - nlTestSuite * suite = static_cast(context); - CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); - NL_TEST_ASSERT(suite, commissionMgr.IsCommissioningWindowOpen()); - NL_TEST_ASSERT(suite, - commissionMgr.CommissioningWindowStatusForCluster() == - chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); - - commissionMgr.OnSessionEstablishmentStarted(); - commissionMgr.OnSessionEstablishmentError(CHIP_ERROR_INTERNAL); - NL_TEST_ASSERT(suite, commissionMgr.IsCommissioningWindowOpen()); - NL_TEST_ASSERT(suite, - commissionMgr.CommissioningWindowStatusForCluster() == - chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); -} - -void CheckCommissioningWindowManagerWindowTimeoutWithSessionEstablishmentErrorsTask(intptr_t context) -{ - nlTestSuite * suite = reinterpret_cast(context); - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); - - CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); - constexpr auto kTimeoutSeconds = chip::System::Clock::Seconds16(1); - constexpr uint16_t kTimeoutMs = 1000; - constexpr unsigned kSleepPadding = 100; - CHIP_ERROR err = commissionMgr.OpenBasicCommissioningWindow(kTimeoutSeconds, CommissioningWindowAdvertisement::kDnssdOnly); - NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(suite, commissionMgr.IsCommissioningWindowOpen()); - NL_TEST_ASSERT(suite, - commissionMgr.CommissioningWindowStatusForCluster() == - chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); - NL_TEST_ASSERT(suite, !chip::DeviceLayer::ConnectivityMgr().IsBLEAdvertisingEnabled()); - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); - - chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Milliseconds32(kTimeoutMs + kSleepPadding), - CheckCommissioningWindowManagerWindowClosedTask, suite); - // Simulate a session establishment error during that window, such that the - // delay for the error plus the window size exceeds our "timeout + padding" above. - chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Milliseconds32(kTimeoutMs / 4 * 3), - SimulateFailedSessionEstablishmentTask, suite); -} - -void CheckCommissioningWindowManagerWindowTimeoutWithSessionEstablishmentErrors(nlTestSuite * suite, void *) -{ - chip::DeviceLayer::PlatformMgr().ScheduleWork(CheckCommissioningWindowManagerWindowTimeoutWithSessionEstablishmentErrorsTask, - reinterpret_cast(suite)); - sleep(kTestTaskWaitSeconds); -} - -void CheckCommissioningWindowManagerEnhancedWindowTask(intptr_t context) -{ - nlTestSuite * suite = reinterpret_cast(context); - CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); - uint16_t originDiscriminator; - CHIP_ERROR err = chip::DeviceLayer::GetCommissionableDataProvider()->GetSetupDiscriminator(originDiscriminator); - NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); - uint16_t newDiscriminator = static_cast(originDiscriminator + 1); - Spake2pVerifier verifier; - constexpr uint32_t kIterations = kSpake2p_Min_PBKDF_Iterations; - uint8_t salt[kSpake2p_Min_PBKDF_Salt_Length]; - chip::ByteSpan saltData(salt); - - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); - - constexpr auto fabricIndex = static_cast(1); - constexpr auto vendorId = static_cast(0xFFF3); - err = commissionMgr.OpenEnhancedCommissioningWindow(commissionMgr.MaxCommissioningTimeout(), newDiscriminator, verifier, - kIterations, saltData, fabricIndex, vendorId); - NL_TEST_ASSERT(suite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(suite, commissionMgr.IsCommissioningWindowOpen()); - NL_TEST_ASSERT(suite, - commissionMgr.CommissioningWindowStatusForCluster() == - chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kEnhancedWindowOpen); - NL_TEST_ASSERT(suite, !chip::DeviceLayer::ConnectivityMgr().IsBLEAdvertisingEnabled()); - NL_TEST_ASSERT(suite, !commissionMgr.GetOpenerFabricIndex().IsNull()); - NL_TEST_ASSERT(suite, commissionMgr.GetOpenerFabricIndex().Value() == fabricIndex); - NL_TEST_ASSERT(suite, !commissionMgr.GetOpenerVendorId().IsNull()); - NL_TEST_ASSERT(suite, commissionMgr.GetOpenerVendorId().Value() == vendorId); - NL_TEST_ASSERT(suite, sWindowStatusDirty); - NL_TEST_ASSERT(suite, sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, sAdminVendorIdDirty); - - ResetDirtyFlags(); - NL_TEST_ASSERT(suite, !sWindowStatusDirty); - NL_TEST_ASSERT(suite, !sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, !sAdminVendorIdDirty); - - commissionMgr.CloseCommissioningWindow(); - NL_TEST_ASSERT(suite, !commissionMgr.IsCommissioningWindowOpen()); - NL_TEST_ASSERT(suite, - commissionMgr.CommissioningWindowStatusForCluster() == - chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); - NL_TEST_ASSERT(suite, commissionMgr.GetOpenerFabricIndex().IsNull()); - NL_TEST_ASSERT(suite, commissionMgr.GetOpenerVendorId().IsNull()); - NL_TEST_ASSERT(suite, sWindowStatusDirty); - NL_TEST_ASSERT(suite, sAdminFabricIndexDirty); - NL_TEST_ASSERT(suite, sAdminVendorIdDirty); - - ResetDirtyFlags(); -} - -void CheckCommissioningWindowManagerEnhancedWindow(nlTestSuite * suite, void *) -{ - chip::DeviceLayer::PlatformMgr().ScheduleWork(CheckCommissioningWindowManagerEnhancedWindowTask, - reinterpret_cast(suite)); - sleep(kTestTaskWaitSeconds); -} - -void TearDownTask(intptr_t context) -{ - chip::Server::GetInstance().Shutdown(); -} - -const nlTest sTests[] = { - NL_TEST_DEF("CheckCommissioningWindowManagerEnhancedWindow", CheckCommissioningWindowManagerEnhancedWindow), - NL_TEST_DEF("CheckCommissioningWindowManagerBasicWindowOpenClose", CheckCommissioningWindowManagerBasicWindowOpenClose), - NL_TEST_DEF("CheckCommissioningWindowManagerBasicWindowOpenCloseFromCluster", - CheckCommissioningWindowManagerBasicWindowOpenCloseFromCluster), - NL_TEST_DEF("CheckCommissioningWindowManagerWindowTimeout", CheckCommissioningWindowManagerWindowTimeout), - NL_TEST_DEF("CheckCommissioningWindowManagerWindowTimeoutWithSessionEstablishmentErrors", - CheckCommissioningWindowManagerWindowTimeoutWithSessionEstablishmentErrors), - NL_TEST_SENTINEL(), -}; - -} // namespace - -int TestCommissioningWindowManager() -{ - // clang-format off - nlTestSuite theSuite = - { - "CommissioningWindowManager", - &sTests[0], - nullptr, - nullptr - }; - // clang-format on - - InitializeChip(&theSuite); - nlTestRunner(&theSuite, nullptr); - - // TODO: The platform memory was intentionally left not deinitialized so that minimal mdns can destruct - chip::DeviceLayer::PlatformMgr().ScheduleWork(TearDownTask, 0); - sleep(kTestTaskWaitSeconds); - ShutdownChipTest(); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestCommissioningWindowManager) diff --git a/src/app/tests/TestCommissioningWindowManager.cpp b/src/app/tests/TestCommissioningWindowManager.cpp new file mode 100644 index 00000000000000..5df7a4b6ce861d --- /dev/null +++ b/src/app/tests/TestCommissioningWindowManager.cpp @@ -0,0 +1,393 @@ +/* + * + * Copyright (c) 2021-2022 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +using namespace chip::Crypto; + +using chip::CommissioningWindowAdvertisement; +using chip::CommissioningWindowManager; +using chip::Server; + +// Mock function for linking +void InitDataModelHandler() {} + +namespace { +bool sAdminFabricIndexDirty = false; +bool sAdminVendorIdDirty = false; +bool sWindowStatusDirty = false; + +void ResetDirtyFlags() +{ + sAdminFabricIndexDirty = false; + sAdminVendorIdDirty = false; + sWindowStatusDirty = false; +} + +} // namespace + +void MatterReportingAttributeChangeCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, chip::AttributeId attributeId) +{ + using namespace chip::app::Clusters; + using namespace chip::app::Clusters::AdministratorCommissioning::Attributes; + if (endpoint != chip::kRootEndpointId || clusterId != AdministratorCommissioning::Id) + { + return; + } + + switch (attributeId) + { + case WindowStatus::Id: + sWindowStatusDirty = true; + break; + case AdminVendorId::Id: + sAdminVendorIdDirty = true; + break; + case AdminFabricIndex::Id: + sAdminFabricIndexDirty = true; + break; + default: + break; + } +} + +namespace { + +void TearDownTask(intptr_t context) +{ + chip::Server::GetInstance().Shutdown(); +} + +static void StopEventLoop(intptr_t context) +{ + chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); +} + +class TestCommissioningWindowManager : 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 chip::DeviceLayer::TestOnlyCommissionableDataProvider commissionableDataProvider; + chip::DeviceLayer::SetCommissionableDataProvider(&commissionableDataProvider); + + static chip::CommonCaseDeviceServerInitParams initParams; + // Report scheduler and timer delegate instance + static chip::app::DefaultTimerDelegate sTimerDelegate; + static chip::app::reporting::ReportSchedulerImpl sReportScheduler(&sTimerDelegate); + initParams.reportScheduler = &sReportScheduler; + static chip::SimpleTestEventTriggerDelegate sSimpleTestEventTriggerDelegate; + initParams.testEventTriggerDelegate = &sSimpleTestEventTriggerDelegate; + (void) initParams.InitializeStaticResourcesBeforeServerInit(); + // Set a randomized server port(slightly shifted from CHIP_PORT) for testing + initParams.operationalServicePort = + static_cast(initParams.operationalServicePort + chip::Crypto::GetRandU16() % 20); + + ASSERT_EQ(chip::Server::GetInstance().Init(initParams), CHIP_NO_ERROR); + + Server::GetInstance().GetCommissioningWindowManager().CloseCommissioningWindow(); + } + static void TearDownTestSuite() + { + + // TODO: The platform memory was intentionally left not deinitialized so that minimal mdns can destruct + chip::DeviceLayer::PlatformMgr().ScheduleWork(TearDownTask, 0); + chip::DeviceLayer::PlatformMgr().ScheduleWork(StopEventLoop); + chip::DeviceLayer::PlatformMgr().RunEventLoop(); + + chip::DeviceLayer::PlatformMgr().Shutdown(); + + auto & mdnsAdvertiser = chip::Dnssd::ServiceAdvertiser::Instance(); + mdnsAdvertiser.RemoveServices(); + mdnsAdvertiser.Shutdown(); + + // Server shudown will be called in TearDownTask + + // TODO: At this point UDP endpoits still seem leaked and the sanitizer + // builds will attempt a memory free. As a result, we keep Memory initialized + // so that the global UDPManager can still be destructed without a coredump. + // + // This is likely either a missing shutdown or an actual UDP endpoint leak + // which I have not been able to track down yet. + // + // chip::Platform::MemoryShutdown(); + } +}; + +void CheckCommissioningWindowManagerBasicWindowOpenCloseTask(intptr_t context) +{ + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); + + CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); + + EXPECT_EQ(commissionMgr.OpenBasicCommissioningWindow(commissionMgr.MaxCommissioningTimeout(), + CommissioningWindowAdvertisement::kDnssdOnly), + CHIP_NO_ERROR); + EXPECT_TRUE(commissionMgr.IsCommissioningWindowOpen()); + EXPECT_EQ(commissionMgr.CommissioningWindowStatusForCluster(), + chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); + EXPECT_TRUE(commissionMgr.GetOpenerFabricIndex().IsNull()); + EXPECT_TRUE(commissionMgr.GetOpenerVendorId().IsNull()); + EXPECT_FALSE(chip::DeviceLayer::ConnectivityMgr().IsBLEAdvertisingEnabled()); + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); + + commissionMgr.CloseCommissioningWindow(); + EXPECT_FALSE(commissionMgr.IsCommissioningWindowOpen()); + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); +} + +TEST_F(TestCommissioningWindowManager, TestCheckCommissioningWindowManagerBasicWindowOpenClose) +{ + + chip::DeviceLayer::PlatformMgr().ScheduleWork(CheckCommissioningWindowManagerBasicWindowOpenCloseTask); + chip::DeviceLayer::PlatformMgr().ScheduleWork(StopEventLoop); + chip::DeviceLayer::PlatformMgr().RunEventLoop(); +} + +void CheckCommissioningWindowManagerBasicWindowOpenCloseFromClusterTask(intptr_t context) +{ + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); + + CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); + constexpr auto fabricIndex = static_cast(1); + constexpr auto vendorId = static_cast(0xFFF3); + EXPECT_EQ(commissionMgr.OpenBasicCommissioningWindowForAdministratorCommissioningCluster( + commissionMgr.MaxCommissioningTimeout(), fabricIndex, vendorId), + CHIP_NO_ERROR); + EXPECT_TRUE(commissionMgr.IsCommissioningWindowOpen()); + EXPECT_EQ(commissionMgr.CommissioningWindowStatusForCluster(), + chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kBasicWindowOpen); + EXPECT_FALSE(commissionMgr.GetOpenerFabricIndex().IsNull()); + EXPECT_EQ(commissionMgr.GetOpenerFabricIndex().Value(), fabricIndex); + EXPECT_FALSE(commissionMgr.GetOpenerVendorId().IsNull()); + EXPECT_EQ(commissionMgr.GetOpenerVendorId().Value(), vendorId); + EXPECT_FALSE(chip::DeviceLayer::ConnectivityMgr().IsBLEAdvertisingEnabled()); + EXPECT_TRUE(sWindowStatusDirty); + EXPECT_TRUE(sAdminFabricIndexDirty); + EXPECT_TRUE(sAdminVendorIdDirty); + + ResetDirtyFlags(); + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); + + commissionMgr.CloseCommissioningWindow(); + EXPECT_FALSE(commissionMgr.IsCommissioningWindowOpen()); + EXPECT_TRUE(commissionMgr.GetOpenerFabricIndex().IsNull()); + EXPECT_TRUE(commissionMgr.GetOpenerVendorId().IsNull()); + EXPECT_TRUE(sWindowStatusDirty); + EXPECT_TRUE(sAdminFabricIndexDirty); + EXPECT_TRUE(sAdminVendorIdDirty); + + ResetDirtyFlags(); +} + +TEST_F(TestCommissioningWindowManager, TestCheckCommissioningWindowManagerBasicWindowOpenCloseFromCluster) +{ + chip::DeviceLayer::PlatformMgr().ScheduleWork(CheckCommissioningWindowManagerBasicWindowOpenCloseFromClusterTask); + chip::DeviceLayer::PlatformMgr().ScheduleWork(StopEventLoop); + chip::DeviceLayer::PlatformMgr().RunEventLoop(); +} + +void CheckCommissioningWindowManagerWindowClosedTask(chip::System::Layer *, void *) +{ + CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); + EXPECT_FALSE(commissionMgr.IsCommissioningWindowOpen()); + EXPECT_EQ(commissionMgr.CommissioningWindowStatusForCluster(), + chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); +} + +void CheckCommissioningWindowManagerWindowTimeoutTask(intptr_t context) +{ + + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); + + CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); + constexpr auto kTimeoutSeconds = chip::System::Clock::Seconds32(1); + constexpr uint16_t kTimeoutMs = 1000; + constexpr unsigned kSleepPadding = 100; + commissionMgr.OverrideMinCommissioningTimeout(kTimeoutSeconds); + EXPECT_EQ(commissionMgr.OpenBasicCommissioningWindow(kTimeoutSeconds, CommissioningWindowAdvertisement::kDnssdOnly), + CHIP_NO_ERROR); + EXPECT_TRUE(commissionMgr.IsCommissioningWindowOpen()); + EXPECT_EQ(commissionMgr.CommissioningWindowStatusForCluster(), + chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); + EXPECT_FALSE(chip::DeviceLayer::ConnectivityMgr().IsBLEAdvertisingEnabled()); + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); + + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Milliseconds32(kTimeoutMs + kSleepPadding), + CheckCommissioningWindowManagerWindowClosedTask, nullptr); +} + +TEST_F(TestCommissioningWindowManager, TestCheckCommissioningWindowManagerWindowTimeout) +{ + chip::DeviceLayer::PlatformMgr().ScheduleWork(CheckCommissioningWindowManagerWindowTimeoutTask); + chip::DeviceLayer::PlatformMgr().ScheduleWork(StopEventLoop); + chip::DeviceLayer::PlatformMgr().RunEventLoop(); +} + +void SimulateFailedSessionEstablishmentTask(chip::System::Layer *, void *) +{ + CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); + EXPECT_TRUE(commissionMgr.IsCommissioningWindowOpen()); + EXPECT_EQ(commissionMgr.CommissioningWindowStatusForCluster(), + chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); + + commissionMgr.OnSessionEstablishmentStarted(); + commissionMgr.OnSessionEstablishmentError(CHIP_ERROR_INTERNAL); + EXPECT_TRUE(commissionMgr.IsCommissioningWindowOpen()); + EXPECT_EQ(commissionMgr.CommissioningWindowStatusForCluster(), + chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); +} + +void CheckCommissioningWindowManagerWindowTimeoutWithSessionEstablishmentErrorsTask(intptr_t context) +{ + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); + + CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); + constexpr auto kTimeoutSeconds = chip::System::Clock::Seconds16(1); + constexpr uint16_t kTimeoutMs = 1000; + constexpr unsigned kSleepPadding = 100; + + EXPECT_EQ(commissionMgr.OpenBasicCommissioningWindow(kTimeoutSeconds, CommissioningWindowAdvertisement::kDnssdOnly), + CHIP_NO_ERROR); + + EXPECT_TRUE(commissionMgr.IsCommissioningWindowOpen()); + EXPECT_EQ(commissionMgr.CommissioningWindowStatusForCluster(), + chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); + + EXPECT_FALSE(chip::DeviceLayer::ConnectivityMgr().IsBLEAdvertisingEnabled()); + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); + + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Milliseconds32(kTimeoutMs + kSleepPadding), + CheckCommissioningWindowManagerWindowClosedTask, nullptr); + // Simulate a session establishment error during that window, such that the + // delay for the error plus the window size exceeds our "timeout + padding" above. + chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Milliseconds32(kTimeoutMs / 4 * 3), + SimulateFailedSessionEstablishmentTask, nullptr); +} + +TEST_F(TestCommissioningWindowManager, CheckCommissioningWindowManagerWindowTimeoutWithSessionEstablishmentErrors) +{ + chip::DeviceLayer::PlatformMgr().ScheduleWork(CheckCommissioningWindowManagerWindowTimeoutWithSessionEstablishmentErrorsTask); + chip::DeviceLayer::PlatformMgr().ScheduleWork(StopEventLoop); + chip::DeviceLayer::PlatformMgr().RunEventLoop(); +} + +void CheckCommissioningWindowManagerEnhancedWindowTask(intptr_t context) +{ + CommissioningWindowManager & commissionMgr = Server::GetInstance().GetCommissioningWindowManager(); + uint16_t originDiscriminator; + EXPECT_EQ(chip::DeviceLayer::GetCommissionableDataProvider()->GetSetupDiscriminator(originDiscriminator), CHIP_NO_ERROR); + uint16_t newDiscriminator = static_cast(originDiscriminator + 1); + Spake2pVerifier verifier; + constexpr uint32_t kIterations = kSpake2p_Min_PBKDF_Iterations; + uint8_t salt[kSpake2p_Min_PBKDF_Salt_Length]; + chip::ByteSpan saltData(salt); + + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); + + constexpr auto fabricIndex = static_cast(1); + constexpr auto vendorId = static_cast(0xFFF3); + EXPECT_EQ(commissionMgr.OpenEnhancedCommissioningWindow(commissionMgr.MaxCommissioningTimeout(), newDiscriminator, verifier, + kIterations, saltData, fabricIndex, vendorId), + CHIP_NO_ERROR); + EXPECT_TRUE(commissionMgr.IsCommissioningWindowOpen()); + EXPECT_EQ(commissionMgr.CommissioningWindowStatusForCluster(), + chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kEnhancedWindowOpen); + EXPECT_FALSE(chip::DeviceLayer::ConnectivityMgr().IsBLEAdvertisingEnabled()); + EXPECT_FALSE(commissionMgr.GetOpenerFabricIndex().IsNull()); + EXPECT_EQ(commissionMgr.GetOpenerFabricIndex().Value(), fabricIndex); + EXPECT_FALSE(commissionMgr.GetOpenerVendorId().IsNull()); + EXPECT_EQ(commissionMgr.GetOpenerVendorId().Value(), vendorId); + EXPECT_TRUE(sWindowStatusDirty); + EXPECT_TRUE(sAdminFabricIndexDirty); + EXPECT_TRUE(sAdminVendorIdDirty); + + ResetDirtyFlags(); + EXPECT_FALSE(sWindowStatusDirty); + EXPECT_FALSE(sAdminFabricIndexDirty); + EXPECT_FALSE(sAdminVendorIdDirty); + + commissionMgr.CloseCommissioningWindow(); + EXPECT_FALSE(commissionMgr.IsCommissioningWindowOpen()); + EXPECT_EQ(commissionMgr.CommissioningWindowStatusForCluster(), + chip::app::Clusters::AdministratorCommissioning::CommissioningWindowStatusEnum::kWindowNotOpen); + EXPECT_TRUE(commissionMgr.GetOpenerFabricIndex().IsNull()); + EXPECT_TRUE(commissionMgr.GetOpenerVendorId().IsNull()); + EXPECT_TRUE(sWindowStatusDirty); + EXPECT_TRUE(sAdminFabricIndexDirty); + EXPECT_TRUE(sAdminVendorIdDirty); + + ResetDirtyFlags(); +} + +TEST_F(TestCommissioningWindowManager, TestCheckCommissioningWindowManagerEnhancedWindow) +{ + chip::DeviceLayer::PlatformMgr().ScheduleWork(CheckCommissioningWindowManagerEnhancedWindowTask); + chip::DeviceLayer::PlatformMgr().ScheduleWork(StopEventLoop); + chip::DeviceLayer::PlatformMgr().RunEventLoop(); +} + +} // namespace diff --git a/src/app/tests/TestDefaultICDClientStorage.cpp b/src/app/tests/TestDefaultICDClientStorage.cpp index 8cf4c8d86fa2a1..ac950fdbc75715 100644 --- a/src/app/tests/TestDefaultICDClientStorage.cpp +++ b/src/app/tests/TestDefaultICDClientStorage.cpp @@ -64,7 +64,6 @@ class TestDefaultICDClientStorage : public ::testing::Test TEST_F(TestDefaultICDClientStorage, TestClientInfoCount) { - CHIP_ERROR err = CHIP_NO_ERROR; FabricIndex fabricId = 1; NodeId nodeId1 = 6666; NodeId nodeId2 = 6667; @@ -73,10 +72,8 @@ TEST_F(TestDefaultICDClientStorage, TestClientInfoCount) { DefaultICDClientStorage manager; - err = manager.Init(&clientInfoStorage, &keystore); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = manager.UpdateFabricList(fabricId); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.Init(&clientInfoStorage, &keystore), CHIP_NO_ERROR); + EXPECT_EQ(manager.UpdateFabricList(fabricId), CHIP_NO_ERROR); // Write some ClientInfos and see the counts are correct ICDClientInfo clientInfo1; clientInfo1.peer_node = ScopedNodeId(nodeId1, fabricId); @@ -84,20 +81,14 @@ TEST_F(TestDefaultICDClientStorage, TestClientInfoCount) clientInfo2.peer_node = ScopedNodeId(nodeId2, fabricId); ICDClientInfo clientInfo3; clientInfo3.peer_node = ScopedNodeId(nodeId1, fabricId); - err = manager.SetKey(clientInfo1, ByteSpan(kKeyBuffer1)); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = manager.StoreEntry(clientInfo1); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.SetKey(clientInfo1, ByteSpan(kKeyBuffer1)), CHIP_NO_ERROR); + EXPECT_EQ(manager.StoreEntry(clientInfo1), CHIP_NO_ERROR); - err = manager.SetKey(clientInfo2, ByteSpan(kKeyBuffer2)); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = manager.StoreEntry(clientInfo2); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.SetKey(clientInfo2, ByteSpan(kKeyBuffer2)), CHIP_NO_ERROR); + EXPECT_EQ(manager.StoreEntry(clientInfo2), CHIP_NO_ERROR); - err = manager.SetKey(clientInfo3, ByteSpan(kKeyBuffer3)); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = manager.StoreEntry(clientInfo3); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.SetKey(clientInfo3, ByteSpan(kKeyBuffer3)), CHIP_NO_ERROR); + EXPECT_EQ(manager.StoreEntry(clientInfo3), CHIP_NO_ERROR); ICDClientInfo clientInfo; // Make sure iterator counts correctly @@ -113,8 +104,7 @@ TEST_F(TestDefaultICDClientStorage, TestClientInfoCount) iterator->Release(); // Delete all and verify iterator counts 0 - err = manager.DeleteAllEntries(fabricId); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.DeleteAllEntries(fabricId), CHIP_NO_ERROR); iterator = manager.IterateICDClientInfo(); EXPECT_EQ(iterator->Count(), 0u); @@ -130,16 +120,14 @@ TEST_F(TestDefaultICDClientStorage, TestClientInfoCount) { DefaultICDClientStorage manager; - err = manager.Init(&clientInfoStorage, &keystore); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = manager.UpdateFabricList(fabricId); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.Init(&clientInfoStorage, &keystore), CHIP_NO_ERROR); + EXPECT_EQ(manager.UpdateFabricList(fabricId), CHIP_NO_ERROR); } } TEST_F(TestDefaultICDClientStorage, TestClientInfoCountMultipleFabric) { - CHIP_ERROR err = CHIP_NO_ERROR; + FabricIndex fabricId1 = 1; FabricIndex fabricId2 = 2; NodeId nodeId1 = 6666; @@ -148,12 +136,9 @@ TEST_F(TestDefaultICDClientStorage, TestClientInfoCountMultipleFabric) DefaultICDClientStorage manager; TestPersistentStorageDelegate clientInfoStorage; TestSessionKeystoreImpl keystore; - err = manager.Init(&clientInfoStorage, &keystore); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = manager.UpdateFabricList(fabricId1); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = manager.UpdateFabricList(fabricId2); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.Init(&clientInfoStorage, &keystore), CHIP_NO_ERROR); + EXPECT_EQ(manager.UpdateFabricList(fabricId1), CHIP_NO_ERROR); + EXPECT_EQ(manager.UpdateFabricList(fabricId2), CHIP_NO_ERROR); // Write some ClientInfos and see the counts are correct ICDClientInfo clientInfo1; @@ -163,39 +148,30 @@ TEST_F(TestDefaultICDClientStorage, TestClientInfoCountMultipleFabric) ICDClientInfo clientInfo3; clientInfo3.peer_node = ScopedNodeId(nodeId3, fabricId2); - err = manager.SetKey(clientInfo1, ByteSpan(kKeyBuffer1)); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = manager.StoreEntry(clientInfo1); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.SetKey(clientInfo1, ByteSpan(kKeyBuffer1)), CHIP_NO_ERROR); + EXPECT_EQ(manager.StoreEntry(clientInfo1), CHIP_NO_ERROR); - err = manager.SetKey(clientInfo2, ByteSpan(kKeyBuffer2)); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = manager.StoreEntry(clientInfo2); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.SetKey(clientInfo2, ByteSpan(kKeyBuffer2)), CHIP_NO_ERROR); + EXPECT_EQ(manager.StoreEntry(clientInfo2), CHIP_NO_ERROR); - err = manager.SetKey(clientInfo3, ByteSpan(kKeyBuffer3)); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = manager.StoreEntry(clientInfo3); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.SetKey(clientInfo3, ByteSpan(kKeyBuffer3)), CHIP_NO_ERROR); + EXPECT_EQ(manager.StoreEntry(clientInfo3), CHIP_NO_ERROR); // Make sure iterator counts correctly auto * iterator = manager.IterateICDClientInfo(); EXPECT_EQ(iterator->Count(), 3u); iterator->Release(); // Delete all and verify iterator counts 0 - err = manager.DeleteEntry(ScopedNodeId(nodeId1, fabricId1)); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.DeleteEntry(ScopedNodeId(nodeId1, fabricId1)), CHIP_NO_ERROR); iterator = manager.IterateICDClientInfo(); ASSERT_NE(iterator, nullptr); DefaultICDClientStorage::ICDClientInfoIteratorWrapper clientInfoIteratorWrapper(iterator); EXPECT_EQ(iterator->Count(), 2u); - err = manager.DeleteEntry(ScopedNodeId(nodeId2, fabricId1)); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.DeleteEntry(ScopedNodeId(nodeId2, fabricId1)), CHIP_NO_ERROR); EXPECT_EQ(iterator->Count(), 1u); - err = manager.DeleteEntry(ScopedNodeId(nodeId3, fabricId2)); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.DeleteEntry(ScopedNodeId(nodeId3, fabricId2)), CHIP_NO_ERROR); EXPECT_EQ(iterator->Count(), 0u); // Verify ClientInfos manually count correctly @@ -211,49 +187,41 @@ TEST_F(TestDefaultICDClientStorage, TestClientInfoCountMultipleFabric) TEST_F(TestDefaultICDClientStorage, TestProcessCheckInPayload) { - CHIP_ERROR err = CHIP_NO_ERROR; FabricIndex fabricId = 1; NodeId nodeId = 6666; TestPersistentStorageDelegate clientInfoStorage; TestSessionKeystoreImpl keystore; DefaultICDClientStorage manager; - err = manager.Init(&clientInfoStorage, &keystore); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = manager.UpdateFabricList(fabricId); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.Init(&clientInfoStorage, &keystore), CHIP_NO_ERROR); + EXPECT_EQ(manager.UpdateFabricList(fabricId), CHIP_NO_ERROR); // Populate clientInfo ICDClientInfo clientInfo; clientInfo.peer_node = ScopedNodeId(nodeId, fabricId); - err = manager.SetKey(clientInfo, ByteSpan(kKeyBuffer1)); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = manager.StoreEntry(clientInfo); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.SetKey(clientInfo, ByteSpan(kKeyBuffer1)), CHIP_NO_ERROR); + EXPECT_EQ(manager.StoreEntry(clientInfo), CHIP_NO_ERROR); uint32_t counter = 1; System::PacketBufferHandle buffer = MessagePacketBuffer::New(chip::Protocols::SecureChannel::CheckinMessage::kMinPayloadSize); MutableByteSpan output{ buffer->Start(), buffer->MaxDataLength() }; - err = chip::Protocols::SecureChannel::CheckinMessage::GenerateCheckinMessagePayload( - clientInfo.aes_key_handle, clientInfo.hmac_key_handle, counter, ByteSpan(), output); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(chip::Protocols::SecureChannel::CheckinMessage::GenerateCheckinMessagePayload( + clientInfo.aes_key_handle, clientInfo.hmac_key_handle, counter, ByteSpan(), output), + CHIP_NO_ERROR); buffer->SetDataLength(static_cast(output.size())); ICDClientInfo decodeClientInfo; uint32_t checkInCounter = 0; ByteSpan payload{ buffer->Start(), buffer->DataLength() }; - err = manager.ProcessCheckInPayload(payload, decodeClientInfo, checkInCounter); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.ProcessCheckInPayload(payload, decodeClientInfo, checkInCounter), CHIP_NO_ERROR); // 2. Use a key not available in the storage for encoding - err = manager.SetKey(clientInfo, ByteSpan(kKeyBuffer2)); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = chip::Protocols::SecureChannel::CheckinMessage::GenerateCheckinMessagePayload( - clientInfo.aes_key_handle, clientInfo.hmac_key_handle, counter, ByteSpan(), output); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(manager.SetKey(clientInfo, ByteSpan(kKeyBuffer2)), CHIP_NO_ERROR); + EXPECT_EQ(chip::Protocols::SecureChannel::CheckinMessage::GenerateCheckinMessagePayload( + clientInfo.aes_key_handle, clientInfo.hmac_key_handle, counter, ByteSpan(), output), + CHIP_NO_ERROR); buffer->SetDataLength(static_cast(output.size())); ByteSpan payload1{ buffer->Start(), buffer->DataLength() }; - err = manager.ProcessCheckInPayload(payload1, decodeClientInfo, checkInCounter); - EXPECT_EQ(err, CHIP_ERROR_NOT_FOUND); + EXPECT_EQ(manager.ProcessCheckInPayload(payload1, decodeClientInfo, checkInCounter), CHIP_ERROR_NOT_FOUND); } diff --git a/src/app/tests/TestEventLogging.cpp b/src/app/tests/TestEventLogging.cpp index 854247240ac701..931b706024c740 100644 --- a/src/app/tests/TestEventLogging.cpp +++ b/src/app/tests/TestEventLogging.cpp @@ -16,12 +16,6 @@ * limitations under the License. */ -/** - * @file - * This file implements a test for CHIP Interaction Model Event logging - * - */ - #include #include #include @@ -37,15 +31,14 @@ #include #include #include -#include -#include #include #include #include #include #include -#include +#include +#include namespace { @@ -60,9 +53,19 @@ static uint8_t gInfoEventBuffer[120]; static uint8_t gCritEventBuffer[120]; static chip::app::CircularEventBuffer gCircularEventBuffer[3]; -class TestContext : public chip::Test::AppContext +class TestEventLogging : public ::testing::Test { public: + static void SetUpTestSuite() + { + mpTestContext = new chip::Test::AppContext; + mpTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + delete mpTestContext; + } // Performs setup for each individual test in the test suite void SetUp() override { @@ -72,13 +75,9 @@ class TestContext : public chip::Test::AppContext { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - chip::Test::AppContext::SetUp(); - - CHIP_ERROR err = CHIP_NO_ERROR; - // TODO: use ASSERT_EQ, once transition to pw_unit_test is complete - VerifyOrDieWithMsg((err = mEventCounter.Init(0)) == CHIP_NO_ERROR, AppServer, - "Init EventCounter failed: %" CHIP_ERROR_FORMAT, err.Format()); - chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), + mpTestContext->SetUp(); + ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); + chip::app::EventManagement::CreateEventManagement(&mpTestContext->GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); } @@ -86,13 +85,17 @@ class TestContext : public chip::Test::AppContext void TearDown() override { chip::app::EventManagement::DestroyEventManagement(); - chip::Test::AppContext::TearDown(); + mpTestContext->TearDown(); } + static chip::Test::AppContext * mpTestContext; + private: chip::MonotonicallyIncreasingCounter mEventCounter; }; +chip::Test::AppContext * TestEventLogging::mpTestContext = nullptr; + void ENFORCE_FORMAT(1, 2) SimpleDumpWriter(const char * aFormat, ...) { va_list args; @@ -112,26 +115,22 @@ void PrintEventLog() chip::TLV::Debug::Dump(reader, SimpleDumpWriter); } -static void CheckLogState(nlTestSuite * apSuite, chip::app::EventManagement & aLogMgmt, size_t expectedNumEvents, - chip::app::PriorityLevel aPriority) +static void CheckLogState(chip::app::EventManagement & aLogMgmt, size_t expectedNumEvents, chip::app::PriorityLevel aPriority) { - CHIP_ERROR err; chip::TLV::TLVReader reader; size_t elementCount; chip::app::CircularEventBufferWrapper bufWrapper; - err = aLogMgmt.GetEventReader(reader, aPriority, &bufWrapper); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(aLogMgmt.GetEventReader(reader, aPriority, &bufWrapper), CHIP_NO_ERROR); - err = chip::TLV::Utilities::Count(reader, elementCount, false); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(chip::TLV::Utilities::Count(reader, elementCount, false), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, elementCount == expectedNumEvents); + EXPECT_EQ(elementCount, expectedNumEvents); printf("elementCount vs expectedNumEvents : %u vs %u \n", static_cast(elementCount), static_cast(expectedNumEvents)); } -static void CheckLogReadOut(nlTestSuite * apSuite, chip::app::EventManagement & alogMgmt, chip::EventNumber startingEventNumber, - size_t expectedNumEvents, chip::SingleLinkedListNode * clusterInfo) +static void CheckLogReadOut(chip::app::EventManagement & alogMgmt, chip::EventNumber startingEventNumber, size_t expectedNumEvents, + chip::SingleLinkedListNode * clusterInfo) { CHIP_ERROR err; chip::TLV::TLVReader reader; @@ -144,7 +143,7 @@ static void CheckLogReadOut(nlTestSuite * apSuite, chip::app::EventManagement & size_t totalNumElements; writer.Init(backingStore.Get(), 1024); err = alogMgmt.FetchEventsSince(writer, clusterInfo, startingEventNumber, eventCount, chip::Access::SubjectDescriptor{}); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR || err == CHIP_END_OF_TLV); + EXPECT_TRUE(err == CHIP_NO_ERROR || err == CHIP_END_OF_TLV); auto eventTLVSize = writer.GetLengthWritten() / eventCount; // XXX: Make sure that the sizes of our event storages are big enough to hold at least 3 events @@ -153,16 +152,17 @@ static void CheckLogReadOut(nlTestSuite * apSuite, chip::app::EventManagement & // The size of TLV-encoded event can vary depending on the UTC vs system time controlled by // the CHIP_DEVICE_CONFIG_EVENT_LOGGING_UTC_TIMESTAMPS, because the relative system time // will be most likely encoded in 1 byte, while the UTC time will be encoded in 8 bytes. - NL_TEST_ASSERT(apSuite, sizeof(gDebugEventBuffer) >= eventTLVSize * 3 && sizeof(gDebugEventBuffer) < eventTLVSize * 4); + EXPECT_GE(sizeof(gDebugEventBuffer), eventTLVSize * 3); + EXPECT_LT(sizeof(gDebugEventBuffer), eventTLVSize * 4); reader.Init(backingStore.Get(), writer.GetLengthWritten()); - err = chip::TLV::Utilities::Count(reader, totalNumElements, false); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(chip::TLV::Utilities::Count(reader, totalNumElements, false), CHIP_NO_ERROR); printf("totalNumElements vs expectedNumEvents vs eventCount : %u vs %u vs %u \n", static_cast(totalNumElements), static_cast(expectedNumEvents), static_cast(eventCount)); - NL_TEST_ASSERT(apSuite, totalNumElements == expectedNumEvents && totalNumElements == eventCount); + EXPECT_EQ(totalNumElements, expectedNumEvents); + EXPECT_EQ(totalNumElements, eventCount); reader.Init(backingStore.Get(), writer.GetLengthWritten()); chip::TLV::Debug::Dump(reader, SimpleDumpWriter); } @@ -185,9 +185,9 @@ class TestEventGenerator : public chip::app::EventLoggingDelegate int32_t mStatus; }; -static void CheckLogEventWithEvictToNextBuffer(nlTestSuite * apSuite, void * apContext) +TEST_F(TestEventLogging, TestCheckLogEventWithEvictToNextBuffer) { - CHIP_ERROR err = CHIP_NO_ERROR; + chip::EventNumber eid1, eid2, eid3, eid4, eid5, eid6; chip::app::EventOptions options1; chip::app::EventOptions options2; @@ -199,40 +199,34 @@ static void CheckLogEventWithEvictToNextBuffer(nlTestSuite * apSuite, void * apC options2.mPriority = chip::app::PriorityLevel::Info; chip::app::EventManagement & logMgmt = chip::app::EventManagement::GetInstance(); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options1, eid1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 1, chip::app::PriorityLevel::Debug); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options1, eid1), CHIP_NO_ERROR); + CheckLogState(logMgmt, 1, chip::app::PriorityLevel::Debug); testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options1, eid2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 2, chip::app::PriorityLevel::Debug); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options1, eid2), CHIP_NO_ERROR); + CheckLogState(logMgmt, 2, chip::app::PriorityLevel::Debug); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options1, eid3); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 3, chip::app::PriorityLevel::Debug); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options1, eid3), CHIP_NO_ERROR); + CheckLogState(logMgmt, 3, chip::app::PriorityLevel::Debug); // Start to copy info event to next buffer since current debug buffer is full and info event is higher priority testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options2, eid4); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 4, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options2, eid4), CHIP_NO_ERROR); + CheckLogState(logMgmt, 4, chip::app::PriorityLevel::Info); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options2, eid5); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 5, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options2, eid5), CHIP_NO_ERROR); + CheckLogState(logMgmt, 5, chip::app::PriorityLevel::Info); testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options2, eid6); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 6, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options2, eid6), CHIP_NO_ERROR); + CheckLogState(logMgmt, 6, chip::app::PriorityLevel::Info); PrintEventLog(); - NL_TEST_ASSERT(apSuite, (eid1 + 1) == eid2); - NL_TEST_ASSERT(apSuite, (eid2 + 1) == eid3); - NL_TEST_ASSERT(apSuite, (eid3 + 1) == eid4); - NL_TEST_ASSERT(apSuite, (eid4 + 1) == eid5); - NL_TEST_ASSERT(apSuite, (eid5 + 1) == eid6); + EXPECT_EQ((eid1 + 1), eid2); + EXPECT_EQ((eid2 + 1), eid3); + EXPECT_EQ((eid3 + 1), eid4); + EXPECT_EQ((eid4 + 1), eid5); + EXPECT_EQ((eid5 + 1), eid6); chip::SingleLinkedListNode paths[2]; @@ -244,32 +238,32 @@ static void CheckLogEventWithEvictToNextBuffer(nlTestSuite * apSuite, void * apC paths[1].mValue.mEventId = kLivenessChangeEvent; // interested paths are path list, expect to retrieve all events for each particular interested path - CheckLogReadOut(apSuite, logMgmt, 0, 3, &paths[0]); - CheckLogReadOut(apSuite, logMgmt, 1, 2, &paths[0]); - CheckLogReadOut(apSuite, logMgmt, 2, 1, &paths[0]); - CheckLogReadOut(apSuite, logMgmt, 3, 3, &paths[1]); - CheckLogReadOut(apSuite, logMgmt, 4, 2, &paths[1]); - CheckLogReadOut(apSuite, logMgmt, 5, 1, &paths[1]); + CheckLogReadOut(logMgmt, 0, 3, &paths[0]); + CheckLogReadOut(logMgmt, 1, 2, &paths[0]); + CheckLogReadOut(logMgmt, 2, 1, &paths[0]); + CheckLogReadOut(logMgmt, 3, 3, &paths[1]); + CheckLogReadOut(logMgmt, 4, 2, &paths[1]); + CheckLogReadOut(logMgmt, 5, 1, &paths[1]); paths[0].mpNext = &paths[1]; // interested paths are path list, expect to retrieve all events for those interested paths - CheckLogReadOut(apSuite, logMgmt, 0, 6, paths); + CheckLogReadOut(logMgmt, 0, 6, paths); chip::SingleLinkedListNode pathsWithWildcard[2]; paths[0].mValue.mEndpointId = kTestEndpointId1; paths[0].mValue.mClusterId = kLivenessClusterId; // second path is wildcard path at default, expect to retrieve all events - CheckLogReadOut(apSuite, logMgmt, 0, 6, &pathsWithWildcard[1]); + CheckLogReadOut(logMgmt, 0, 6, &pathsWithWildcard[1]); paths[0].mpNext = &paths[1]; // first path is not wildcard, second path is wildcard path at default, expect to retrieve all events - CheckLogReadOut(apSuite, logMgmt, 0, 6, pathsWithWildcard); + CheckLogReadOut(logMgmt, 0, 6, pathsWithWildcard); } -static void CheckLogEventWithDiscardLowEvent(nlTestSuite * apSuite, void * apContext) +TEST_F(TestEventLogging, TestCheckLogEventWithDiscardLowEvent) { - CHIP_ERROR err = CHIP_NO_ERROR; + chip::EventNumber eid1, eid2, eid3, eid4, eid5, eid6; chip::app::EventOptions options; options.mPath = { kTestEndpointId1, kLivenessClusterId, kLivenessChangeEvent }; @@ -278,57 +272,29 @@ static void CheckLogEventWithDiscardLowEvent(nlTestSuite * apSuite, void * apCon chip::app::EventManagement & logMgmt = chip::app::EventManagement::GetInstance(); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options, eid1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 1, chip::app::PriorityLevel::Debug); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options, eid1), CHIP_NO_ERROR); + CheckLogState(logMgmt, 1, chip::app::PriorityLevel::Debug); testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options, eid2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 2, chip::app::PriorityLevel::Debug); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options, eid2), CHIP_NO_ERROR); + CheckLogState(logMgmt, 2, chip::app::PriorityLevel::Debug); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options, eid3); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 3, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 3, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options, eid3), CHIP_NO_ERROR); + CheckLogState(logMgmt, 3, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 3, chip::app::PriorityLevel::Info); // Start to drop off debug event since debug event can only be saved in debug buffer testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options, eid4); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 3, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 3, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options, eid4), CHIP_NO_ERROR); + CheckLogState(logMgmt, 3, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 3, chip::app::PriorityLevel::Info); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options, eid5); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 3, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 3, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options, eid5), CHIP_NO_ERROR); + CheckLogState(logMgmt, 3, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 3, chip::app::PriorityLevel::Info); testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options, eid6); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 3, chip::app::PriorityLevel::Debug); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options, eid6), CHIP_NO_ERROR); + CheckLogState(logMgmt, 3, chip::app::PriorityLevel::Debug); } -const nlTest sTests[] = { - NL_TEST_DEF("CheckLogEventWithEvictToNextBuffer", CheckLogEventWithEvictToNextBuffer), - NL_TEST_DEF("CheckLogEventWithDiscardLowEvent", CheckLogEventWithDiscardLowEvent), - NL_TEST_SENTINEL(), -}; - -nlTestSuite sSuite = { - "EventLogging", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; - } // namespace - -int TestEventLogging() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestEventLogging) diff --git a/src/app/tests/TestEventLoggingNoUTCTime.cpp b/src/app/tests/TestEventLoggingNoUTCTime.cpp index c6dc4182b79e0e..907a85982c1155 100644 --- a/src/app/tests/TestEventLoggingNoUTCTime.cpp +++ b/src/app/tests/TestEventLoggingNoUTCTime.cpp @@ -15,12 +15,6 @@ * limitations under the License. */ -/** - * @file - * This file implements a test for CHIP Interaction Model Event logging - * - */ - #include #include #include @@ -36,15 +30,14 @@ #include #include #include -#include -#include #include #include #include #include #include -#include +#include +#include namespace { @@ -80,13 +73,14 @@ class MockClock : public chip::System::Clock::ClockBase chip::System::Clock::ClockBase & mRealClock; }; -class TestContext : public chip::Test::AppContext +class TestEventLoggingNoUTCTime : public ::testing::Test { public: // Performs shared setup for all tests in the test suite static void SetUpTestSuite() { - chip::Test::AppContext::SetUpTestSuite(); + mpTestContext = new chip::Test::AppContext; + mpTestContext->SetUpTestSuite(); sClock.Emplace(chip::System::SystemClock()); } @@ -94,7 +88,8 @@ class TestContext : public chip::Test::AppContext static void TearDownTestSuite() { sClock.ClearValue(); - chip::Test::AppContext::TearDownTestSuite(); + mpTestContext->TearDownTestSuite(); + delete mpTestContext; } // Performs setup for each individual test in the test suite @@ -106,13 +101,9 @@ class TestContext : public chip::Test::AppContext { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - chip::Test::AppContext::SetUp(); - - CHIP_ERROR err = CHIP_NO_ERROR; - // TODO: use ASSERT_EQ, once transition to pw_unit_test is complete - VerifyOrDieWithMsg((err = mEventCounter.Init(0)) == CHIP_NO_ERROR, AppServer, - "Init EventCounter failed: %" CHIP_ERROR_FORMAT, err.Format()); - chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), + mpTestContext->SetUp(); + ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); + chip::app::EventManagement::CreateEventManagement(&mpTestContext->GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); } @@ -120,15 +111,18 @@ class TestContext : public chip::Test::AppContext void TearDown() override { chip::app::EventManagement::DestroyEventManagement(); - chip::Test::AppContext::TearDown(); + mpTestContext->TearDown(); } + static chip::Test::AppContext * mpTestContext; + private: chip::MonotonicallyIncreasingCounter mEventCounter; static chip::Optional sClock; }; -chip::Optional TestContext::sClock; +chip::Test::AppContext * TestEventLoggingNoUTCTime::mpTestContext = nullptr; +chip::Optional TestEventLoggingNoUTCTime::sClock; void ENFORCE_FORMAT(1, 2) SimpleDumpWriter(const char * aFormat, ...) { @@ -149,34 +143,31 @@ void PrintEventLog() chip::TLV::Debug::Dump(reader, SimpleDumpWriter); } -static void CheckLogState(nlTestSuite * apSuite, chip::app::EventManagement & aLogMgmt, size_t expectedMinNumEvents, - size_t expectedMaxNumEvents, chip::app::PriorityLevel aPriority) +static void CheckLogState(chip::app::EventManagement & aLogMgmt, size_t expectedMinNumEvents, size_t expectedMaxNumEvents, + chip::app::PriorityLevel aPriority) { - CHIP_ERROR err; + chip::TLV::TLVReader reader; size_t elementCount; chip::app::CircularEventBufferWrapper bufWrapper; - err = aLogMgmt.GetEventReader(reader, aPriority, &bufWrapper); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(aLogMgmt.GetEventReader(reader, aPriority, &bufWrapper), CHIP_NO_ERROR); - err = chip::TLV::Utilities::Count(reader, elementCount, false); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(chip::TLV::Utilities::Count(reader, elementCount, false), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, elementCount >= expectedMinNumEvents); - NL_TEST_ASSERT(apSuite, elementCount <= expectedMaxNumEvents); + EXPECT_GE(elementCount, expectedMinNumEvents); + EXPECT_LE(elementCount, expectedMaxNumEvents); printf("elementCount vs [expectedMinNumEvents, expectedMaxNumEvents] : %u vs [%u, %u] \n", static_cast(elementCount), static_cast(expectedMinNumEvents), static_cast(expectedMaxNumEvents)); } -static void CheckLogState(nlTestSuite * apSuite, chip::app::EventManagement & aLogMgmt, size_t expectedNumEvents, - chip::app::PriorityLevel aPriority) +static void CheckLogState(chip::app::EventManagement & aLogMgmt, size_t expectedNumEvents, chip::app::PriorityLevel aPriority) { - CheckLogState(apSuite, aLogMgmt, expectedNumEvents, expectedNumEvents, aPriority); + CheckLogState(aLogMgmt, expectedNumEvents, expectedNumEvents, aPriority); } -static void CheckLogReadOut(nlTestSuite * apSuite, chip::app::EventManagement & alogMgmt, chip::EventNumber startingEventNumber, - size_t expectedNumEvents, chip::SingleLinkedListNode * clusterInfo) +static void CheckLogReadOut(chip::app::EventManagement & alogMgmt, chip::EventNumber startingEventNumber, size_t expectedNumEvents, + chip::SingleLinkedListNode * clusterInfo) { CHIP_ERROR err; chip::TLV::TLVReader reader; @@ -189,16 +180,16 @@ static void CheckLogReadOut(nlTestSuite * apSuite, chip::app::EventManagement & size_t totalNumElements; writer.Init(backingStore.Get(), 1024); err = alogMgmt.FetchEventsSince(writer, clusterInfo, startingEventNumber, eventCount, chip::Access::SubjectDescriptor{}); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR || err == CHIP_END_OF_TLV); + EXPECT_TRUE(err == CHIP_NO_ERROR || err == CHIP_END_OF_TLV); reader.Init(backingStore.Get(), writer.GetLengthWritten()); - err = chip::TLV::Utilities::Count(reader, totalNumElements, false); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(chip::TLV::Utilities::Count(reader, totalNumElements, false), CHIP_NO_ERROR); printf("totalNumElements vs expectedNumEvents vs eventCount : %u vs %u vs %u \n", static_cast(totalNumElements), static_cast(expectedNumEvents), static_cast(eventCount)); - NL_TEST_ASSERT(apSuite, totalNumElements == expectedNumEvents && totalNumElements == eventCount); + EXPECT_EQ(totalNumElements, expectedNumEvents); + EXPECT_EQ(totalNumElements, eventCount); reader.Init(backingStore.Get(), writer.GetLengthWritten()); chip::TLV::Debug::Dump(reader, SimpleDumpWriter); } @@ -221,9 +212,8 @@ class TestEventGenerator : public chip::app::EventLoggingDelegate int32_t mStatus; }; -static void CheckLogEventWithEvictToNextBuffer(nlTestSuite * apSuite, void * apContext) +TEST_F(TestEventLoggingNoUTCTime, TestCheckLogEventWithEvictToNextBuffer) { - CHIP_ERROR err = CHIP_NO_ERROR; chip::EventNumber eid1, eid2, eid3, eid4, eid5, eid6; chip::app::EventOptions options1; chip::app::EventOptions options2; @@ -235,48 +225,42 @@ static void CheckLogEventWithEvictToNextBuffer(nlTestSuite * apSuite, void * apC options2.mPriority = chip::app::PriorityLevel::Info; chip::app::EventManagement & logMgmt = chip::app::EventManagement::GetInstance(); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options1, eid1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 1, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 1, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options1, eid1), CHIP_NO_ERROR); + CheckLogState(logMgmt, 1, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 1, chip::app::PriorityLevel::Info); testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options1, eid2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 2, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 2, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options1, eid2), CHIP_NO_ERROR); + CheckLogState(logMgmt, 2, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 2, chip::app::PriorityLevel::Info); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options1, eid3); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 3, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 3, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options1, eid3), CHIP_NO_ERROR); + CheckLogState(logMgmt, 3, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 3, chip::app::PriorityLevel::Info); // Start to copy info event to next buffer since current debug buffer is full and info event is higher priority testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options2, eid4); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options2, eid4), CHIP_NO_ERROR); // At this point depending on timing and hence event sizes we might have // either 3 or 4 events in the Debug buffer. - CheckLogState(apSuite, logMgmt, 3, 4, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 4, chip::app::PriorityLevel::Info); + CheckLogState(logMgmt, 3, 4, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 4, chip::app::PriorityLevel::Info); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options2, eid5); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 3, 4, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 5, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options2, eid5), CHIP_NO_ERROR); + CheckLogState(logMgmt, 3, 4, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 5, chip::app::PriorityLevel::Info); testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options2, eid6); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 3, 4, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 6, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options2, eid6), CHIP_NO_ERROR); + CheckLogState(logMgmt, 3, 4, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 6, chip::app::PriorityLevel::Info); PrintEventLog(); - NL_TEST_ASSERT(apSuite, (eid1 + 1) == eid2); - NL_TEST_ASSERT(apSuite, (eid2 + 1) == eid3); - NL_TEST_ASSERT(apSuite, (eid3 + 1) == eid4); - NL_TEST_ASSERT(apSuite, (eid4 + 1) == eid5); - NL_TEST_ASSERT(apSuite, (eid5 + 1) == eid6); + EXPECT_EQ((eid1 + 1), eid2); + EXPECT_EQ((eid2 + 1), eid3); + EXPECT_EQ((eid3 + 1), eid4); + EXPECT_EQ((eid4 + 1), eid5); + EXPECT_EQ((eid5 + 1), eid6); chip::SingleLinkedListNode paths[2]; @@ -288,32 +272,31 @@ static void CheckLogEventWithEvictToNextBuffer(nlTestSuite * apSuite, void * apC paths[1].mValue.mEventId = kLivenessChangeEvent; // interested paths are path list, expect to retrieve all events for each particular interested path - CheckLogReadOut(apSuite, logMgmt, 0, 3, &paths[0]); - CheckLogReadOut(apSuite, logMgmt, 1, 2, &paths[0]); - CheckLogReadOut(apSuite, logMgmt, 2, 1, &paths[0]); - CheckLogReadOut(apSuite, logMgmt, 3, 3, &paths[1]); - CheckLogReadOut(apSuite, logMgmt, 4, 2, &paths[1]); - CheckLogReadOut(apSuite, logMgmt, 5, 1, &paths[1]); + CheckLogReadOut(logMgmt, 0, 3, &paths[0]); + CheckLogReadOut(logMgmt, 1, 2, &paths[0]); + CheckLogReadOut(logMgmt, 2, 1, &paths[0]); + CheckLogReadOut(logMgmt, 3, 3, &paths[1]); + CheckLogReadOut(logMgmt, 4, 2, &paths[1]); + CheckLogReadOut(logMgmt, 5, 1, &paths[1]); paths[0].mpNext = &paths[1]; // interested paths are path list, expect to retrieve all events for those interested paths - CheckLogReadOut(apSuite, logMgmt, 0, 6, paths); + CheckLogReadOut(logMgmt, 0, 6, paths); chip::SingleLinkedListNode pathsWithWildcard[2]; paths[0].mValue.mEndpointId = kTestEndpointId1; paths[0].mValue.mClusterId = kLivenessClusterId; // second path is wildcard path at default, expect to retrieve all events - CheckLogReadOut(apSuite, logMgmt, 0, 6, &pathsWithWildcard[1]); + CheckLogReadOut(logMgmt, 0, 6, &pathsWithWildcard[1]); paths[0].mpNext = &paths[1]; // first path is not wildcard, second path is wildcard path at default, expect to retrieve all events - CheckLogReadOut(apSuite, logMgmt, 0, 6, pathsWithWildcard); + CheckLogReadOut(logMgmt, 0, 6, pathsWithWildcard); } -static void CheckLogEventWithDiscardLowEvent(nlTestSuite * apSuite, void * apContext) +TEST_F(TestEventLoggingNoUTCTime, TestCheckLogEventWithDiscardLowEvent) { - CHIP_ERROR err = CHIP_NO_ERROR; chip::EventNumber eid1, eid2, eid3, eid4, eid5, eid6; chip::app::EventOptions options; options.mPath = { kTestEndpointId1, kLivenessClusterId, kLivenessChangeEvent }; @@ -321,68 +304,37 @@ static void CheckLogEventWithDiscardLowEvent(nlTestSuite * apSuite, void * apCon TestEventGenerator testEventGenerator; chip::app::EventManagement & logMgmt = chip::app::EventManagement::GetInstance(); - CheckLogState(apSuite, logMgmt, 0, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 0, chip::app::PriorityLevel::Info); + CheckLogState(logMgmt, 0, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 0, chip::app::PriorityLevel::Info); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options, eid1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 1, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 1, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options, eid1), CHIP_NO_ERROR); + CheckLogState(logMgmt, 1, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 1, chip::app::PriorityLevel::Info); testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options, eid2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 2, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 2, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options, eid2), CHIP_NO_ERROR); + CheckLogState(logMgmt, 2, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 2, chip::app::PriorityLevel::Info); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options, eid3); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 3, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 3, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options, eid3), CHIP_NO_ERROR); + CheckLogState(logMgmt, 3, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 3, chip::app::PriorityLevel::Info); testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options, eid4); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 4, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 4, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options, eid4), CHIP_NO_ERROR); + CheckLogState(logMgmt, 4, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 4, chip::app::PriorityLevel::Info); // Start to drop off debug event since debug event can only be saved in debug buffer testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options, eid5); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 4, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 4, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options, eid5), CHIP_NO_ERROR); + CheckLogState(logMgmt, 4, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 4, chip::app::PriorityLevel::Info); testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options, eid6); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 4, chip::app::PriorityLevel::Debug); - CheckLogState(apSuite, logMgmt, 4, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options, eid6), CHIP_NO_ERROR); + CheckLogState(logMgmt, 4, chip::app::PriorityLevel::Debug); + CheckLogState(logMgmt, 4, chip::app::PriorityLevel::Info); } -/** - * Test Suite. It lists all the test functions. - */ - -const nlTest sTests[] = { - NL_TEST_DEF("CheckLogEventWithEvictToNextBufferNoUTCTime", CheckLogEventWithEvictToNextBuffer), - NL_TEST_DEF("CheckLogEventWithDiscardLowEventNoUTCTime", CheckLogEventWithDiscardLowEvent), - NL_TEST_SENTINEL(), -}; - -nlTestSuite sSuite = { - "EventLogging", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; } // namespace - -int TestEventLoggingNoUTCTime() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestEventLoggingNoUTCTime) diff --git a/src/app/tests/TestEventOverflow.cpp b/src/app/tests/TestEventOverflow.cpp index 23615f401d6f75..45692273c88274 100644 --- a/src/app/tests/TestEventOverflow.cpp +++ b/src/app/tests/TestEventOverflow.cpp @@ -35,15 +35,14 @@ #include #include #include -#include -#include #include #include #include #include #include -#include +#include +#include namespace { @@ -52,9 +51,20 @@ static uint8_t gInfoEventBuffer[2048]; static uint8_t gCritEventBuffer[2048]; static chip::app::CircularEventBuffer gCircularEventBuffer[3]; -class TestContext : public chip::Test::AppContext +class TestEventOverflow : public ::testing::Test { public: + static void SetUpTestSuite() + { + mpTestContext = new chip::Test::AppContext; + mpTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + delete mpTestContext; + } + // Performs setup for each individual test in the test suite void SetUp() override { @@ -64,13 +74,9 @@ class TestContext : public chip::Test::AppContext { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - chip::Test::AppContext::SetUp(); - - CHIP_ERROR err = CHIP_NO_ERROR; - // TODO: use ASSERT_EQ, once transition to pw_unit_test is complete - VerifyOrDieWithMsg((err = mEventCounter.Init(0)) == CHIP_NO_ERROR, AppServer, - "Init EventCounter failed: %" CHIP_ERROR_FORMAT, err.Format()); - chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), + mpTestContext->SetUp(); + ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); + chip::app::EventManagement::CreateEventManagement(&mpTestContext->GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); } @@ -78,13 +84,17 @@ class TestContext : public chip::Test::AppContext void TearDown() override { chip::app::EventManagement::DestroyEventManagement(); - chip::Test::AppContext::TearDown(); + mpTestContext->TearDown(); } + static chip::Test::AppContext * mpTestContext; + private: chip::MonotonicallyIncreasingCounter mEventCounter; }; +chip::Test::AppContext * TestEventOverflow::mpTestContext = nullptr; + class TestEventGenerator : public chip::app::EventLoggingDelegate { public: @@ -99,9 +109,8 @@ class TestEventGenerator : public chip::app::EventLoggingDelegate } }; -static void CheckLogEventOverFlow(nlTestSuite * apSuite, void * apContext) +TEST_F(TestEventOverflow, TestCheckLogEventOverFlow) { - CHIP_ERROR err = CHIP_NO_ERROR; chip::EventNumber oldEid = 0; chip::EventNumber eid = 0; chip::app::EventOptions options; @@ -152,35 +161,13 @@ static void CheckLogEventOverFlow(nlTestSuite * apSuite, void * apContext) } alternate = i % 10; - err = logMgmt.LogEvent(&testEventGenerator, options, eid); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options, eid), CHIP_NO_ERROR); if (eid > 0) { - NL_TEST_ASSERT(apSuite, eid == oldEid + 1); + EXPECT_EQ(eid, oldEid + 1); oldEid = eid; } } } -const nlTest sTests[] = { NL_TEST_DEF("CheckLogEventOverFlow", CheckLogEventOverFlow), NL_TEST_SENTINEL() }; - -// clang-format off -nlTestSuite sSuite = -{ - "TestEventOverflow", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; -// clang-format on - } // namespace - -int TestEventOverflow() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestEventOverflow) diff --git a/src/app/tests/TestFabricScopedEventLogging.cpp b/src/app/tests/TestFabricScopedEventLogging.cpp index 2ed758573aa5b6..d113bc692e069f 100644 --- a/src/app/tests/TestFabricScopedEventLogging.cpp +++ b/src/app/tests/TestFabricScopedEventLogging.cpp @@ -16,12 +16,6 @@ * limitations under the License. */ -/** - * @file - * This file implements a test for CHIP Interaction Model Fabric-scoped Event logging - * - */ - #include #include #include @@ -37,15 +31,14 @@ #include #include #include -#include -#include #include #include #include #include #include -#include +#include +#include namespace { @@ -60,9 +53,20 @@ static uint8_t gInfoEventBuffer[128]; static uint8_t gCritEventBuffer[128]; static chip::app::CircularEventBuffer gCircularEventBuffer[3]; -class TestContext : public chip::Test::AppContext +class TestFabricScopedEventLogging : public ::testing::Test { public: + static void SetUpTestSuite() + { + mpTestContext = new chip::Test::AppContext; + mpTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + delete mpTestContext; + } + // Performs setup for each individual test in the test suite void SetUp() override { @@ -72,13 +76,10 @@ class TestContext : public chip::Test::AppContext { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - chip::Test::AppContext::SetUp(); + mpTestContext->SetUp(); - CHIP_ERROR err = CHIP_NO_ERROR; - // TODO: use ASSERT_EQ, once transition to pw_unit_test is complete - VerifyOrDieWithMsg((err = mEventCounter.Init(0)) == CHIP_NO_ERROR, AppServer, - "Init EventCounter failed: %" CHIP_ERROR_FORMAT, err.Format()); - chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), + ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); + chip::app::EventManagement::CreateEventManagement(&mpTestContext->GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); } @@ -86,12 +87,15 @@ class TestContext : public chip::Test::AppContext void TearDown() override { chip::app::EventManagement::DestroyEventManagement(); - chip::Test::AppContext::TearDown(); + mpTestContext->TearDown(); } + static chip::Test::AppContext * mpTestContext; + private: chip::MonotonicallyIncreasingCounter mEventCounter; }; +chip::Test::AppContext * TestFabricScopedEventLogging::mpTestContext = nullptr; void ENFORCE_FORMAT(1, 2) SimpleDumpWriter(const char * aFormat, ...) { @@ -116,26 +120,22 @@ void PrintEventLog(chip::app::PriorityLevel aPriorityLevel) chip::TLV::Debug::Dump(reader, SimpleDumpWriter); } -static void CheckLogState(nlTestSuite * apSuite, chip::app::EventManagement & aLogMgmt, size_t expectedNumEvents, - chip::app::PriorityLevel aPriority) +static void CheckLogState(chip::app::EventManagement & aLogMgmt, size_t expectedNumEvents, chip::app::PriorityLevel aPriority) { - CHIP_ERROR err; chip::TLV::TLVReader reader; size_t elementCount; chip::app::CircularEventBufferWrapper bufWrapper; - err = aLogMgmt.GetEventReader(reader, aPriority, &bufWrapper); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(aLogMgmt.GetEventReader(reader, aPriority, &bufWrapper), CHIP_NO_ERROR); - err = chip::TLV::Utilities::Count(reader, elementCount, false); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(chip::TLV::Utilities::Count(reader, elementCount, false), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, elementCount == expectedNumEvents); + EXPECT_EQ(elementCount, expectedNumEvents); printf("elementCount vs expectedNumEvents : %u vs %u \n", static_cast(elementCount), static_cast(expectedNumEvents)); } -static void CheckLogReadOut(nlTestSuite * apSuite, chip::app::EventManagement & alogMgmt, chip::EventNumber startingEventNumber, - size_t expectedNumEvents, chip::SingleLinkedListNode * clusterInfo, +static void CheckLogReadOut(chip::app::EventManagement & alogMgmt, chip::EventNumber startingEventNumber, size_t expectedNumEvents, + chip::SingleLinkedListNode * clusterInfo, const chip::Access::SubjectDescriptor & aSubjectDescriptor) { CHIP_ERROR err; @@ -146,16 +146,17 @@ static void CheckLogReadOut(nlTestSuite * apSuite, chip::app::EventManagement & size_t totalNumElements; writer.Init(backingStore, 1024); err = alogMgmt.FetchEventsSince(writer, clusterInfo, startingEventNumber, eventCount, aSubjectDescriptor); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR || err == CHIP_END_OF_TLV); + EXPECT_TRUE(err == CHIP_NO_ERROR || err == CHIP_END_OF_TLV); reader.Init(backingStore, writer.GetLengthWritten()); - err = chip::TLV::Utilities::Count(reader, totalNumElements, false); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(chip::TLV::Utilities::Count(reader, totalNumElements, false), CHIP_NO_ERROR); printf("totalNumElements vs expectedNumEvents vs eventCount : %u vs %u vs %u \n", static_cast(totalNumElements), static_cast(expectedNumEvents), static_cast(eventCount)); - NL_TEST_ASSERT(apSuite, totalNumElements == expectedNumEvents && totalNumElements == eventCount); + EXPECT_EQ(totalNumElements, expectedNumEvents); + EXPECT_EQ(totalNumElements, eventCount); + reader.Init(backingStore, writer.GetLengthWritten()); chip::TLV::Debug::Dump(reader, SimpleDumpWriter); } @@ -178,9 +179,8 @@ class TestEventGenerator : public chip::app::EventLoggingDelegate int32_t mStatus; }; -static void CheckLogEventWithEvictToNextBuffer(nlTestSuite * apSuite, void * apContext) +TEST_F(TestFabricScopedEventLogging, TestCheckLogEventWithEvictToNextBuffer) { - CHIP_ERROR err = CHIP_NO_ERROR; chip::EventNumber eid1, eid2, eid3, eid4; chip::app::EventOptions options1; chip::app::EventOptions options2; @@ -194,29 +194,25 @@ static void CheckLogEventWithEvictToNextBuffer(nlTestSuite * apSuite, void * apC options2.mFabricIndex = 2; chip::app::EventManagement & logMgmt = chip::app::EventManagement::GetInstance(); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options1, eid1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 1, chip::app::PriorityLevel::Debug); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options1, eid1), CHIP_NO_ERROR); + CheckLogState(logMgmt, 1, chip::app::PriorityLevel::Debug); testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options1, eid2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 2, chip::app::PriorityLevel::Debug); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options1, eid2), CHIP_NO_ERROR); + CheckLogState(logMgmt, 2, chip::app::PriorityLevel::Debug); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options1, eid3); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 3, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options1, eid3), CHIP_NO_ERROR); + CheckLogState(logMgmt, 3, chip::app::PriorityLevel::Info); // Start to copy info event to next buffer since current debug buffer is full and info event is higher priority testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options2, eid4); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - CheckLogState(apSuite, logMgmt, 4, chip::app::PriorityLevel::Info); + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options2, eid4), CHIP_NO_ERROR); + CheckLogState(logMgmt, 4, chip::app::PriorityLevel::Info); PrintEventLog(chip::app::PriorityLevel::Debug); PrintEventLog(chip::app::PriorityLevel::Info); - NL_TEST_ASSERT(apSuite, (eid1 + 1) == eid2); - NL_TEST_ASSERT(apSuite, (eid2 + 1) == eid3); - NL_TEST_ASSERT(apSuite, (eid3 + 1) == eid4); + EXPECT_EQ((eid1 + 1), eid2); + EXPECT_EQ((eid2 + 1), eid3); + EXPECT_EQ((eid3 + 1), eid4); chip::SingleLinkedListNode paths[2]; @@ -230,66 +226,41 @@ static void CheckLogEventWithEvictToNextBuffer(nlTestSuite * apSuite, void * apC chip::Access::SubjectDescriptor descriptor; descriptor.fabricIndex = 1; - CheckLogReadOut(apSuite, logMgmt, 0, 3, &paths[0], descriptor); - CheckLogReadOut(apSuite, logMgmt, 1, 2, &paths[0], descriptor); - CheckLogReadOut(apSuite, logMgmt, 2, 1, &paths[0], descriptor); - CheckLogReadOut(apSuite, logMgmt, 3, 0, &paths[1], descriptor); + CheckLogReadOut(logMgmt, 0, 3, &paths[0], descriptor); + CheckLogReadOut(logMgmt, 1, 2, &paths[0], descriptor); + CheckLogReadOut(logMgmt, 2, 1, &paths[0], descriptor); + CheckLogReadOut(logMgmt, 3, 0, &paths[1], descriptor); descriptor.fabricIndex = 2; - CheckLogReadOut(apSuite, logMgmt, 3, 1, &paths[1], descriptor); + CheckLogReadOut(logMgmt, 3, 1, &paths[1], descriptor); paths[0].mpNext = &paths[1]; descriptor.fabricIndex = 1; - CheckLogReadOut(apSuite, logMgmt, 0, 3, paths, descriptor); + CheckLogReadOut(logMgmt, 0, 3, paths, descriptor); descriptor.fabricIndex = 2; - CheckLogReadOut(apSuite, logMgmt, 0, 1, paths, descriptor); + CheckLogReadOut(logMgmt, 0, 1, paths, descriptor); // Fabric event + wildcard test, only have one fabric-scoped event with fabric 2 chip::SingleLinkedListNode pathsWithWildcard[2]; paths[0].mValue.mEndpointId = kTestEndpointId1; paths[0].mValue.mClusterId = kLivenessClusterId; - CheckLogReadOut(apSuite, logMgmt, 0, 1, &pathsWithWildcard[1], descriptor); + CheckLogReadOut(logMgmt, 0, 1, &pathsWithWildcard[1], descriptor); paths[0].mpNext = &paths[1]; - CheckLogReadOut(apSuite, logMgmt, 0, 1, pathsWithWildcard, descriptor); + CheckLogReadOut(logMgmt, 0, 1, pathsWithWildcard, descriptor); // Invalidate obsolete fabric-scope event // Invalidate 3 event with fabric 1 descriptor.fabricIndex = 1; logMgmt.FabricRemoved(descriptor.fabricIndex); - CheckLogReadOut(apSuite, logMgmt, 0, 0, &pathsWithWildcard[1], descriptor); + CheckLogReadOut(logMgmt, 0, 0, &pathsWithWildcard[1], descriptor); // Invalidate 1 event with fabric 2 descriptor.fabricIndex = 2; logMgmt.FabricRemoved(descriptor.fabricIndex); - CheckLogReadOut(apSuite, logMgmt, 0, 0, &pathsWithWildcard[1], descriptor); + CheckLogReadOut(logMgmt, 0, 0, &pathsWithWildcard[1], descriptor); } -/** - * Test Suite. It lists all the test functions. - */ - -const nlTest sTests[] = { NL_TEST_DEF("CheckLogEventWithEvictToNextBuffer", CheckLogEventWithEvictToNextBuffer), - NL_TEST_SENTINEL() }; - -// clang-format off -nlTestSuite sSuite = -{ - "TestFabricScopedEventLogging", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; -// clang-format on } // namespace - -int TestFabricScopedEventLogging() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestFabricScopedEventLogging) diff --git a/src/app/tests/TestFailSafeContext.cpp b/src/app/tests/TestFailSafeContext.cpp index 96868ff241fa28..fa13990d4f7947 100644 --- a/src/app/tests/TestFailSafeContext.cpp +++ b/src/app/tests/TestFailSafeContext.cpp @@ -65,12 +65,9 @@ class TestFailSafeContext : public ::testing::Test TEST_F(TestFailSafeContext, TestFailSafeContext_ArmFailSafe) { - CHIP_ERROR err = CHIP_NO_ERROR; - chip::app::FailSafeContext failSafeContext; - err = failSafeContext.ArmFailSafe(kTestAccessingFabricIndex1, System::Clock::Seconds16(1)); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(failSafeContext.ArmFailSafe(kTestAccessingFabricIndex1, System::Clock::Seconds16(1)), CHIP_NO_ERROR); EXPECT_TRUE(failSafeContext.IsFailSafeArmed()); EXPECT_EQ(failSafeContext.GetFabricIndex(), kTestAccessingFabricIndex1); EXPECT_TRUE(failSafeContext.IsFailSafeArmed(kTestAccessingFabricIndex1)); @@ -82,12 +79,9 @@ TEST_F(TestFailSafeContext, TestFailSafeContext_ArmFailSafe) TEST_F(TestFailSafeContext, TestFailSafeContext_NocCommandInvoked) { - CHIP_ERROR err = CHIP_NO_ERROR; - chip::app::FailSafeContext failSafeContext; - err = failSafeContext.ArmFailSafe(kTestAccessingFabricIndex1, System::Clock::Seconds16(1)); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(failSafeContext.ArmFailSafe(kTestAccessingFabricIndex1, System::Clock::Seconds16(1)), CHIP_NO_ERROR); EXPECT_EQ(failSafeContext.GetFabricIndex(), kTestAccessingFabricIndex1); failSafeContext.SetAddNocCommandInvoked(kTestAccessingFabricIndex2); diff --git a/src/app/tests/TestInteractionModelEngine.cpp b/src/app/tests/TestInteractionModelEngine.cpp index 3d6abd9e651d49..1e471da68b01af 100644 --- a/src/app/tests/TestInteractionModelEngine.cpp +++ b/src/app/tests/TestInteractionModelEngine.cpp @@ -16,12 +16,6 @@ * limitations under the License. */ -/** - * @file - * This file implements unit tests for CHIP Interaction Model Engine - * - */ - #include #include #include @@ -31,23 +25,22 @@ #include #include #include +#include #include #include #include -#include #include -#include +#include #include #include #include +#include #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS #include #include -#endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS - -#include +#endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS namespace { using TestContext = chip::Test::AppContext; @@ -67,26 +60,53 @@ class NullReadHandlerCallback : public chip::app::ReadHandler::ManagementCallbac namespace chip { namespace app { -class TestInteractionModelEngine +class TestInteractionModelEngine : public ::testing::Test { public: - static void TestAttributePathParamsPushRelease(nlTestSuite * apSuite, void * apContext); - static void TestRemoveDuplicateConcreteAttribute(nlTestSuite * apSuite, void * apContext); -#if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS - static void TestSubjectHasPersistedSubscription(nlTestSuite * apSuite, void * apContext); -#if CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION - static void TestSubscriptionResumptionTimer(nlTestSuite * apSuite, void * apContext); -#endif // CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION -#endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS + static void SetUpTestSuite() + { + mpTestContext = new chip::Test::AppContext; + mpTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + if (mpTestContext != nullptr) + { + delete mpTestContext; + } + } + + void SetUp() override + { + + if (mpTestContext != nullptr) + { + mpTestContext->SetUp(); + } + } + void TearDown() override + { + if (mpTestContext != nullptr) + { + mpTestContext->TearDown(); + } + } + + void TestSubjectHasActiveSubscriptionSingleSubOneEntry(); + void TestSubjectHasActiveSubscriptionSingleSubMultipleEntries(); + void TestSubjectHasActiveSubscriptionMultipleSubsSingleEntry(); + void TestSubjectHasActiveSubscriptionMultipleSubsMultipleEntries(); + void TestSubjectHasActiveSubscriptionSubWithCAT(); + void TestSubscriptionResumptionTimer(); + void TestDecrementNumSubscriptionsToResume(); static int GetAttributePathListLength(SingleLinkedListNode * apattributePathParamsList); - static void TestSubjectHasActiveSubscriptionSingleSubOneEntry(nlTestSuite * apSuite, void * apContext); - static void TestSubjectHasActiveSubscriptionSingleSubMultipleEntries(nlTestSuite * apSuite, void * apContext); - static void TestSubjectHasActiveSubscriptionMultipleSubsSingleEntry(nlTestSuite * apSuite, void * apContext); - static void TestSubjectHasActiveSubscriptionMultipleSubsMultipleEntries(nlTestSuite * apSuite, void * apContext); - static void TestSubjectHasActiveSubscriptionSubWithCAT(nlTestSuite * apSuite, void * apContext); - static void TestDecrementNumSubscriptionsToResume(nlTestSuite * apSuite, void * apContext); + + static chip::Test::AppContext * mpTestContext; }; +chip::Test::AppContext * TestInteractionModelEngine::mpTestContext = nullptr; + int TestInteractionModelEngine::GetAttributePathListLength(SingleLinkedListNode * apAttributePathParamsList) { int length = 0; @@ -99,13 +119,15 @@ int TestInteractionModelEngine::GetAttributePathListLength(SingleLinkedListNode< return length; } -void TestInteractionModelEngine::TestAttributePathParamsPushRelease(nlTestSuite * apSuite, void * apContext) +TEST_F(TestInteractionModelEngine, TestAttributePathParamsPushRelease) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - err = InteractionModelEngine::GetInstance()->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), - app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + + InteractionModelEngine * engine = InteractionModelEngine::GetInstance(); + + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); + SingleLinkedListNode * attributePathParamsList = nullptr; AttributePathParams attributePathParams1; AttributePathParams attributePathParams2; @@ -115,158 +137,157 @@ void TestInteractionModelEngine::TestAttributePathParamsPushRelease(nlTestSuite attributePathParams2.mEndpointId = 2; attributePathParams3.mEndpointId = 3; - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); - NL_TEST_ASSERT(apSuite, - attributePathParamsList != nullptr && - attributePathParams1.mEndpointId == attributePathParamsList->mValue.mEndpointId); - NL_TEST_ASSERT(apSuite, GetAttributePathListLength(attributePathParamsList) == 1); - - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); - NL_TEST_ASSERT(apSuite, - attributePathParamsList != nullptr && - attributePathParams2.mEndpointId == attributePathParamsList->mValue.mEndpointId); - NL_TEST_ASSERT(apSuite, GetAttributePathListLength(attributePathParamsList) == 2); - - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); - NL_TEST_ASSERT(apSuite, - attributePathParamsList != nullptr && - attributePathParams3.mEndpointId == attributePathParamsList->mValue.mEndpointId); - NL_TEST_ASSERT(apSuite, GetAttributePathListLength(attributePathParamsList) == 3); - - InteractionModelEngine::GetInstance()->ReleaseAttributePathList(attributePathParamsList); - NL_TEST_ASSERT(apSuite, GetAttributePathListLength(attributePathParamsList) == 0); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); + ASSERT_NE(attributePathParamsList, nullptr); + EXPECT_EQ(attributePathParams1.mEndpointId, attributePathParamsList->mValue.mEndpointId); + EXPECT_EQ(GetAttributePathListLength(attributePathParamsList), 1); + + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); + ASSERT_NE(attributePathParamsList, nullptr); + EXPECT_EQ(attributePathParams2.mEndpointId, attributePathParamsList->mValue.mEndpointId); + EXPECT_EQ(GetAttributePathListLength(attributePathParamsList), 2); + + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); + ASSERT_NE(attributePathParamsList, nullptr); + EXPECT_EQ(attributePathParams3.mEndpointId, attributePathParamsList->mValue.mEndpointId); + EXPECT_EQ(GetAttributePathListLength(attributePathParamsList), 3); + + engine->ReleaseAttributePathList(attributePathParamsList); + EXPECT_EQ(GetAttributePathListLength(attributePathParamsList), 0); } -void TestInteractionModelEngine::TestRemoveDuplicateConcreteAttribute(nlTestSuite * apSuite, void * apContext) +TEST_F(TestInteractionModelEngine, TestRemoveDuplicateConcreteAttribute) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - err = InteractionModelEngine::GetInstance()->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), - app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + + InteractionModelEngine * engine = InteractionModelEngine::GetInstance(); + + EXPECT_EQ(CHIP_NO_ERROR, + engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler())); + SingleLinkedListNode * attributePathParamsList = nullptr; AttributePathParams attributePathParams1; AttributePathParams attributePathParams2; AttributePathParams attributePathParams3; // Three concrete paths, no duplicates - attributePathParams1.mEndpointId = Test::kMockEndpoint3; - attributePathParams1.mClusterId = Test::MockClusterId(2); - attributePathParams1.mAttributeId = Test::MockAttributeId(1); + attributePathParams1.mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams1.mClusterId = chip::Test::MockClusterId(2); + attributePathParams1.mAttributeId = chip::Test::MockAttributeId(1); - attributePathParams2.mEndpointId = Test::kMockEndpoint3; - attributePathParams2.mClusterId = Test::MockClusterId(2); - attributePathParams2.mAttributeId = Test::MockAttributeId(2); + attributePathParams2.mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams2.mClusterId = chip::Test::MockClusterId(2); + attributePathParams2.mAttributeId = chip::Test::MockAttributeId(2); - attributePathParams3.mEndpointId = Test::kMockEndpoint3; - attributePathParams3.mClusterId = Test::MockClusterId(2); - attributePathParams3.mAttributeId = Test::MockAttributeId(3); + attributePathParams3.mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams3.mClusterId = chip::Test::MockClusterId(2); + attributePathParams3.mAttributeId = chip::Test::MockAttributeId(3); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); - InteractionModelEngine::GetInstance()->RemoveDuplicateConcreteAttributePath(attributePathParamsList); - NL_TEST_ASSERT(apSuite, GetAttributePathListLength(attributePathParamsList) == 3); - InteractionModelEngine::GetInstance()->ReleaseAttributePathList(attributePathParamsList); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); + engine->RemoveDuplicateConcreteAttributePath(attributePathParamsList); + EXPECT_EQ(GetAttributePathListLength(attributePathParamsList), 3); + engine->ReleaseAttributePathList(attributePathParamsList); attributePathParams1.mEndpointId = kInvalidEndpointId; attributePathParams1.mClusterId = kInvalidClusterId; attributePathParams1.mAttributeId = kInvalidAttributeId; - attributePathParams2.mEndpointId = Test::kMockEndpoint3; - attributePathParams2.mClusterId = Test::MockClusterId(2); - attributePathParams2.mAttributeId = Test::MockAttributeId(2); + attributePathParams2.mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams2.mClusterId = chip::Test::MockClusterId(2); + attributePathParams2.mAttributeId = chip::Test::MockAttributeId(2); - attributePathParams3.mEndpointId = Test::kMockEndpoint3; - attributePathParams3.mClusterId = Test::MockClusterId(2); - attributePathParams3.mAttributeId = Test::MockAttributeId(3); + attributePathParams3.mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams3.mClusterId = chip::Test::MockClusterId(2); + attributePathParams3.mAttributeId = chip::Test::MockAttributeId(3); // 1st path is wildcard endpoint, 2nd, 3rd paths are concrete paths, the concrete ones would be removed. - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); - InteractionModelEngine::GetInstance()->RemoveDuplicateConcreteAttributePath(attributePathParamsList); - NL_TEST_ASSERT(apSuite, GetAttributePathListLength(attributePathParamsList) == 1); - InteractionModelEngine::GetInstance()->ReleaseAttributePathList(attributePathParamsList); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); + engine->RemoveDuplicateConcreteAttributePath(attributePathParamsList); + EXPECT_EQ(GetAttributePathListLength(attributePathParamsList), 1); + engine->ReleaseAttributePathList(attributePathParamsList); // 2nd path is wildcard endpoint, 1st, 3rd paths are concrete paths, the latter two would be removed. - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); - InteractionModelEngine::GetInstance()->RemoveDuplicateConcreteAttributePath(attributePathParamsList); - NL_TEST_ASSERT(apSuite, GetAttributePathListLength(attributePathParamsList) == 1); - InteractionModelEngine::GetInstance()->ReleaseAttributePathList(attributePathParamsList); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); + engine->RemoveDuplicateConcreteAttributePath(attributePathParamsList); + EXPECT_EQ(GetAttributePathListLength(attributePathParamsList), 1); + engine->ReleaseAttributePathList(attributePathParamsList); // 3nd path is wildcard endpoint, 1st, 2nd paths are concrete paths, the latter two would be removed. - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); - InteractionModelEngine::GetInstance()->RemoveDuplicateConcreteAttributePath(attributePathParamsList); - NL_TEST_ASSERT(apSuite, GetAttributePathListLength(attributePathParamsList) == 1); - InteractionModelEngine::GetInstance()->ReleaseAttributePathList(attributePathParamsList); - - attributePathParams1.mEndpointId = Test::kMockEndpoint3; - attributePathParams1.mClusterId = Test::MockClusterId(2); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); + engine->RemoveDuplicateConcreteAttributePath(attributePathParamsList); + EXPECT_EQ(GetAttributePathListLength(attributePathParamsList), 1); + engine->ReleaseAttributePathList(attributePathParamsList); + + attributePathParams1.mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams1.mClusterId = chip::Test::MockClusterId(2); attributePathParams1.mAttributeId = kInvalidAttributeId; - attributePathParams2.mEndpointId = Test::kMockEndpoint2; - attributePathParams2.mClusterId = Test::MockClusterId(2); - attributePathParams2.mAttributeId = Test::MockAttributeId(2); + attributePathParams2.mEndpointId = chip::Test::kMockEndpoint2; + attributePathParams2.mClusterId = chip::Test::MockClusterId(2); + attributePathParams2.mAttributeId = chip::Test::MockAttributeId(2); - attributePathParams3.mEndpointId = Test::kMockEndpoint2; - attributePathParams3.mClusterId = Test::MockClusterId(2); - attributePathParams3.mAttributeId = Test::MockAttributeId(3); + attributePathParams3.mEndpointId = chip::Test::kMockEndpoint2; + attributePathParams3.mClusterId = chip::Test::MockClusterId(2); + attributePathParams3.mAttributeId = chip::Test::MockAttributeId(3); // 1st is wildcard one, but not intersect with the latter two concrete paths, so the paths in total are 3 finally - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); - InteractionModelEngine::GetInstance()->RemoveDuplicateConcreteAttributePath(attributePathParamsList); - NL_TEST_ASSERT(apSuite, GetAttributePathListLength(attributePathParamsList) == 3); - InteractionModelEngine::GetInstance()->ReleaseAttributePathList(attributePathParamsList); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); + engine->RemoveDuplicateConcreteAttributePath(attributePathParamsList); + EXPECT_EQ(GetAttributePathListLength(attributePathParamsList), 3); + engine->ReleaseAttributePathList(attributePathParamsList); attributePathParams1.mEndpointId = kInvalidEndpointId; attributePathParams1.mClusterId = kInvalidClusterId; attributePathParams1.mAttributeId = kInvalidAttributeId; - attributePathParams2.mEndpointId = Test::kMockEndpoint3; + attributePathParams2.mEndpointId = chip::Test::kMockEndpoint3; attributePathParams2.mClusterId = kInvalidClusterId; attributePathParams2.mAttributeId = kInvalidAttributeId; attributePathParams3.mEndpointId = kInvalidEndpointId; attributePathParams3.mClusterId = kInvalidClusterId; - attributePathParams3.mAttributeId = Test::MockAttributeId(3); + attributePathParams3.mAttributeId = chip::Test::MockAttributeId(3); // Wildcards cannot be deduplicated. - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); - InteractionModelEngine::GetInstance()->RemoveDuplicateConcreteAttributePath(attributePathParamsList); - NL_TEST_ASSERT(apSuite, GetAttributePathListLength(attributePathParamsList) == 3); - InteractionModelEngine::GetInstance()->ReleaseAttributePathList(attributePathParamsList); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams3); + engine->RemoveDuplicateConcreteAttributePath(attributePathParamsList); + EXPECT_EQ(GetAttributePathListLength(attributePathParamsList), 3); + engine->ReleaseAttributePathList(attributePathParamsList); attributePathParams1.mEndpointId = kInvalidEndpointId; - attributePathParams1.mClusterId = Test::MockClusterId(2); - attributePathParams1.mAttributeId = Test::MockAttributeId(10); + attributePathParams1.mClusterId = chip::Test::MockClusterId(2); + attributePathParams1.mAttributeId = chip::Test::MockAttributeId(10); - attributePathParams2.mEndpointId = Test::kMockEndpoint3; - attributePathParams2.mClusterId = Test::MockClusterId(2); - attributePathParams2.mAttributeId = Test::MockAttributeId(10); + attributePathParams2.mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams2.mClusterId = chip::Test::MockClusterId(2); + attributePathParams2.mAttributeId = chip::Test::MockAttributeId(10); // 1st path is wildcard endpoint, 2nd path is invalid attribute - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); - InteractionModelEngine::GetInstance()->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); - InteractionModelEngine::GetInstance()->RemoveDuplicateConcreteAttributePath(attributePathParamsList); - NL_TEST_ASSERT(apSuite, GetAttributePathListLength(attributePathParamsList) == 2); - InteractionModelEngine::GetInstance()->ReleaseAttributePathList(attributePathParamsList); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams1); + engine->PushFrontAttributePathList(attributePathParamsList, attributePathParams2); + engine->RemoveDuplicateConcreteAttributePath(attributePathParamsList); + EXPECT_EQ(GetAttributePathListLength(attributePathParamsList), 2); + engine->ReleaseAttributePathList(attributePathParamsList); } /** * @brief Test verifies the SubjectHasActiveSubscription with a single subscription with a single entry */ -void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionSingleSubOneEntry(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestSubjectHasActiveSubscriptionSingleSubOneEntry) { - TestContext & ctx = *static_cast(apContext); + NullReadHandlerCallback nullCallback; InteractionModelEngine * engine = InteractionModelEngine::GetInstance(); @@ -274,44 +295,44 @@ void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionSingleSubOneEnt FabricIndex bobFabricIndex = 1; // Create ExchangeContext - Messaging::ExchangeContext * exchangeCtx1 = ctx.NewExchangeToBob(nullptr, false); - NL_TEST_ASSERT(apSuite, exchangeCtx1); + Messaging::ExchangeContext * exchangeCtx1 = mpTestContext->NewExchangeToBob(nullptr, false); + ASSERT_TRUE(exchangeCtx1); // InteractionModelEngine init - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == - engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), reporting::GetDefaultReportScheduler())); + EXPECT_EQ(CHIP_NO_ERROR, + engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + reporting::GetDefaultReportScheduler())); // Verify that there are no active subscriptions - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); // Create and setup readHandler 1 ReadHandler * readHandler1 = engine->GetReadHandlerPool().CreateObject( nullCallback, exchangeCtx1, ReadHandler::InteractionType::Subscribe, reporting::GetDefaultReportScheduler()); // Verify that Bob still doesn't have an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); // Set readHandler1 to active readHandler1->SetStateFlag(ReadHandler::ReadHandlerFlags::ActiveSubscription, true); // Verify that Bob still has an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); + EXPECT_TRUE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); // Clean up read handlers engine->GetReadHandlerPool().ReleaseAll(); // Verify that there are no active subscriptions - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); } /** * @brief Test verifies that the SubjectHasActiveSubscription will continue iterating till it fines at least one valid active * subscription */ -void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionSingleSubMultipleEntries(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestSubjectHasActiveSubscriptionSingleSubMultipleEntries) { - TestContext & ctx = *static_cast(apContext); + NullReadHandlerCallback nullCallback; InteractionModelEngine * engine = InteractionModelEngine::GetInstance(); @@ -319,45 +340,45 @@ void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionSingleSubMultip FabricIndex bobFabricIndex = 1; // Create ExchangeContexts - Messaging::ExchangeContext * exchangeCtx1 = ctx.NewExchangeToBob(nullptr, false); - NL_TEST_ASSERT(apSuite, exchangeCtx1); + Messaging::ExchangeContext * exchangeCtx1 = mpTestContext->NewExchangeToBob(nullptr, false); + ASSERT_TRUE(exchangeCtx1); - Messaging::ExchangeContext * exchangeCtx2 = ctx.NewExchangeToBob(nullptr, false); - NL_TEST_ASSERT(apSuite, exchangeCtx1); + Messaging::ExchangeContext * exchangeCtx2 = mpTestContext->NewExchangeToBob(nullptr, false); + ASSERT_TRUE(exchangeCtx1); // InteractionModelEngine init - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == - engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), reporting::GetDefaultReportScheduler())); + EXPECT_EQ(CHIP_NO_ERROR, + engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + reporting::GetDefaultReportScheduler())); // Verify that both Alice and Bob have no active subscriptions - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); // Create readHandler 1 engine->GetReadHandlerPool().CreateObject(nullCallback, exchangeCtx1, ReadHandler::InteractionType::Subscribe, reporting::GetDefaultReportScheduler()); // Verify that Bob still doesn't have an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); // Create and setup readHandler 2 ReadHandler * readHandler2 = engine->GetReadHandlerPool().CreateObject( nullCallback, exchangeCtx2, ReadHandler::InteractionType::Subscribe, reporting::GetDefaultReportScheduler()); // Verify that Bob still doesn't have an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); // Set readHandler2 to active readHandler2->SetStateFlag(ReadHandler::ReadHandlerFlags::ActiveSubscription, true); - // Verify that Bob still doesn't have an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); + // Verify that Bob has an active subscription + EXPECT_TRUE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); // Release active ReadHandler engine->GetReadHandlerPool().ReleaseObject(readHandler2); // Verify that there are no active subscriptions - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); // Clean up read handlers engine->GetReadHandlerPool().ReleaseAll(); @@ -366,9 +387,9 @@ void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionSingleSubMultip /** * @brief Test validates that the SubjectHasActiveSubscription can support multiple subscriptions from different clients */ -void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionMultipleSubsSingleEntry(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestSubjectHasActiveSubscriptionMultipleSubsSingleEntry) { - TestContext & ctx = *static_cast(apContext); + NullReadHandlerCallback nullCallback; InteractionModelEngine * engine = InteractionModelEngine::GetInstance(); @@ -378,20 +399,20 @@ void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionMultipleSubsSin FabricIndex aliceFabricIndex = 2; // Create ExchangeContexts - Messaging::ExchangeContext * exchangeCtx1 = ctx.NewExchangeToBob(nullptr, false); - NL_TEST_ASSERT(apSuite, exchangeCtx1); + Messaging::ExchangeContext * exchangeCtx1 = mpTestContext->NewExchangeToBob(nullptr, false); + ASSERT_TRUE(exchangeCtx1); - Messaging::ExchangeContext * exchangeCtx2 = ctx.NewExchangeToAlice(nullptr, false); - NL_TEST_ASSERT(apSuite, exchangeCtx2); + Messaging::ExchangeContext * exchangeCtx2 = mpTestContext->NewExchangeToAlice(nullptr, false); + ASSERT_TRUE(exchangeCtx2); // InteractionModelEngine init - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == - engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), reporting::GetDefaultReportScheduler())); + EXPECT_EQ(CHIP_NO_ERROR, + engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + reporting::GetDefaultReportScheduler())); // Verify that both Alice and Bob have no active subscriptions - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); // Create and setup readHandler 1 ReadHandler * readHandler1 = engine->GetReadHandlerPool().CreateObject( @@ -402,51 +423,49 @@ void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionMultipleSubsSin nullCallback, exchangeCtx2, ReadHandler::InteractionType::Subscribe, reporting::GetDefaultReportScheduler()); // Verify that Bob still doesn't have an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); // Set readHandler1 to active readHandler1->SetStateFlag(ReadHandler::ReadHandlerFlags::ActiveSubscription, true); // Verify that Bob has an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); + EXPECT_TRUE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); // Verify that Alice still doesn't have an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); // Set readHandler2 to active readHandler2->SetStateFlag(ReadHandler::ReadHandlerFlags::ActiveSubscription, true); // Verify that Bob has an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); + EXPECT_TRUE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); - // Verify that Alice still doesn't have an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); + // Verify that Alice has an active subscription + EXPECT_TRUE(engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); // Set readHandler1 to inactive readHandler1->SetStateFlag(ReadHandler::ReadHandlerFlags::ActiveSubscription, false); // Verify that Bob doesn't have an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); // Verify that Alice still has an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); + EXPECT_TRUE(engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); // Clean up read handlers engine->GetReadHandlerPool().ReleaseAll(); // Verify that both Alice and Bob have no active subscriptions - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); } /** * @brief Test validates that the SubjectHasActiveSubscription can find the active subscription even if there are multiple * subscriptions for each client */ -void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionMultipleSubsMultipleEntries(nlTestSuite * apSuite, - void * apContext) +TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestSubjectHasActiveSubscriptionMultipleSubsMultipleEntries) { - TestContext & ctx = *static_cast(apContext); NullReadHandlerCallback nullCallback; InteractionModelEngine * engine = InteractionModelEngine::GetInstance(); @@ -456,26 +475,26 @@ void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionMultipleSubsMul FabricIndex aliceFabricIndex = 2; // Create ExchangeContexts - Messaging::ExchangeContext * exchangeCtx11 = ctx.NewExchangeToBob(nullptr, false); - NL_TEST_ASSERT(apSuite, exchangeCtx11); + Messaging::ExchangeContext * exchangeCtx11 = mpTestContext->NewExchangeToBob(nullptr, false); + ASSERT_TRUE(exchangeCtx11); - Messaging::ExchangeContext * exchangeCtx12 = ctx.NewExchangeToBob(nullptr, false); - NL_TEST_ASSERT(apSuite, exchangeCtx12); + Messaging::ExchangeContext * exchangeCtx12 = mpTestContext->NewExchangeToBob(nullptr, false); + ASSERT_TRUE(exchangeCtx12); - Messaging::ExchangeContext * exchangeCtx21 = ctx.NewExchangeToAlice(nullptr, false); - NL_TEST_ASSERT(apSuite, exchangeCtx21); + Messaging::ExchangeContext * exchangeCtx21 = mpTestContext->NewExchangeToAlice(nullptr, false); + ASSERT_TRUE(exchangeCtx21); - Messaging::ExchangeContext * exchangeCtx22 = ctx.NewExchangeToAlice(nullptr, false); - NL_TEST_ASSERT(apSuite, exchangeCtx22); + Messaging::ExchangeContext * exchangeCtx22 = mpTestContext->NewExchangeToAlice(nullptr, false); + ASSERT_TRUE(exchangeCtx22); // InteractionModelEngine init - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == - engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), reporting::GetDefaultReportScheduler())); + EXPECT_EQ(CHIP_NO_ERROR, + engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + reporting::GetDefaultReportScheduler())); // Verify that both Alice and Bob have no active subscriptions - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); // Create and setup readHandler 1-1 engine->GetReadHandlerPool().CreateObject(nullCallback, exchangeCtx11, ReadHandler::InteractionType::Subscribe, @@ -494,50 +513,49 @@ void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionMultipleSubsMul nullCallback, exchangeCtx22, ReadHandler::InteractionType::Subscribe, reporting::GetDefaultReportScheduler()); // Verify that both Alice and Bob have no active subscriptions - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); // Set readHandler 1-2 to active readHandler12->SetStateFlag(ReadHandler::ReadHandlerFlags::ActiveSubscription, true); // Verify that Bob has an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); + EXPECT_TRUE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); // Verify that Alice still doesn't have an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); // Set readHandler 2-2 to active readHandler22->SetStateFlag(ReadHandler::ReadHandlerFlags::ActiveSubscription, true); // Verify that Bob has an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); + EXPECT_TRUE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); - // Verify that Alice still doesn't have an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); + // Verify that Alice has an active subscription + EXPECT_TRUE(engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); // Set readHandler1 to inactive readHandler12->SetStateFlag(ReadHandler::ReadHandlerFlags::ActiveSubscription, false); // Verify that Bob doesn't have an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); // Verify that Alice still has an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); + EXPECT_TRUE(engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); // Clean up read handlers engine->GetReadHandlerPool().ReleaseAll(); // Verify that both Alice and Bob have no active subscriptions - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId) == false); - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(aliceFabricIndex, aliceNodeId)); } /** * @brief Verifies that SubjectHasActiveSubscription support CATs as a subject-id */ -void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionSubWithCAT(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestSubjectHasActiveSubscriptionSubWithCAT) { - TestContext & ctx = *reinterpret_cast(apContext); InteractionModelEngine * engine = InteractionModelEngine::GetInstance(); NullReadHandlerCallback nullCallback; @@ -549,41 +567,41 @@ void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionSubWithCAT(nlTe FabricIndex bobFabricIndex = 1; // InteractionModelEngine init - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == - engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), reporting::GetDefaultReportScheduler())); + EXPECT_EQ(CHIP_NO_ERROR, + engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + reporting::GetDefaultReportScheduler())); // Make sure we are using CASE sessions, because there is no defunct-marking for PASE. - ctx.ExpireSessionBobToAlice(); - ctx.ExpireSessionAliceToBob(); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == ctx.CreateCASESessionBobToAlice(cats)); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == ctx.CreateCASESessionAliceToBob(cats)); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + EXPECT_EQ(CHIP_NO_ERROR, mpTestContext->CreateCASESessionBobToAlice(cats)); + EXPECT_EQ(CHIP_NO_ERROR, mpTestContext->CreateCASESessionAliceToBob(cats)); // Create ExchangeContexts - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToBob(nullptr, false); - NL_TEST_ASSERT(apSuite, exchangeCtx); + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToBob(nullptr, false); + ASSERT_TRUE(exchangeCtx); // Create readHandler ReadHandler * readHandler = engine->GetReadHandlerPool().CreateObject( nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, reporting::GetDefaultReportScheduler()); // Verify there are not active subscriptions - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, valideSubjectId) == false); - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, invalideSubjectId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, valideSubjectId)); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, invalideSubjectId)); // Set readHandler to active readHandler->SetStateFlag(ReadHandler::ReadHandlerFlags::ActiveSubscription, true); // Verify tthat valid subjectID has an active subscription - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, valideSubjectId)); - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, invalideSubjectId) == false); + EXPECT_TRUE(engine->SubjectHasActiveSubscription(bobFabricIndex, valideSubjectId)); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, invalideSubjectId)); // Clean up read handlers engine->GetReadHandlerPool().ReleaseAll(); // Verify there are not active subscriptions - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, valideSubjectId) == false); - NL_TEST_ASSERT(apSuite, engine->SubjectHasActiveSubscription(bobFabricIndex, invalideSubjectId) == false); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, valideSubjectId)); + EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, invalideSubjectId)); } #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS @@ -591,20 +609,18 @@ void TestInteractionModelEngine::TestSubjectHasActiveSubscriptionSubWithCAT(nlTe /** * @brief Test verifies the SubjectHasPersistedSubscription with single and multiple persisted subscriptions. */ -void TestInteractionModelEngine::TestSubjectHasPersistedSubscription(nlTestSuite * apSuite, void * apContext) +TEST_F(TestInteractionModelEngine, TestSubjectHasPersistedSubscription) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + InteractionModelEngine * engine = InteractionModelEngine::GetInstance(); chip::TestPersistentStorageDelegate storage; chip::app::SimpleSubscriptionResumptionStorage subscriptionStorage; - err = subscriptionStorage.Init(&storage); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(subscriptionStorage.Init(&storage), CHIP_NO_ERROR); - err = InteractionModelEngine::GetInstance()->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), - app::reporting::GetDefaultReportScheduler(), nullptr, &subscriptionStorage); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(CHIP_NO_ERROR, + engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler(), nullptr, &subscriptionStorage)); NodeId nodeId1 = 1; FabricIndex fabric1 = 1; @@ -621,29 +637,29 @@ void TestInteractionModelEngine::TestSubjectHasPersistedSubscription(nlTestSuite .mSubscriptionId = sub2 }; // Test with no persisted subscriptions - Should return false - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->SubjectHasPersistedSubscription(fabric1, nodeId1) == false); + EXPECT_FALSE(engine->SubjectHasPersistedSubscription(fabric1, nodeId1)); // Add one entry - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == subscriptionStorage.Save(info1)); + EXPECT_EQ(CHIP_NO_ERROR, subscriptionStorage.Save(info1)); // Verify that entry matches - Should return true - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->SubjectHasPersistedSubscription(fabric1, nodeId1)); + EXPECT_TRUE(engine->SubjectHasPersistedSubscription(fabric1, nodeId1)); // Test with absent subscription - Should return false - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->SubjectHasPersistedSubscription(fabric2, nodeId2) == false); + EXPECT_FALSE(engine->SubjectHasPersistedSubscription(fabric2, nodeId2)); // Add second entry - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == subscriptionStorage.Save(info2)); + EXPECT_EQ(CHIP_NO_ERROR, subscriptionStorage.Save(info2)); // Verify that entry matches - Should return true - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->SubjectHasPersistedSubscription(fabric2, nodeId2)); - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->SubjectHasPersistedSubscription(fabric1, nodeId1)); + EXPECT_TRUE(engine->SubjectHasPersistedSubscription(fabric2, nodeId2)); + EXPECT_TRUE(engine->SubjectHasPersistedSubscription(fabric1, nodeId1)); // Remove an entry - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == subscriptionStorage.Delete(nodeId1, fabric1, sub1)); + EXPECT_EQ(CHIP_NO_ERROR, subscriptionStorage.Delete(nodeId1, fabric1, sub1)); // Test with absent subscription - Should return false - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->SubjectHasPersistedSubscription(fabric1, nodeId1) == false); + EXPECT_FALSE(engine->SubjectHasPersistedSubscription(fabric1, nodeId1)); // Clean Up entries subscriptionStorage.DeleteAll(fabric1); @@ -652,48 +668,47 @@ void TestInteractionModelEngine::TestSubjectHasPersistedSubscription(nlTestSuite #if CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION -void TestInteractionModelEngine::TestSubscriptionResumptionTimer(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestSubscriptionResumptionTimer) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - err = InteractionModelEngine::GetInstance()->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), - app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + + InteractionModelEngine * engine = InteractionModelEngine::GetInstance(); + + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); uint32_t timeTillNextResubscriptionMs; - InteractionModelEngine::GetInstance()->mNumSubscriptionResumptionRetries = 0; - timeTillNextResubscriptionMs = InteractionModelEngine::GetInstance()->ComputeTimeSecondsTillNextSubscriptionResumption(); - NL_TEST_ASSERT(apSuite, timeTillNextResubscriptionMs == CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION_MIN_RETRY_INTERVAL_SECS); + engine->mNumSubscriptionResumptionRetries = 0; + timeTillNextResubscriptionMs = engine->ComputeTimeSecondsTillNextSubscriptionResumption(); + EXPECT_EQ(timeTillNextResubscriptionMs, (unsigned) CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION_MIN_RETRY_INTERVAL_SECS); uint32_t lastTimeTillNextResubscriptionMs = timeTillNextResubscriptionMs; - for (InteractionModelEngine::GetInstance()->mNumSubscriptionResumptionRetries = 1; - InteractionModelEngine::GetInstance()->mNumSubscriptionResumptionRetries <= - CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION_MAX_FIBONACCI_STEP_INDEX; - InteractionModelEngine::GetInstance()->mNumSubscriptionResumptionRetries++) + for (engine->mNumSubscriptionResumptionRetries = 1; + engine->mNumSubscriptionResumptionRetries <= CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION_MAX_FIBONACCI_STEP_INDEX; + engine->mNumSubscriptionResumptionRetries++) { - timeTillNextResubscriptionMs = InteractionModelEngine::GetInstance()->ComputeTimeSecondsTillNextSubscriptionResumption(); - NL_TEST_ASSERT(apSuite, timeTillNextResubscriptionMs >= lastTimeTillNextResubscriptionMs); - NL_TEST_ASSERT(apSuite, timeTillNextResubscriptionMs < CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION_MAX_RETRY_INTERVAL_SECS); + timeTillNextResubscriptionMs = engine->ComputeTimeSecondsTillNextSubscriptionResumption(); + EXPECT_GE(timeTillNextResubscriptionMs, lastTimeTillNextResubscriptionMs); + EXPECT_LT(timeTillNextResubscriptionMs, (unsigned) CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION_MAX_RETRY_INTERVAL_SECS); lastTimeTillNextResubscriptionMs = timeTillNextResubscriptionMs; } - InteractionModelEngine::GetInstance()->mNumSubscriptionResumptionRetries = 2000; - timeTillNextResubscriptionMs = InteractionModelEngine::GetInstance()->ComputeTimeSecondsTillNextSubscriptionResumption(); - NL_TEST_ASSERT(apSuite, timeTillNextResubscriptionMs == CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION_MAX_RETRY_INTERVAL_SECS); + engine->mNumSubscriptionResumptionRetries = 2000; + timeTillNextResubscriptionMs = engine->ComputeTimeSecondsTillNextSubscriptionResumption(); + EXPECT_EQ(timeTillNextResubscriptionMs, (unsigned) CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION_MAX_RETRY_INTERVAL_SECS); } #endif // CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION -void TestInteractionModelEngine::TestDecrementNumSubscriptionsToResume(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestDecrementNumSubscriptionsToResume) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; InteractionModelEngine * engine = InteractionModelEngine::GetInstance(); constexpr uint8_t kNumberOfSubsToResume = 5; uint8_t numberOfSubsRemaining = kNumberOfSubsToResume; - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); #if CHIP_CONFIG_ENABLE_ICD_CIP && !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION ICDManager manager; @@ -705,35 +720,35 @@ void TestInteractionModelEngine::TestDecrementNumSubscriptionsToResume(nlTestSui #if CHIP_CONFIG_ENABLE_ICD_CIP && !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION // Verify mIsBootUpResumeSubscriptionExecuted has not been set - NL_TEST_ASSERT(apSuite, !manager.GetIsBootUpResumeSubscriptionExecuted()); + EXPECT_FALSE(manager.GetIsBootUpResumeSubscriptionExecuted()); #endif // CHIP_CONFIG_ENABLE_ICD_CIP && CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION // Decrease number of subs by 1 numberOfSubsRemaining--; engine->DecrementNumSubscriptionsToResume(); - NL_TEST_ASSERT_EQUALS(apSuite, numberOfSubsRemaining, engine->mNumOfSubscriptionsToResume); + EXPECT_EQ(numberOfSubsRemaining, engine->mNumOfSubscriptionsToResume); // Decrease to 0 subs remaining while (numberOfSubsRemaining > 0) { #if CHIP_CONFIG_ENABLE_ICD_CIP && !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION // Verify mIsBootUpResumeSubscriptionExecuted has not been set - NL_TEST_ASSERT(apSuite, !manager.GetIsBootUpResumeSubscriptionExecuted()); + EXPECT_FALSE(manager.GetIsBootUpResumeSubscriptionExecuted()); #endif // CHIP_CONFIG_ENABLE_ICD_CIP && CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION numberOfSubsRemaining--; engine->DecrementNumSubscriptionsToResume(); - NL_TEST_ASSERT_EQUALS(apSuite, numberOfSubsRemaining, engine->mNumOfSubscriptionsToResume); + EXPECT_EQ(numberOfSubsRemaining, engine->mNumOfSubscriptionsToResume); } #if CHIP_CONFIG_ENABLE_ICD_CIP && !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION // Verify mIsBootUpResumeSubscriptionExecuted has been set - NL_TEST_ASSERT(apSuite, manager.GetIsBootUpResumeSubscriptionExecuted()); + EXPECT_TRUE(manager.GetIsBootUpResumeSubscriptionExecuted()); #endif // CHIP_CONFIG_ENABLE_ICD_CIP && CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION // Make sure we don't rollover / go negative engine->DecrementNumSubscriptionsToResume(); - NL_TEST_ASSERT_EQUALS(apSuite, numberOfSubsRemaining, engine->mNumOfSubscriptionsToResume); + EXPECT_EQ(numberOfSubsRemaining, engine->mNumOfSubscriptionsToResume); // Clean up #if CHIP_CONFIG_ENABLE_ICD_CIP && !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION @@ -744,47 +759,3 @@ void TestInteractionModelEngine::TestDecrementNumSubscriptionsToResume(nlTestSui } // namespace app } // namespace chip - -namespace { - -// clang-format off -const nlTest sTests[] = - { - NL_TEST_DEF("TestAttributePathParamsPushRelease", chip::app::TestInteractionModelEngine::TestAttributePathParamsPushRelease), - NL_TEST_DEF("TestRemoveDuplicateConcreteAttribute", chip::app::TestInteractionModelEngine::TestRemoveDuplicateConcreteAttribute), -#if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS - NL_TEST_DEF("TestSubjectHasPersistedSubscription", chip::app::TestInteractionModelEngine::TestSubjectHasPersistedSubscription), - NL_TEST_DEF("TestDecrementNumSubscriptionsToResume", chip::app::TestInteractionModelEngine::TestDecrementNumSubscriptionsToResume), -#if CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION - NL_TEST_DEF("TestSubscriptionResumptionTimer", chip::app::TestInteractionModelEngine::TestSubscriptionResumptionTimer), -#endif // CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION -#endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS - NL_TEST_DEF("TestSubjectHasActiveSubscriptionSingleSubOneEntry", chip::app::TestInteractionModelEngine::TestSubjectHasActiveSubscriptionSingleSubOneEntry), - NL_TEST_DEF("TestSubjectHasActiveSubscriptionSingleSubMultipleEntries", chip::app::TestInteractionModelEngine::TestSubjectHasActiveSubscriptionSingleSubMultipleEntries), - NL_TEST_DEF("TestSubjectHasActiveSubscriptionMultipleSubsSingleEntry", chip::app::TestInteractionModelEngine::TestSubjectHasActiveSubscriptionMultipleSubsSingleEntry), - NL_TEST_DEF("TestSubjectHasActiveSubscriptionMultipleSubsMultipleEntries", chip::app::TestInteractionModelEngine::TestSubjectHasActiveSubscriptionMultipleSubsMultipleEntries), - NL_TEST_DEF("TestSubjectHasActiveSubscriptionSubWithCAT", chip::app::TestInteractionModelEngine::TestSubjectHasActiveSubscriptionSubWithCAT), - NL_TEST_SENTINEL() - }; -// clang-format on - -// clang-format off -nlTestSuite sSuite = -{ - "TestInteractionModelEngine", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; -// clang-format on - -} // namespace - -int TestInteractionModelEngine() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestInteractionModelEngine) diff --git a/src/app/tests/TestReadInteraction.cpp b/src/app/tests/TestReadInteraction.cpp index 8d1d2e686896fa..561a0997afa2a8 100644 --- a/src/app/tests/TestReadInteraction.cpp +++ b/src/app/tests/TestReadInteraction.cpp @@ -16,14 +16,9 @@ * limitations under the License. */ -/** - * @file - * This file implements unit tests for CHIP Interaction Model Read Interaction - * - */ +#include #include "app/tests/test-interaction-model-api.h" - #include "lib/support/CHIPMem.h" #include #include @@ -39,17 +34,16 @@ #include #include #include +#include #include #include #include #include -#include -#include +#include #include #include -#include #include -#include +#include namespace { uint8_t gDebugEventBuffer[128]; @@ -76,75 +70,6 @@ static chip::System::Clock::ClockBase * gRealClock; static chip::app::reporting::ReportSchedulerImpl * gReportScheduler; static bool sUsingSubSync = false; -class TestContext : public chip::Test::AppContext -{ -public: - // Performs shared setup for all tests in the test suite - static void SetUpTestSuite() - { - chip::Test::AppContext::SetUpTestSuite(); - gRealClock = &chip::System::SystemClock(); - chip::System::Clock::Internal::SetSystemClockForTesting(&gMockClock); - - if (sSyncScheduler) - { - gReportScheduler = chip::app::reporting::GetSynchronizedReportScheduler(); - sUsingSubSync = true; - } - else - { - gReportScheduler = chip::app::reporting::GetDefaultReportScheduler(); - } - } - - // Performs shared teardown for all tests in the test suite - static void TearDownTestSuite() - { - chip::System::Clock::Internal::SetSystemClockForTesting(gRealClock); - chip::Test::AppContext::TearDownTestSuite(); - } - - // Performs setup for each individual test in the test suite - void SetUp() override - { - const chip::app::LogStorageResources logStorageResources[] = { - { &gDebugEventBuffer[0], sizeof(gDebugEventBuffer), chip::app::PriorityLevel::Debug }, - { &gInfoEventBuffer[0], sizeof(gInfoEventBuffer), chip::app::PriorityLevel::Info }, - { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, - }; - - chip::Test::AppContext::SetUp(); - - // TODO: change to ASSERT_EQ, once transition to pw_unit_test is complete - VerifyOrDie(mEventCounter.Init(0) == CHIP_NO_ERROR); - chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), - gCircularEventBuffer, logStorageResources, &mEventCounter); - } - - // Performs teardown for each individual test in the test suite - void TearDown() override - { - chip::app::EventManagement::DestroyEventManagement(); - chip::Test::AppContext::TearDown(); - } - -protected: - chip::MonotonicallyIncreasingCounter mEventCounter; - static bool sSyncScheduler; -}; - -bool TestContext::sSyncScheduler = false; - -class TestSyncContext : public TestContext -{ -public: - static void SetUpTestSuite() - { - sSyncScheduler = true; - TestContext::SetUpTestSuite(); - } -}; - class TestEventGenerator : public chip::app::EventLoggingDelegate { public: @@ -163,9 +88,8 @@ class TestEventGenerator : public chip::app::EventLoggingDelegate int32_t mStatus; }; -void GenerateEvents(nlTestSuite * apSuite, void * apContext) +void GenerateEvents() { - CHIP_ERROR err = CHIP_NO_ERROR; chip::EventNumber eid1, eid2; chip::app::EventOptions options1; options1.mPath = { kTestEventEndpointId, kTestEventClusterId, kTestEventIdDebug }; @@ -179,11 +103,11 @@ void GenerateEvents(nlTestSuite * apSuite, void * apContext) ChipLogDetail(DataManagement, "Generating Events"); testEventGenerator.SetStatus(0); - err = logMgmt.LogEvent(&testEventGenerator, options1, eid1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options1, eid1), CHIP_NO_ERROR); testEventGenerator.SetStatus(1); - err = logMgmt.LogEvent(&testEventGenerator, options2, eid2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + + EXPECT_EQ(logMgmt.LogEvent(&testEventGenerator, options2, eid2), CHIP_NO_ERROR); } class MockInteractionModelApp : public chip::app::ReadClient::Callback @@ -302,122 +226,147 @@ using ReadHandlerNode = chip::app::reporting::ReportScheduler::ReadHandlerNo namespace chip { namespace app { -class TestReadInteraction +using Seconds16 = System::Clock::Seconds16; +using Milliseconds32 = System::Clock::Milliseconds32; + +// TODO: Add support for a 2nd Test Context by making sSyncScheduler = true (this was not ported from NL Tests yet) +class TestReadInteraction : public ::testing::Test { - using Seconds16 = System::Clock::Seconds16; - using Milliseconds32 = System::Clock::Milliseconds32; public: - static void TestReadClient(nlTestSuite * apSuite, void * apContext); - static void TestReadUnexpectedSubscriptionId(nlTestSuite * apSuite, void * apContext); - static void TestReadHandler(nlTestSuite * apSuite, void * apContext); - static void TestReadClientGenerateAttributePathList(nlTestSuite * apSuite, void * apContext); - static void TestReadClientGenerateInvalidAttributePathList(nlTestSuite * apSuite, void * apContext); - static void TestReadClientGenerateOneEventPaths(nlTestSuite * apSuite, void * apContext); - static void TestReadClientGenerateTwoEventPaths(nlTestSuite * apSuite, void * apContext); - static void TestReadClientInvalidReport(nlTestSuite * apSuite, void * apContext); - static void TestReadClientInvalidAttributeId(nlTestSuite * apSuite, void * apContext); - static void TestReadHandlerInvalidAttributePath(nlTestSuite * apSuite, void * apContext); - static void TestProcessSubscribeRequest(nlTestSuite * apSuite, void * apContext); -#if CHIP_CONFIG_ENABLE_ICD_SERVER - static void TestICDProcessSubscribeRequestSupMaxIntervalCeiling(nlTestSuite * apSuite, void * apContext); - static void TestICDProcessSubscribeRequestInfMaxIntervalCeiling(nlTestSuite * apSuite, void * apContext); - static void TestICDProcessSubscribeRequestSupMinInterval(nlTestSuite * apSuite, void * apContext); - static void TestICDProcessSubscribeRequestMaxMinInterval(nlTestSuite * apSuite, void * apContext); - static void TestICDProcessSubscribeRequestInvalidIdleModeDuration(nlTestSuite * apSuite, void * apContext); -#endif // CHIP_CONFIG_ENABLE_ICD_SERVER - static void TestReadRoundtrip(nlTestSuite * apSuite, void * apContext); - static void TestPostSubscribeRoundtripChunkReport(nlTestSuite * apSuite, void * apContext); - static void TestReadRoundtripWithDataVersionFilter(nlTestSuite * apSuite, void * apContext); - static void TestReadRoundtripWithNoMatchPathDataVersionFilter(nlTestSuite * apSuite, void * apContext); - static void TestReadRoundtripWithMultiSamePathDifferentDataVersionFilter(nlTestSuite * apSuite, void * apContext); - static void TestReadRoundtripWithSameDifferentPathsDataVersionFilter(nlTestSuite * apSuite, void * apContext); - static void TestReadWildcard(nlTestSuite * apSuite, void * apContext); - static void TestReadChunking(nlTestSuite * apSuite, void * apContext); - static void TestSetDirtyBetweenChunks(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeRoundtrip(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeEarlyReport(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeUrgentWildcardEvent(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeWildcard(nlTestSuite * apSuite, void * apContext); - static void TestSubscribePartialOverlap(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeSetDirtyFullyOverlap(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeEarlyShutdown(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeInvalidAttributePathRoundtrip(nlTestSuite * apSuite, void * apContext); - static void TestReadInvalidAttributePathRoundtrip(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeInvalidInterval(nlTestSuite * apSuite, void * apContext); - static void TestReadShutdown(nlTestSuite * apSuite, void * apContext); - static void TestResubscribeRoundtrip(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeRoundtripStatusReportTimeout(nlTestSuite * apSuite, void * apContext); - static void TestPostSubscribeRoundtripStatusReportTimeout(nlTestSuite * apSuite, void * apContext); - static void TestReadChunkingStatusReportTimeout(nlTestSuite * apSuite, void * apContext); - static void TestReadReportFailure(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeRoundtripChunkStatusReportTimeout(nlTestSuite * apSuite, void * apContext); - static void TestPostSubscribeRoundtripChunkStatusReportTimeout(nlTestSuite * apSuite, void * apContext); - static void TestPostSubscribeRoundtripChunkReportTimeout(nlTestSuite * apSuite, void * apContext); - static void TestReadClientReceiveInvalidMessage(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeClientReceiveInvalidStatusResponse(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeClientReceiveWellFormedStatusResponse(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeClientReceiveInvalidReportMessage(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeClientReceiveUnsolicitedInvalidReportMessage(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeClientReceiveInvalidSubscribeResponseMessage(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeClientReceiveUnsolicitedReportMessageWithInvalidSubscriptionId(nlTestSuite * apSuite, - void * apContext); - static void TestReadChunkingInvalidSubscriptionId(nlTestSuite * apSuite, void * apContext); - static void TestReadHandlerMalformedReadRequest1(nlTestSuite * apSuite, void * apContext); - static void TestReadHandlerMalformedReadRequest2(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeSendUnknownMessage(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeSendInvalidStatusReport(nlTestSuite * apSuite, void * apContext); - static void TestReadHandlerInvalidSubscribeRequest(nlTestSuite * apSuite, void * apContext); - static void TestSubscribeInvalidateFabric(nlTestSuite * apSuite, void * apContext); - static void TestShutdownSubscription(nlTestSuite * apSuite, void * apContext); - static void TestSubscriptionReportWithDefunctSession(nlTestSuite * apSuite, void * apContext); - static void TestReadHandlerMalformedSubscribeRequest(nlTestSuite * apSuite, void * apContext); + static void SetUpTestSuite() + { + mpTestContext = new chip::Test::AppContext; + mpTestContext->SetUpTestSuite(); + + gRealClock = &chip::System::SystemClock(); + chip::System::Clock::Internal::SetSystemClockForTesting(&gMockClock); + + if (sSyncScheduler) + { + gReportScheduler = chip::app::reporting::GetSynchronizedReportScheduler(); + sUsingSubSync = true; + } + else + { + gReportScheduler = chip::app::reporting::GetDefaultReportScheduler(); + } + } + static void TearDownTestSuite() + { + chip::System::Clock::Internal::SetSystemClockForTesting(gRealClock); + + mpTestContext->TearDownTestSuite(); + delete mpTestContext; + } + + void SetUp() + { + const chip::app::LogStorageResources logStorageResources[] = { + { &gDebugEventBuffer[0], sizeof(gDebugEventBuffer), chip::app::PriorityLevel::Debug }, + { &gInfoEventBuffer[0], sizeof(gInfoEventBuffer), chip::app::PriorityLevel::Info }, + { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, + }; + + mpTestContext->SetUp(); + + ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); + chip::app::EventManagement::CreateEventManagement(&mpTestContext->GetExchangeManager(), ArraySize(logStorageResources), + gCircularEventBuffer, logStorageResources, &mEventCounter); + } + void TearDown() + { + chip::app::EventManagement::DestroyEventManagement(); + mpTestContext->TearDown(); + } + + static chip::Test::AppContext * mpTestContext; + + void TestReadClient(); + void TestReadUnexpectedSubscriptionId(); + void TestReadHandler(); + void TestReadClientGenerateAttributePathList(); + void TestReadClientGenerateInvalidAttributePathList(); + void TestReadClientInvalidReport(); + void TestReadClientInvalidAttributeId(); + void TestReadHandlerInvalidAttributePath(); + void TestReadClientGenerateOneEventPaths(); + void TestReadClientGenerateTwoEventPaths(); + void TestProcessSubscribeRequest(); + void TestICDProcessSubscribeRequestSupMaxIntervalCeiling(); + void TestICDProcessSubscribeRequestInfMaxIntervalCeiling(); + void TestICDProcessSubscribeRequestSupMinInterval(); + void TestICDProcessSubscribeRequestMaxMinInterval(); + void TestICDProcessSubscribeRequestInvalidIdleModeDuration(); + void TestSubscribeRoundtrip(); + void TestSubscribeEarlyReport(); + void TestSubscribeUrgentWildcardEvent(); + void TestSubscribeInvalidAttributePathRoundtrip(); + void TestPostSubscribeRoundtripStatusReportTimeout(); + void TestReadClientReceiveInvalidMessage(); + void TestSubscribeClientReceiveInvalidStatusResponse(); + void TestSubscribeClientReceiveWellFormedStatusResponse(); + void TestSubscribeClientReceiveInvalidReportMessage(); + void TestSubscribeClientReceiveUnsolicitedInvalidReportMessage(); + void TestSubscribeClientReceiveInvalidSubscribeResponseMessage(); + void TestSubscribeClientReceiveUnsolicitedReportMessageWithInvalidSubscriptionId(); + void TestReadChunkingInvalidSubscriptionId(); + void TestReadHandlerMalformedSubscribeRequest(); + void TestReadHandlerMalformedReadRequest1(); + void TestReadHandlerMalformedReadRequest2(); + void TestSubscribeSendUnknownMessage(); + void TestSubscribeSendInvalidStatusReport(); + void TestReadHandlerInvalidSubscribeRequest(); + void TestShutdownSubscription(); + void TestSubscriptionReportWithDefunctSession(); -private: enum class ReportType : uint8_t { kValid, kInvalidNoAttributeId, kInvalidOutOfRangeAttributeId, }; + static void GenerateReportData(System::PacketBufferHandle & aPayload, ReportType aReportType, bool aSuppressResponse, + bool aHasSubscriptionId); - static void GenerateReportData(nlTestSuite * apSuite, void * apContext, System::PacketBufferHandle & aPayload, - ReportType aReportType, bool aSuppressResponse, bool aHasSubscriptionId); +protected: + chip::MonotonicallyIncreasingCounter mEventCounter; + static bool sSyncScheduler; }; -void TestReadInteraction::GenerateReportData(nlTestSuite * apSuite, void * apContext, System::PacketBufferHandle & aPayload, - ReportType aReportType, bool aSuppressResponse, bool aHasSubscriptionId = false) +chip::Test::AppContext * TestReadInteraction::mpTestContext = nullptr; +bool TestReadInteraction::sSyncScheduler = false; + +void TestReadInteraction::GenerateReportData(System::PacketBufferHandle & aPayload, ReportType aReportType, bool aSuppressResponse, + bool aHasSubscriptionId = false) { - CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBufferTLVWriter writer; writer.Init(std::move(aPayload)); ReportDataMessage::Builder reportDataMessageBuilder; - err = reportDataMessageBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(reportDataMessageBuilder.Init(&writer), CHIP_NO_ERROR); if (aHasSubscriptionId) { reportDataMessageBuilder.SubscriptionId(1); - NL_TEST_ASSERT(apSuite, reportDataMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(reportDataMessageBuilder.GetError(), CHIP_NO_ERROR); } AttributeReportIBs::Builder & attributeReportIBsBuilder = reportDataMessageBuilder.CreateAttributeReportIBs(); - NL_TEST_ASSERT(apSuite, reportDataMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(reportDataMessageBuilder.GetError(), CHIP_NO_ERROR); AttributeReportIB::Builder & attributeReportIBBuilder = attributeReportIBsBuilder.CreateAttributeReport(); - NL_TEST_ASSERT(apSuite, attributeReportIBsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeReportIBsBuilder.GetError(), CHIP_NO_ERROR); AttributeDataIB::Builder & attributeDataIBBuilder = attributeReportIBBuilder.CreateAttributeData(); - NL_TEST_ASSERT(apSuite, attributeReportIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeReportIBBuilder.GetError(), CHIP_NO_ERROR); attributeDataIBBuilder.DataVersion(2); - err = attributeDataIBBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributeDataIBBuilder.GetError(), CHIP_NO_ERROR); AttributePathIB::Builder & attributePathBuilder = attributeDataIBBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributeDataIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeDataIBBuilder.GetError(), CHIP_NO_ERROR); if (aReportType == ReportType::kInvalidNoAttributeId) { @@ -429,103 +378,91 @@ void TestReadInteraction::GenerateReportData(nlTestSuite * apSuite, void * apCon } else { - NL_TEST_ASSERT(apSuite, aReportType == ReportType::kValid); + EXPECT_EQ(aReportType, ReportType::kValid); attributePathBuilder.Node(1).Endpoint(2).Cluster(3).Attribute(4).EndOfAttributePathIB(); } - err = attributePathBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder.GetError(), CHIP_NO_ERROR); // Construct attribute data { chip::TLV::TLVWriter * pWriter = attributeDataIBBuilder.GetWriter(); chip::TLV::TLVType dummyType = chip::TLV::kTLVType_NotSpecified; - err = pWriter->StartContainer(chip::TLV::ContextTag(chip::to_underlying(chip::app::AttributeDataIB::Tag::kData)), - chip::TLV::kTLVType_Structure, dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - - err = pWriter->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(pWriter->StartContainer(chip::TLV::ContextTag(chip::to_underlying(chip::app::AttributeDataIB::Tag::kData)), + chip::TLV::kTLVType_Structure, dummyType), + CHIP_NO_ERROR); - err = pWriter->EndContainer(dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(pWriter->PutBoolean(chip::TLV::ContextTag(1), true), CHIP_NO_ERROR); + EXPECT_EQ(pWriter->EndContainer(dummyType), CHIP_NO_ERROR); } attributeDataIBBuilder.EndOfAttributeDataIB(); - NL_TEST_ASSERT(apSuite, attributeDataIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeDataIBBuilder.GetError(), CHIP_NO_ERROR); attributeReportIBBuilder.EndOfAttributeReportIB(); - NL_TEST_ASSERT(apSuite, attributeReportIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeReportIBBuilder.GetError(), CHIP_NO_ERROR); attributeReportIBsBuilder.EndOfAttributeReportIBs(); - NL_TEST_ASSERT(apSuite, attributeReportIBsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeReportIBsBuilder.GetError(), CHIP_NO_ERROR); reportDataMessageBuilder.MoreChunkedMessages(false); - NL_TEST_ASSERT(apSuite, reportDataMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(reportDataMessageBuilder.GetError(), CHIP_NO_ERROR); reportDataMessageBuilder.SuppressResponse(aSuppressResponse); - NL_TEST_ASSERT(apSuite, reportDataMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(reportDataMessageBuilder.GetError(), CHIP_NO_ERROR); reportDataMessageBuilder.EndOfReportDataMessage(); - NL_TEST_ASSERT(apSuite, reportDataMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(reportDataMessageBuilder.GetError(), CHIP_NO_ERROR); - err = writer.Finalize(&aPayload); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&aPayload), CHIP_NO_ERROR); } -void TestReadInteraction::TestReadClient(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClient) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); MockInteractionModelApp delegate; - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); + System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); // We don't actually want to deliver that message, because we want to // synthesize the read response. But we don't want it hanging around // forever either. - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->DrainAndServiceIO(); - GenerateReportData(apSuite, apContext, buf, ReportType::kValid, true /* aSuppressResponse*/); - err = readClient.ProcessReportData(std::move(buf), ReadClient::ReportType::kContinuingTransaction); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + GenerateReportData(buf, ReportType::kValid, true /* aSuppressResponse*/); + EXPECT_EQ(readClient.ProcessReportData(std::move(buf), ReadClient::ReportType::kContinuingTransaction), CHIP_NO_ERROR); } -void TestReadInteraction::TestReadUnexpectedSubscriptionId(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadUnexpectedSubscriptionId) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); MockInteractionModelApp delegate; - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); + System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); // We don't actually want to deliver that message, because we want to // synthesize the read response. But we don't want it hanging around // forever either. - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->DrainAndServiceIO(); // For read, we don't expect there is subscription id in report data. - GenerateReportData(apSuite, apContext, buf, ReportType::kValid, true /* aSuppressResponse*/, true /*aHasSubscriptionId*/); - err = readClient.ProcessReportData(std::move(buf), ReadClient::ReportType::kContinuingTransaction); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_INVALID_ARGUMENT); + GenerateReportData(buf, ReportType::kValid, true /* aSuppressResponse*/, true /*aHasSubscriptionId*/); + EXPECT_EQ(readClient.ProcessReportData(std::move(buf), ReadClient::ReportType::kContinuingTransaction), + CHIP_ERROR_INVALID_ARGUMENT); } -void TestReadInteraction::TestReadHandler(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandler) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); System::PacketBufferTLVWriter writer; System::PacketBufferHandle reportDatabuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); System::PacketBufferHandle readRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); @@ -533,67 +470,58 @@ void TestReadInteraction::TestReadHandler(nlTestSuite * apSuite, void * apContex NullReadHandlerCallback nullCallback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); { - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); ReadHandler readHandler(nullCallback, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); - GenerateReportData(apSuite, apContext, reportDatabuf, ReportType::kValid, false /* aSuppressResponse*/); - err = readHandler.SendReportData(std::move(reportDatabuf), false); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_INCORRECT_STATE); + GenerateReportData(reportDatabuf, ReportType::kValid, false /* aSuppressResponse*/); + EXPECT_EQ(readHandler.SendReportData(std::move(reportDatabuf), false), CHIP_ERROR_INCORRECT_STATE); writer.Init(std::move(readRequestbuf)); - err = readRequestBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readRequestBuilder.Init(&writer), CHIP_NO_ERROR); AttributePathIBs::Builder & attributePathListBuilder = readRequestBuilder.CreateAttributeRequests(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); AttributePathIB::Builder & attributePathBuilder = attributePathListBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); attributePathBuilder.Node(1).Endpoint(2).Cluster(3).Attribute(4).EndOfAttributePathIB(); - err = attributePathBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder.GetError(), CHIP_NO_ERROR); attributePathListBuilder.EndOfAttributePathIBs(); - err = attributePathListBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, readRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(readRequestBuilder.GetError(), CHIP_NO_ERROR); readRequestBuilder.IsFabricFiltered(false).EndOfReadRequestMessage(); - NL_TEST_ASSERT(apSuite, readRequestBuilder.GetError() == CHIP_NO_ERROR); - err = writer.Finalize(&readRequestbuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readRequestBuilder.GetError(), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&readRequestbuf), CHIP_NO_ERROR); // Call ProcessReadRequest directly, because OnInitialRequest sends status // messages on the wire instead of returning an error. - err = readHandler.ProcessReadRequest(std::move(readRequestbuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readHandler.ProcessReadRequest(std::move(readRequestbuf)), CHIP_NO_ERROR); } engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestReadClientGenerateAttributePathList(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateAttributePathList) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); MockInteractionModelApp delegate; System::PacketBufferHandle msgBuf; System::PacketBufferTLVWriter writer; ReadRequestMessage::Builder request; msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); writer.Init(std::move(msgBuf)); - err = request.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(request.Init(&writer), CHIP_NO_ERROR); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); AttributePathParams attributePathParams[2]; @@ -604,27 +532,23 @@ void TestReadInteraction::TestReadClientGenerateAttributePathList(nlTestSuite * Span attributePaths(attributePathParams, 2 /*aAttributePathParamsListSize*/); AttributePathIBs::Builder & attributePathListBuilder = request.CreateAttributeRequests(); - err = readClient.GenerateAttributePaths(attributePathListBuilder, attributePaths); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.GenerateAttributePaths(attributePathListBuilder, attributePaths), CHIP_NO_ERROR); } -void TestReadInteraction::TestReadClientGenerateInvalidAttributePathList(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateInvalidAttributePathList) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); MockInteractionModelApp delegate; System::PacketBufferHandle msgBuf; System::PacketBufferTLVWriter writer; ReadRequestMessage::Builder request; msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); writer.Init(std::move(msgBuf)); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = request.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(request.Init(&writer), CHIP_NO_ERROR); AttributePathParams attributePathParams[2]; attributePathParams[0].mAttributeId = 0; @@ -633,75 +557,68 @@ void TestReadInteraction::TestReadClientGenerateInvalidAttributePathList(nlTestS Span attributePaths(attributePathParams, 2 /*aAttributePathParamsListSize*/); AttributePathIBs::Builder & attributePathListBuilder = request.CreateAttributeRequests(); - err = readClient.GenerateAttributePaths(attributePathListBuilder, attributePaths); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_IM_MALFORMED_ATTRIBUTE_PATH_IB); + EXPECT_EQ(readClient.GenerateAttributePaths(attributePathListBuilder, attributePaths), + CHIP_ERROR_IM_MALFORMED_ATTRIBUTE_PATH_IB); } -void TestReadInteraction::TestReadClientInvalidReport(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientInvalidReport) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); MockInteractionModelApp delegate; System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); // We don't actually want to deliver that message, because we want to // synthesize the read response. But we don't want it hanging around // forever either. - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->DrainAndServiceIO(); - GenerateReportData(apSuite, apContext, buf, ReportType::kInvalidNoAttributeId, true /* aSuppressResponse*/); + GenerateReportData(buf, ReportType::kInvalidNoAttributeId, true /* aSuppressResponse*/); - err = readClient.ProcessReportData(std::move(buf), ReadClient::ReportType::kContinuingTransaction); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_IM_MALFORMED_ATTRIBUTE_PATH_IB); + EXPECT_EQ(readClient.ProcessReportData(std::move(buf), ReadClient::ReportType::kContinuingTransaction), + CHIP_ERROR_IM_MALFORMED_ATTRIBUTE_PATH_IB); } -void TestReadInteraction::TestReadClientInvalidAttributeId(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientInvalidAttributeId) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); MockInteractionModelApp delegate; System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); // We don't actually want to deliver that message, because we want to // synthesize the read response. But we don't want it hanging around // forever either. - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->DrainAndServiceIO(); - GenerateReportData(apSuite, apContext, buf, ReportType::kInvalidOutOfRangeAttributeId, true /* aSuppressResponse*/); + GenerateReportData(buf, ReportType::kInvalidOutOfRangeAttributeId, true /* aSuppressResponse*/); - err = readClient.ProcessReportData(std::move(buf), ReadClient::ReportType::kContinuingTransaction); // Overall processing should succeed. - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.ProcessReportData(std::move(buf), ReadClient::ReportType::kContinuingTransaction), CHIP_NO_ERROR); // We should not have gotten any attribute reports or errors. - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 0); - NL_TEST_ASSERT(apSuite, !delegate.mGotReport); - NL_TEST_ASSERT(apSuite, !delegate.mReadError); + EXPECT_FALSE(delegate.mGotEventResponse); + EXPECT_EQ(delegate.mNumAttributeResponse, 0); + EXPECT_FALSE(delegate.mGotReport); + EXPECT_FALSE(delegate.mReadError); } -void TestReadInteraction::TestReadHandlerInvalidAttributePath(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerInvalidAttributePath) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); + CHIP_ERROR err = CHIP_NO_ERROR; + System::PacketBufferTLVWriter writer; System::PacketBufferHandle reportDatabuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); System::PacketBufferHandle readRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); @@ -709,41 +626,36 @@ void TestReadInteraction::TestReadHandlerInvalidAttributePath(nlTestSuite * apSu NullReadHandlerCallback nullCallback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); { - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); ReadHandler readHandler(nullCallback, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); - GenerateReportData(apSuite, apContext, reportDatabuf, ReportType::kValid, false /* aSuppressResponse*/); - err = readHandler.SendReportData(std::move(reportDatabuf), false); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_INCORRECT_STATE); + GenerateReportData(reportDatabuf, ReportType::kValid, false /* aSuppressResponse*/); + EXPECT_EQ(readHandler.SendReportData(std::move(reportDatabuf), false), CHIP_ERROR_INCORRECT_STATE); writer.Init(std::move(readRequestbuf)); - err = readRequestBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readRequestBuilder.Init(&writer), CHIP_NO_ERROR); AttributePathIBs::Builder & attributePathListBuilder = readRequestBuilder.CreateAttributeRequests(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); AttributePathIB::Builder & attributePathBuilder = attributePathListBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); attributePathBuilder.Node(1).Endpoint(2).Cluster(3).EndOfAttributePathIB(); - err = attributePathBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder.GetError(), CHIP_NO_ERROR); - attributePathListBuilder.EndOfAttributePathIBs(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.EndOfAttributePathIBs(), CHIP_NO_ERROR); readRequestBuilder.EndOfReadRequestMessage(); - NL_TEST_ASSERT(apSuite, readRequestBuilder.GetError() == CHIP_NO_ERROR); - err = writer.Finalize(&readRequestbuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readRequestBuilder.GetError(), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&readRequestbuf), CHIP_NO_ERROR); err = readHandler.ProcessReadRequest(std::move(readRequestbuf)); ChipLogError(DataManagement, "The error is %s", ErrorStr(err)); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_END_OF_TLV); + EXPECT_EQ(err, CHIP_ERROR_END_OF_TLV); // // In the call above to ProcessReadRequest, the handler will not actually close out the EC since @@ -757,24 +669,21 @@ void TestReadInteraction::TestReadHandlerInvalidAttributePath(nlTestSuite * apSu } engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestReadClientGenerateOneEventPaths(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateOneEventPaths) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); MockInteractionModelApp delegate; System::PacketBufferHandle msgBuf; System::PacketBufferTLVWriter writer; ReadRequestMessage::Builder request; msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); writer.Init(std::move(msgBuf)); - err = request.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(request.Init(&writer), CHIP_NO_ERROR); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); chip::app::EventPathParams eventPathParams[1]; @@ -784,44 +693,38 @@ void TestReadInteraction::TestReadClientGenerateOneEventPaths(nlTestSuite * apSu EventPathIBs::Builder & eventPathListBuilder = request.CreateEventRequests(); Span eventPaths(eventPathParams, 1 /*aEventPathParamsListSize*/); - err = readClient.GenerateEventPaths(eventPathListBuilder, eventPaths); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.GenerateEventPaths(eventPathListBuilder, eventPaths), CHIP_NO_ERROR); request.IsFabricFiltered(false).EndOfReadRequestMessage(); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == request.GetError()); + EXPECT_EQ(CHIP_NO_ERROR, request.GetError()); - err = writer.Finalize(&msgBuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); chip::System::PacketBufferTLVReader reader; ReadRequestMessage::Parser readRequestParser; reader.Init(msgBuf.Retain()); - err = readRequestParser.Init(reader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readRequestParser.Init(reader), CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT readRequestParser.PrettyPrint(); #endif - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestReadClientGenerateTwoEventPaths(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateTwoEventPaths) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); MockInteractionModelApp delegate; System::PacketBufferHandle msgBuf; System::PacketBufferTLVWriter writer; ReadRequestMessage::Builder request; msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); writer.Init(std::move(msgBuf)); - err = request.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(request.Init(&writer), CHIP_NO_ERROR); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); chip::app::EventPathParams eventPathParams[2]; @@ -835,45 +738,40 @@ void TestReadInteraction::TestReadClientGenerateTwoEventPaths(nlTestSuite * apSu EventPathIBs::Builder & eventPathListBuilder = request.CreateEventRequests(); Span eventPaths(eventPathParams, 2 /*aEventPathParamsListSize*/); - err = readClient.GenerateEventPaths(eventPathListBuilder, eventPaths); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.GenerateEventPaths(eventPathListBuilder, eventPaths), CHIP_NO_ERROR); request.IsFabricFiltered(false).EndOfReadRequestMessage(); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == request.GetError()); + EXPECT_EQ(CHIP_NO_ERROR, request.GetError()); - err = writer.Finalize(&msgBuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); chip::System::PacketBufferTLVReader reader; ReadRequestMessage::Parser readRequestParser; reader.Init(msgBuf.Retain()); - err = readRequestParser.Init(reader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readRequestParser.Init(reader), CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT readRequestParser.PrettyPrint(); #endif - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestReadRoundtrip(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestReadRoundtrip) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); chip::app::EventPathParams eventPathParams[1]; eventPathParams[0].mEndpointId = kTestEventEndpointId; @@ -889,7 +787,7 @@ void TestReadInteraction::TestReadRoundtrip(nlTestSuite * apSuite, void * apCont attributePathParams[1].mAttributeId = 2; attributePathParams[1].mListIndex = 1; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mEventPathParamsListSize = 1; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -897,19 +795,18 @@ void TestReadInteraction::TestReadRoundtrip(nlTestSuite * apSuite, void * apCont readPrepareParams.mEventNumber.SetValue(1); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mNumDataElementIndex == 1); - NL_TEST_ASSERT(apSuite, delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 2); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, !delegate.mReadError); + EXPECT_EQ(delegate.mNumDataElementIndex, 1); + EXPECT_TRUE(delegate.mGotEventResponse); + EXPECT_EQ(delegate.mNumAttributeResponse, 2); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_FALSE(delegate.mReadError); delegate.mGotEventResponse = false; delegate.mNumAttributeResponse = 0; @@ -917,45 +814,42 @@ void TestReadInteraction::TestReadRoundtrip(nlTestSuite * apSuite, void * apCont } { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 2); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, !delegate.mReadError); + EXPECT_TRUE(delegate.mGotEventResponse); + EXPECT_EQ(delegate.mNumAttributeResponse, 2); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_FALSE(delegate.mReadError); // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestReadRoundtripWithDataVersionFilter(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestReadRoundtripWithDataVersionFilter) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[2]; attributePathParams[0].mEndpointId = kTestEndpointId; @@ -972,45 +866,42 @@ void TestReadInteraction::TestReadRoundtripWithDataVersionFilter(nlTestSuite * a dataVersionFilters[0].mClusterId = kTestClusterId; dataVersionFilters[0].mDataVersion.SetValue(kTestDataVersion1); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; readPrepareParams.mpDataVersionFilterList = dataVersionFilters; readPrepareParams.mDataVersionFilterListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 0); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(delegate.mNumAttributeResponse, 0); delegate.mNumAttributeResponse = 0; } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestReadRoundtripWithNoMatchPathDataVersionFilter(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestReadRoundtripWithNoMatchPathDataVersionFilter) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); chip::app::AttributePathParams attributePathParams[2]; attributePathParams[0].mEndpointId = kTestEndpointId; @@ -1031,47 +922,44 @@ void TestReadInteraction::TestReadRoundtripWithNoMatchPathDataVersionFilter(nlTe dataVersionFilters[1].mClusterId = kTestClusterId; dataVersionFilters[1].mDataVersion.SetValue(kTestDataVersion2); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; readPrepareParams.mpDataVersionFilterList = dataVersionFilters; readPrepareParams.mDataVersionFilterListSize = 2; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 2); - NL_TEST_ASSERT(apSuite, !delegate.mReadError); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(delegate.mNumAttributeResponse, 2); + EXPECT_FALSE(delegate.mReadError); delegate.mNumAttributeResponse = 0; } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestReadRoundtripWithMultiSamePathDifferentDataVersionFilter(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestReadRoundtripWithMultiSamePathDifferentDataVersionFilter) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[2]; attributePathParams[0].mEndpointId = kTestEndpointId; @@ -1092,47 +980,44 @@ void TestReadInteraction::TestReadRoundtripWithMultiSamePathDifferentDataVersion dataVersionFilters[1].mClusterId = kTestClusterId; dataVersionFilters[1].mDataVersion.SetValue(kTestDataVersion2); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; readPrepareParams.mpDataVersionFilterList = dataVersionFilters; readPrepareParams.mDataVersionFilterListSize = 2; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 2); - NL_TEST_ASSERT(apSuite, !delegate.mReadError); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(delegate.mNumAttributeResponse, 2); + EXPECT_FALSE(delegate.mReadError); delegate.mNumAttributeResponse = 0; } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestReadRoundtripWithSameDifferentPathsDataVersionFilter(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestReadRoundtripWithSameDifferentPathsDataVersionFilter) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[2]; attributePathParams[0].mEndpointId = kTestEndpointId; @@ -1153,53 +1038,50 @@ void TestReadInteraction::TestReadRoundtripWithSameDifferentPathsDataVersionFilt dataVersionFilters[1].mClusterId = kTestClusterId; dataVersionFilters[1].mDataVersion.SetValue(kTestDataVersion2); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; readPrepareParams.mpDataVersionFilterList = dataVersionFilters; readPrepareParams.mDataVersionFilterListSize = 2; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 0); - NL_TEST_ASSERT(apSuite, !delegate.mReadError); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(delegate.mNumAttributeResponse, 0); + EXPECT_FALSE(delegate.mReadError); delegate.mNumAttributeResponse = 0; } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestReadWildcard(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestReadWildcard) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[1]; - attributePathParams[0].mEndpointId = Test::kMockEndpoint2; - attributePathParams[0].mClusterId = Test::MockClusterId(3); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint2; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(3); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -1207,107 +1089,101 @@ void TestReadInteraction::TestReadWildcard(nlTestSuite * apSuite, void * apConte { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 5); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, !delegate.mReadError); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(delegate.mNumAttributeResponse, 5); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_FALSE(delegate.mReadError); // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } // TestReadChunking will try to read a few large attributes, the report won't fit into the MTU and result in chunking. -void TestReadInteraction::TestReadChunking(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestReadChunking) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[1]; // Mock Attribute 4 is a big attribute, with kMockAttribute4ListLength large // OCTET_STRING elements. - attributePathParams[0].mEndpointId = Test::kMockEndpoint3; - attributePathParams[0].mClusterId = Test::MockClusterId(2); - attributePathParams[0].mAttributeId = Test::MockAttributeId(4); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // We get one chunk with 4 array elements, and then one chunk per // element, and the total size of the array is // kMockAttribute4ListLength. - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 1 + (kMockAttribute4ListLength - 4)); - NL_TEST_ASSERT(apSuite, delegate.mNumArrayItems == 6); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, !delegate.mReadError); + EXPECT_EQ(delegate.mNumAttributeResponse, 1 + (kMockAttribute4ListLength - 4)); + EXPECT_EQ(delegate.mNumArrayItems, 6); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_FALSE(delegate.mReadError); // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestSetDirtyBetweenChunks(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestSetDirtyBetweenChunks) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); chip::app::AttributePathParams attributePathParams[2]; for (auto & attributePathParam : attributePathParams) { - attributePathParam.mEndpointId = Test::kMockEndpoint3; - attributePathParam.mClusterId = Test::MockClusterId(2); - attributePathParam.mAttributeId = Test::MockAttributeId(4); + attributePathParam.mEndpointId = chip::Test::kMockEndpoint3; + attributePathParam.mClusterId = chip::Test::MockClusterId(2); + attributePathParam.mAttributeId = chip::Test::MockAttributeId(4); } - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -1377,9 +1253,9 @@ void TestReadInteraction::TestSetDirtyBetweenChunks(nlTestSuite * apSuite, void mDidSetDirty = true; AttributePathParams dirtyPath; - dirtyPath.mEndpointId = Test::kMockEndpoint3; - dirtyPath.mClusterId = Test::MockClusterId(2); - dirtyPath.mAttributeId = Test::MockAttributeId(4); + dirtyPath.mEndpointId = chip::Test::kMockEndpoint3; + dirtyPath.mClusterId = chip::Test::MockClusterId(2); + dirtyPath.mAttributeId = chip::Test::MockAttributeId(4); if (aPath.mEndpointId == dirtyPath.mEndpointId && aPath.mClusterId == dirtyPath.mClusterId && aPath.mAttributeId == dirtyPath.mAttributeId) @@ -1405,15 +1281,14 @@ void TestReadInteraction::TestSetDirtyBetweenChunks(nlTestSuite * apSuite, void }; DirtyingMockDelegate delegate(attributePathParams, currentAttributeResponsesWhenSetDirty, currentArrayItemsWhenSetDirty); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_FALSE(delegate.mGotEventResponse); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // Our list has length kMockAttribute4ListLength. Since the underlying // path iterator should be reset to the beginning of the cluster it is @@ -1423,122 +1298,112 @@ void TestReadInteraction::TestSetDirtyBetweenChunks(nlTestSuite * apSuite, void const int expectedIBs = 1 + (kMockAttribute4ListLength - 4); ChipLogError(DataManagement, "OLD: %d\n", currentAttributeResponsesWhenSetDirty); ChipLogError(DataManagement, "NEW: %d\n", delegate.mNumAttributeResponse); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == currentAttributeResponsesWhenSetDirty + expectedIBs); - NL_TEST_ASSERT(apSuite, delegate.mNumArrayItems == currentArrayItemsWhenSetDirty + kMockAttribute4ListLength); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, !delegate.mReadError); + EXPECT_EQ(delegate.mNumAttributeResponse, currentAttributeResponsesWhenSetDirty + expectedIBs); + EXPECT_EQ(delegate.mNumArrayItems, currentArrayItemsWhenSetDirty + kMockAttribute4ListLength); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_FALSE(delegate.mReadError); // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestReadInvalidAttributePathRoundtrip(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestReadInvalidAttributePathRoundtrip) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[2]; attributePathParams[0].mEndpointId = kTestEndpointId; attributePathParams[0].mClusterId = kInvalidTestClusterId; attributePathParams[0].mAttributeId = 1; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 0); + EXPECT_EQ(delegate.mNumAttributeResponse, 0); // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); } engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestProcessSubscribeRequest(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestProcessSubscribeRequest) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); System::PacketBufferTLVWriter writer; System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); SubscribeRequestMessage::Builder subscribeRequestBuilder; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); { ReadHandler readHandler(*engine, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); writer.Init(std::move(subscribeRequestbuf)); - err = subscribeRequestBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.Init(&writer), CHIP_NO_ERROR); subscribeRequestBuilder.KeepSubscriptions(true); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.MinIntervalFloorSeconds(2); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.MaxIntervalCeilingSeconds(3); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); AttributePathIBs::Builder & attributePathListBuilder = subscribeRequestBuilder.CreateAttributeRequests(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); AttributePathIB::Builder & attributePathBuilder = attributePathListBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); attributePathBuilder.Node(1).Endpoint(2).Cluster(3).Attribute(4).ListIndex(5).EndOfAttributePathIB(); - err = attributePathBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder.GetError(), CHIP_NO_ERROR); attributePathListBuilder.EndOfAttributePathIBs(); - err = attributePathListBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.IsFabricFiltered(false).EndOfSubscribeRequestMessage(); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); - err = writer.Finalize(&subscribeRequestbuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&subscribeRequestbuf), CHIP_NO_ERROR); - err = readHandler.ProcessSubscribeRequest(std::move(subscribeRequestbuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readHandler.ProcessSubscribeRequest(std::move(subscribeRequestbuf)), CHIP_NO_ERROR); } engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } #if CHIP_CONFIG_ENABLE_ICD_SERVER @@ -1546,61 +1411,54 @@ void TestReadInteraction::TestProcessSubscribeRequest(nlTestSuite * apSuite, voi * @brief Test validates that an ICD will choose its IdleModeDuration (GetPublisherSelectedIntervalLimit) * as MaxInterval when the MaxIntervalCeiling is superior. */ -void TestReadInteraction::TestICDProcessSubscribeRequestSupMaxIntervalCeiling(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestSupMaxIntervalCeiling) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); System::PacketBufferTLVWriter writer; System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); SubscribeRequestMessage::Builder subscribeRequestBuilder; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); uint16_t kMinInterval = 0; uint16_t kMaxIntervalCeiling = 1; - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); { ReadHandler readHandler(*engine, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); writer.Init(std::move(subscribeRequestbuf)); - err = subscribeRequestBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.Init(&writer), CHIP_NO_ERROR); subscribeRequestBuilder.KeepSubscriptions(true); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.MinIntervalFloorSeconds(kMinInterval); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.MaxIntervalCeilingSeconds(kMaxIntervalCeiling); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); AttributePathIBs::Builder & attributePathListBuilder = subscribeRequestBuilder.CreateAttributeRequests(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); AttributePathIB::Builder & attributePathBuilder = attributePathListBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); attributePathBuilder.Node(1).Endpoint(2).Cluster(3).Attribute(4).ListIndex(5).EndOfAttributePathIB(); - err = attributePathBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder.GetError(), CHIP_NO_ERROR); attributePathListBuilder.EndOfAttributePathIBs(); - err = attributePathListBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.IsFabricFiltered(false).EndOfSubscribeRequestMessage(); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); - err = writer.Finalize(&subscribeRequestbuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&subscribeRequestbuf), CHIP_NO_ERROR); - err = readHandler.ProcessSubscribeRequest(std::move(subscribeRequestbuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readHandler.ProcessSubscribeRequest(std::move(subscribeRequestbuf)), CHIP_NO_ERROR); uint16_t idleModeDuration = readHandler.GetPublisherSelectedIntervalLimit(); @@ -1608,73 +1466,66 @@ void TestReadInteraction::TestICDProcessSubscribeRequestSupMaxIntervalCeiling(nl uint16_t maxInterval; readHandler.GetReportingIntervals(minInterval, maxInterval); - NL_TEST_ASSERT(apSuite, minInterval == kMinInterval); - NL_TEST_ASSERT(apSuite, maxInterval == idleModeDuration); + EXPECT_EQ(minInterval, kMinInterval); + EXPECT_EQ(maxInterval, idleModeDuration); } engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } /** * @brief Test validates that an ICD will choose its IdleModeDuration (GetPublisherSelectedIntervalLimit) * as MaxInterval when the MaxIntervalCeiling is inferior. */ -void TestReadInteraction::TestICDProcessSubscribeRequestInfMaxIntervalCeiling(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestInfMaxIntervalCeiling) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); System::PacketBufferTLVWriter writer; System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); SubscribeRequestMessage::Builder subscribeRequestBuilder; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); uint16_t kMinInterval = 0; uint16_t kMaxIntervalCeiling = 1; - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); { ReadHandler readHandler(*engine, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); writer.Init(std::move(subscribeRequestbuf)); - err = subscribeRequestBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.Init(&writer), CHIP_NO_ERROR); subscribeRequestBuilder.KeepSubscriptions(true); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.MinIntervalFloorSeconds(kMinInterval); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.MaxIntervalCeilingSeconds(kMaxIntervalCeiling); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); AttributePathIBs::Builder & attributePathListBuilder = subscribeRequestBuilder.CreateAttributeRequests(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); AttributePathIB::Builder & attributePathBuilder = attributePathListBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); attributePathBuilder.Node(1).Endpoint(2).Cluster(3).Attribute(4).ListIndex(5).EndOfAttributePathIB(); - err = attributePathBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder.GetError(), CHIP_NO_ERROR); attributePathListBuilder.EndOfAttributePathIBs(); - err = attributePathListBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.IsFabricFiltered(false).EndOfSubscribeRequestMessage(); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); - err = writer.Finalize(&subscribeRequestbuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&subscribeRequestbuf), CHIP_NO_ERROR); - err = readHandler.ProcessSubscribeRequest(std::move(subscribeRequestbuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readHandler.ProcessSubscribeRequest(std::move(subscribeRequestbuf)), CHIP_NO_ERROR); uint16_t idleModeDuration = readHandler.GetPublisherSelectedIntervalLimit(); @@ -1682,73 +1533,66 @@ void TestReadInteraction::TestICDProcessSubscribeRequestInfMaxIntervalCeiling(nl uint16_t maxInterval; readHandler.GetReportingIntervals(minInterval, maxInterval); - NL_TEST_ASSERT(apSuite, minInterval == kMinInterval); - NL_TEST_ASSERT(apSuite, maxInterval == idleModeDuration); + EXPECT_EQ(minInterval, kMinInterval); + EXPECT_EQ(maxInterval, idleModeDuration); } engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } /** * @brief Test validates that an ICD will choose a multiple of its IdleModeDuration (GetPublisherSelectedIntervalLimit) * as MaxInterval when the MinInterval > IdleModeDuration. */ -void TestReadInteraction::TestICDProcessSubscribeRequestSupMinInterval(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestSupMinInterval) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); System::PacketBufferTLVWriter writer; System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); SubscribeRequestMessage::Builder subscribeRequestBuilder; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); uint16_t kMinInterval = 305; // Default IdleModeDuration is 300 uint16_t kMaxIntervalCeiling = 605; - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); { ReadHandler readHandler(*engine, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); writer.Init(std::move(subscribeRequestbuf)); - err = subscribeRequestBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.Init(&writer), CHIP_NO_ERROR); subscribeRequestBuilder.KeepSubscriptions(true); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.MinIntervalFloorSeconds(kMinInterval); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.MaxIntervalCeilingSeconds(kMaxIntervalCeiling); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); AttributePathIBs::Builder & attributePathListBuilder = subscribeRequestBuilder.CreateAttributeRequests(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); AttributePathIB::Builder & attributePathBuilder = attributePathListBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); attributePathBuilder.Node(1).Endpoint(2).Cluster(3).Attribute(4).ListIndex(5).EndOfAttributePathIB(); - err = attributePathBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder.GetError(), CHIP_NO_ERROR); attributePathListBuilder.EndOfAttributePathIBs(); - err = attributePathListBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.IsFabricFiltered(false).EndOfSubscribeRequestMessage(); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); - err = writer.Finalize(&subscribeRequestbuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&subscribeRequestbuf), CHIP_NO_ERROR); - err = readHandler.ProcessSubscribeRequest(std::move(subscribeRequestbuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readHandler.ProcessSubscribeRequest(std::move(subscribeRequestbuf)), CHIP_NO_ERROR); uint16_t idleModeDuration = readHandler.GetPublisherSelectedIntervalLimit(); @@ -1756,176 +1600,161 @@ void TestReadInteraction::TestICDProcessSubscribeRequestSupMinInterval(nlTestSui uint16_t maxInterval; readHandler.GetReportingIntervals(minInterval, maxInterval); - NL_TEST_ASSERT(apSuite, minInterval == kMinInterval); - NL_TEST_ASSERT(apSuite, maxInterval == (2 * idleModeDuration)); + EXPECT_EQ(minInterval, kMinInterval); + EXPECT_EQ(maxInterval, (2 * idleModeDuration)); } engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } /** * @brief Test validates that an ICD will choose a maximal value for an uint16 if the multiple of the IdleModeDuration * is greater than variable size. */ -void TestReadInteraction::TestICDProcessSubscribeRequestMaxMinInterval(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestMaxMinInterval) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); System::PacketBufferTLVWriter writer; System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); SubscribeRequestMessage::Builder subscribeRequestBuilder; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); uint16_t kMinInterval = System::Clock::Seconds16::max().count(); uint16_t kMaxIntervalCeiling = System::Clock::Seconds16::max().count(); - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); { ReadHandler readHandler(*engine, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); writer.Init(std::move(subscribeRequestbuf)); - err = subscribeRequestBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.Init(&writer), CHIP_NO_ERROR); subscribeRequestBuilder.KeepSubscriptions(true); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.MinIntervalFloorSeconds(kMinInterval); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.MaxIntervalCeilingSeconds(kMaxIntervalCeiling); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); AttributePathIBs::Builder & attributePathListBuilder = subscribeRequestBuilder.CreateAttributeRequests(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); AttributePathIB::Builder & attributePathBuilder = attributePathListBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); attributePathBuilder.Node(1).Endpoint(2).Cluster(3).Attribute(4).ListIndex(5).EndOfAttributePathIB(); - err = attributePathBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder.GetError(), CHIP_NO_ERROR); attributePathListBuilder.EndOfAttributePathIBs(); - err = attributePathListBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.IsFabricFiltered(false).EndOfSubscribeRequestMessage(); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); - err = writer.Finalize(&subscribeRequestbuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&subscribeRequestbuf), CHIP_NO_ERROR); - err = readHandler.ProcessSubscribeRequest(std::move(subscribeRequestbuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readHandler.ProcessSubscribeRequest(std::move(subscribeRequestbuf)), CHIP_NO_ERROR); uint16_t minInterval; uint16_t maxInterval; readHandler.GetReportingIntervals(minInterval, maxInterval); - NL_TEST_ASSERT(apSuite, minInterval == kMinInterval); - NL_TEST_ASSERT(apSuite, maxInterval == kMaxIntervalCeiling); + EXPECT_EQ(minInterval, kMinInterval); + EXPECT_EQ(maxInterval, kMaxIntervalCeiling); } engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } /** * @brief Test validates that an ICD will choose the MaxIntervalCeiling as MaxInterval if the next multiple after the MinInterval * is greater than the IdleModeDuration and MaxIntervalCeiling */ -void TestReadInteraction::TestICDProcessSubscribeRequestInvalidIdleModeDuration(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestInvalidIdleModeDuration) { - CHIP_ERROR err = CHIP_NO_ERROR; - TestContext & ctx = *static_cast(apContext); System::PacketBufferTLVWriter writer; System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); SubscribeRequestMessage::Builder subscribeRequestBuilder; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); uint16_t kMinInterval = 400; uint16_t kMaxIntervalCeiling = 400; - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); { ReadHandler readHandler(*engine, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); writer.Init(std::move(subscribeRequestbuf)); - err = subscribeRequestBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.Init(&writer), CHIP_NO_ERROR); subscribeRequestBuilder.KeepSubscriptions(true); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.MinIntervalFloorSeconds(kMinInterval); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.MaxIntervalCeilingSeconds(kMaxIntervalCeiling); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); AttributePathIBs::Builder & attributePathListBuilder = subscribeRequestBuilder.CreateAttributeRequests(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); AttributePathIB::Builder & attributePathBuilder = attributePathListBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); attributePathBuilder.Node(1).Endpoint(2).Cluster(3).Attribute(4).ListIndex(5).EndOfAttributePathIB(); - err = attributePathBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder.GetError(), CHIP_NO_ERROR); attributePathListBuilder.EndOfAttributePathIBs(); - err = attributePathListBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); subscribeRequestBuilder.IsFabricFiltered(false).EndOfSubscribeRequestMessage(); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); - err = writer.Finalize(&subscribeRequestbuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&subscribeRequestbuf), CHIP_NO_ERROR); - err = readHandler.ProcessSubscribeRequest(std::move(subscribeRequestbuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readHandler.ProcessSubscribeRequest(std::move(subscribeRequestbuf)), CHIP_NO_ERROR); uint16_t minInterval; uint16_t maxInterval; readHandler.GetReportingIntervals(minInterval, maxInterval); - NL_TEST_ASSERT(apSuite, minInterval == kMinInterval); - NL_TEST_ASSERT(apSuite, maxInterval == kMaxIntervalCeiling); + EXPECT_EQ(minInterval, kMinInterval); + EXPECT_EQ(maxInterval, kMaxIntervalCeiling); } engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } #endif // CHIP_CONFIG_ENABLE_ICD_SERVER -void TestReadInteraction::TestSubscribeRoundtrip(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); + + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -1955,38 +1784,36 @@ void TestReadInteraction::TestSubscribeRoundtrip(nlTestSuite * apSuite, void * a printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); + EXPECT_TRUE(delegate.mGotReport); } delegate.mNumAttributeResponse = 0; readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 2); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(delegate.mNumAttributeResponse, 2); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); - GenerateEvents(apSuite, apContext); + GenerateEvents(); chip::app::AttributePathParams dirtyPath1; dirtyPath1.mClusterId = kTestClusterId; dirtyPath1.mEndpointId = kTestEndpointId; @@ -2017,79 +1844,69 @@ void TestReadInteraction::TestSubscribeRoundtrip(nlTestSuite * apSuite, void * a // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); delegate.mGotReport = false; delegate.mGotEventResponse = false; delegate.mNumAttributeResponse = 0; - err = engine->GetReportingEngine().SetDirty(dirtyPath1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = engine->GetReportingEngine().SetDirty(dirtyPath2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath1), CHIP_NO_ERROR); + + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath2), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mGotEventResponse == true); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 2); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_TRUE(delegate.mGotEventResponse); + EXPECT_EQ(delegate.mNumAttributeResponse, 2); // Test report with 2 different path, and 1 same path // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; - err = engine->GetReportingEngine().SetDirty(dirtyPath1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = engine->GetReportingEngine().SetDirty(dirtyPath2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = engine->GetReportingEngine().SetDirty(dirtyPath2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath1), CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath2), CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath2), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 2); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(delegate.mNumAttributeResponse, 2); // Test report with 3 different path, and one path is overlapped with another // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; - err = engine->GetReportingEngine().SetDirty(dirtyPath1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = engine->GetReportingEngine().SetDirty(dirtyPath2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = engine->GetReportingEngine().SetDirty(dirtyPath3); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath1), CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath2), CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath3), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 2); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(delegate.mNumAttributeResponse, 2); // Test report with 3 different path, all are not overlapped, one path is not interested for current subscription // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; - err = engine->GetReportingEngine().SetDirty(dirtyPath1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = engine->GetReportingEngine().SetDirty(dirtyPath2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = engine->GetReportingEngine().SetDirty(dirtyPath4); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath1), CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath2), CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath4), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 2); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(delegate.mNumAttributeResponse, 2); uint16_t minInterval; uint16_t maxInterval; @@ -2098,42 +1915,40 @@ void TestReadInteraction::TestSubscribeRoundtrip(nlTestSuite * apSuite, void * a // Test empty report // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(maxInterval)); - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().IsRunScheduled()); + EXPECT_TRUE(engine->GetReportingEngine().IsRunScheduled()); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 0); + EXPECT_EQ(delegate.mNumAttributeResponse, 0); } // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestSubscribeEarlyReport(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeEarlyReport) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[1]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -2150,165 +1965,153 @@ void TestReadInteraction::TestSubscribeEarlyReport(nlTestSuite * apSuite, void * readPrepareParams.mKeepSubscriptions = true; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); readPrepareParams.mpEventPathParamsList[0].mIsUrgentEvent = true; delegate.mGotEventResponse = false; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); System::Clock::Timestamp startTime = gMockClock.GetMonotonicTimestamp(); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); uint16_t minInterval; uint16_t maxInterval; delegate.mpReadHandler->GetReportingIntervals(minInterval, maxInterval); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler) == - gMockClock.GetMonotonicTimestamp() + Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMaxTimestampForHandler(delegate.mpReadHandler) == - gMockClock.GetMonotonicTimestamp() + Seconds16(maxInterval)); + EXPECT_EQ(gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler), + gMockClock.GetMonotonicTimestamp() + Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); + EXPECT_EQ(gReportScheduler->GetMaxTimestampForHandler(delegate.mpReadHandler), + gMockClock.GetMonotonicTimestamp() + Seconds16(maxInterval)); // Confirm that the node is scheduled to run - NL_TEST_ASSERT(apSuite, gReportScheduler->IsReportScheduled(delegate.mpReadHandler)); + EXPECT_TRUE(gReportScheduler->IsReportScheduled(delegate.mpReadHandler)); ReportScheduler::ReadHandlerNode * node = gReportScheduler->GetReadHandlerNode(delegate.mpReadHandler); - NL_TEST_ASSERT(apSuite, node != nullptr); + ASSERT_NE(node, nullptr); - GenerateEvents(apSuite, apContext); + GenerateEvents(); // modify the node's min timestamp to be 50ms later than the timer expiration time node->SetIntervalTimeStamps(delegate.mpReadHandler, startTime + Milliseconds32(50)); - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler) == - gMockClock.GetMonotonicTimestamp() + Seconds16(readPrepareParams.mMinIntervalFloorSeconds) + - Milliseconds32(50)); + EXPECT_EQ(gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler), + gMockClock.GetMonotonicTimestamp() + Seconds16(readPrepareParams.mMinIntervalFloorSeconds) + Milliseconds32(50)); - NL_TEST_ASSERT(apSuite, gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler) > startTime); - NL_TEST_ASSERT(apSuite, delegate.mpReadHandler->IsDirty()); + EXPECT_GT(gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler), startTime); + EXPECT_TRUE(delegate.mpReadHandler->IsDirty()); delegate.mGotEventResponse = false; // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); - NL_TEST_ASSERT(apSuite, !InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); + EXPECT_FALSE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); // Service Timer expired event - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler) > gMockClock.GetMonotonicTimestamp()); + EXPECT_GT(gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler), gMockClock.GetMonotonicTimestamp()); // The behavior on min interval elapse is different between synced subscription and non-synced subscription if (!sUsingSubSync) { // Verify the ReadHandler is considered as reportable even if its node's min timestamp has not expired - NL_TEST_ASSERT(apSuite, gReportScheduler->IsReportableNow(delegate.mpReadHandler)); - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); + EXPECT_TRUE(gReportScheduler->IsReportableNow(delegate.mpReadHandler)); + EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); // Service Engine Run - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); // Service EventManagement event - ctx.GetIOContext().DriveIO(); - ctx.GetIOContext().DriveIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotEventResponse); + mpTestContext->GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); + EXPECT_TRUE(delegate.mGotEventResponse); } else { // Verify logic on Min for synced subscription // Verify the ReadHandler is not considered as reportable yet - NL_TEST_ASSERT(apSuite, !gReportScheduler->IsReportableNow(delegate.mpReadHandler)); + EXPECT_FALSE(gReportScheduler->IsReportableNow(delegate.mpReadHandler)); // confirm that the timer was kicked off for the next min of the node - NL_TEST_ASSERT(apSuite, gReportScheduler->IsReportScheduled(delegate.mpReadHandler)); + EXPECT_TRUE(gReportScheduler->IsReportScheduled(delegate.mpReadHandler)); // Expired new timer gMockClock.AdvanceMonotonic(Milliseconds32(50)); // Service Timer expired event - ctx.GetIOContext().DriveIO(); - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); + mpTestContext->GetIOContext().DriveIO(); + EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); // Service Engine Run - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); // Service EventManagement event - ctx.GetIOContext().DriveIO(); - ctx.GetIOContext().DriveIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotEventResponse); + mpTestContext->GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); + EXPECT_TRUE(delegate.mGotEventResponse); } // The behavior is identical on max since the sync subscription will interpret an early max firing as a earlier node got // reportable and allow nodes that have passed their min to sync on it. - NL_TEST_ASSERT(apSuite, !delegate.mpReadHandler->IsDirty()); + EXPECT_FALSE(delegate.mpReadHandler->IsDirty()); delegate.mGotEventResponse = false; - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler) == - gMockClock.GetMonotonicTimestamp() + Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMaxTimestampForHandler(delegate.mpReadHandler) == - gMockClock.GetMonotonicTimestamp() + Seconds16(maxInterval)); + EXPECT_EQ(gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler), + gMockClock.GetMonotonicTimestamp() + Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); + EXPECT_EQ(gReportScheduler->GetMaxTimestampForHandler(delegate.mpReadHandler), + gMockClock.GetMonotonicTimestamp() + Seconds16(maxInterval)); // Confirm that the node is scheduled to run - NL_TEST_ASSERT(apSuite, gReportScheduler->IsReportScheduled(delegate.mpReadHandler)); - NL_TEST_ASSERT(apSuite, node != nullptr); + EXPECT_TRUE(gReportScheduler->IsReportScheduled(delegate.mpReadHandler)); + ASSERT_NE(node, nullptr); // modify the node's max timestamp to be 50ms later than the timer expiration time node->SetIntervalTimeStamps(delegate.mpReadHandler, gMockClock.GetMonotonicTimestamp() + Milliseconds32(50)); - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMaxTimestampForHandler(delegate.mpReadHandler) == - gMockClock.GetMonotonicTimestamp() + Seconds16(maxInterval) + Milliseconds32(50)); + EXPECT_EQ(gReportScheduler->GetMaxTimestampForHandler(delegate.mpReadHandler), + gMockClock.GetMonotonicTimestamp() + Seconds16(maxInterval) + Milliseconds32(50)); // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(Seconds16(maxInterval)); - NL_TEST_ASSERT(apSuite, !InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); + EXPECT_FALSE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); // Service Timer expired event - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); // Verify the ReadHandler is considered as reportable even if its node's min timestamp has not expired - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMaxTimestampForHandler(delegate.mpReadHandler) > gMockClock.GetMonotonicTimestamp()); - NL_TEST_ASSERT(apSuite, gReportScheduler->IsReportableNow(delegate.mpReadHandler)); - NL_TEST_ASSERT(apSuite, !gReportScheduler->IsReportScheduled(delegate.mpReadHandler)); - NL_TEST_ASSERT(apSuite, !delegate.mpReadHandler->IsDirty()); - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); + EXPECT_GT(gReportScheduler->GetMaxTimestampForHandler(delegate.mpReadHandler), gMockClock.GetMonotonicTimestamp()); + EXPECT_TRUE(gReportScheduler->IsReportableNow(delegate.mpReadHandler)); + EXPECT_FALSE(gReportScheduler->IsReportScheduled(delegate.mpReadHandler)); + EXPECT_FALSE(delegate.mpReadHandler->IsDirty()); + EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); // Service Engine Run - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); // Service EventManagement event - ctx.GetIOContext().DriveIO(); - ctx.GetIOContext().DriveIO(); - NL_TEST_ASSERT(apSuite, gReportScheduler->IsReportScheduled(delegate.mpReadHandler)); - NL_TEST_ASSERT(apSuite, !InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); + mpTestContext->GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); + EXPECT_TRUE(gReportScheduler->IsReportScheduled(delegate.mpReadHandler)); + EXPECT_FALSE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); } - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestSubscribeUrgentWildcardEvent(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeUrgentWildcardEvent) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; MockInteractionModelApp nonUrgentDelegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); + EXPECT_FALSE(nonUrgentDelegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -2331,39 +2134,39 @@ void TestReadInteraction::TestSubscribeUrgentWildcardEvent(nlTestSuite * apSuite readPrepareParams.mKeepSubscriptions = true; { - app::ReadClient nonUrgentReadClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), + app::ReadClient nonUrgentReadClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), nonUrgentDelegate, chip::app::ReadClient::InteractionType::Subscribe); nonUrgentDelegate.mGotReport = false; - err = nonUrgentReadClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(nonUrgentReadClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); readPrepareParams.mpEventPathParamsList[0].mIsUrgentEvent = true; delegate.mGotReport = false; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); System::Clock::Timestamp startTime = gMockClock.GetMonotonicTimestamp(); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 2); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 2u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); nonUrgentDelegate.mpReadHandler = engine->ActiveHandlerAt(0); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(1) != nullptr); + ASSERT_NE(engine->ActiveHandlerAt(1), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 2); + // Adding These to be able to access private members/methods of ReadHandler - GenerateEvents(apSuite, apContext); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 2u); - NL_TEST_ASSERT(apSuite, gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler) > startTime); - NL_TEST_ASSERT(apSuite, delegate.mpReadHandler->IsDirty()); + GenerateEvents(); + + EXPECT_GT(gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler), startTime); + EXPECT_TRUE(delegate.mpReadHandler->IsDirty()); delegate.mGotEventResponse = false; delegate.mGotReport = false; - NL_TEST_ASSERT(apSuite, gReportScheduler->GetMinTimestampForHandler(nonUrgentDelegate.mpReadHandler) > startTime); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mpReadHandler->IsDirty()); + EXPECT_GT(gReportScheduler->GetMinTimestampForHandler(nonUrgentDelegate.mpReadHandler), startTime); + EXPECT_FALSE(nonUrgentDelegate.mpReadHandler->IsDirty()); nonUrgentDelegate.mGotEventResponse = false; nonUrgentDelegate.mGotReport = false; @@ -2375,194 +2178,185 @@ void TestReadInteraction::TestSubscribeUrgentWildcardEvent(nlTestSuite * apSuite // Advance monotonic looping to allow events to trigger gMockClock.AdvanceMonotonic(System::Clock::Milliseconds32(600)); - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mGotEventResponse); + EXPECT_FALSE(delegate.mGotEventResponse); + EXPECT_FALSE(nonUrgentDelegate.mGotEventResponse); // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Milliseconds32(800)); // Service Timer expired event - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); // Service Engine Run - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); // Service EventManagement event - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotEventResponse); + EXPECT_TRUE(delegate.mGotEventResponse); // The logic differs here depending on what Scheduler is implemented if (!sUsingSubSync) { - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mGotEventResponse); + EXPECT_FALSE(nonUrgentDelegate.mGotEventResponse); // Since we just sent a report for our urgent subscription, the min interval of the urgent subcription should have been // updated - NL_TEST_ASSERT( - apSuite, gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler) > gMockClock.GetMonotonicTimestamp()); - NL_TEST_ASSERT(apSuite, !delegate.mpReadHandler->IsDirty()); + EXPECT_GT(gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler), gMockClock.GetMonotonicTimestamp()); + + EXPECT_FALSE(delegate.mpReadHandler->IsDirty()); delegate.mGotEventResponse = false; // For our non-urgent subscription, we did not send anything, so the min interval should of the non urgent subcription // should be in the past - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMinTimestampForHandler(nonUrgentDelegate.mpReadHandler) < - gMockClock.GetMonotonicTimestamp()); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mpReadHandler->IsDirty()); + EXPECT_LT(gReportScheduler->GetMinTimestampForHandler(nonUrgentDelegate.mpReadHandler), + gMockClock.GetMonotonicTimestamp()); + EXPECT_FALSE(nonUrgentDelegate.mpReadHandler->IsDirty()); // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Milliseconds32(2100)); - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); // No reporting should have happened. - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mGotEventResponse); + EXPECT_FALSE(delegate.mGotEventResponse); + EXPECT_FALSE(nonUrgentDelegate.mGotEventResponse); // The min-interval should have elapsed for the urgent subscription, and our handler should still // not be dirty or reportable. - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler) < - System::SystemClock().GetMonotonicTimestamp()); - NL_TEST_ASSERT(apSuite, !delegate.mpReadHandler->IsDirty()); - NL_TEST_ASSERT(apSuite, !delegate.mpReadHandler->ShouldStartReporting()); + EXPECT_LT(gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler), + System::SystemClock().GetMonotonicTimestamp()); + EXPECT_FALSE(delegate.mpReadHandler->IsDirty()); + EXPECT_FALSE(delegate.mpReadHandler->ShouldStartReporting()); // And the non-urgent one should not have changed state either, since // it's waiting for the max-interval. - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMinTimestampForHandler(nonUrgentDelegate.mpReadHandler) < - System::SystemClock().GetMonotonicTimestamp()); - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMaxTimestampForHandler(nonUrgentDelegate.mpReadHandler) > - System::SystemClock().GetMonotonicTimestamp()); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mpReadHandler->IsDirty()); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mpReadHandler->ShouldStartReporting()); + EXPECT_LT(gReportScheduler->GetMinTimestampForHandler(nonUrgentDelegate.mpReadHandler), + System::SystemClock().GetMonotonicTimestamp()); + EXPECT_GT(gReportScheduler->GetMaxTimestampForHandler(nonUrgentDelegate.mpReadHandler), + System::SystemClock().GetMonotonicTimestamp()); + EXPECT_FALSE(nonUrgentDelegate.mpReadHandler->IsDirty()); + EXPECT_FALSE(nonUrgentDelegate.mpReadHandler->ShouldStartReporting()); // There should be no reporting run scheduled. This is very important; // otherwise we can get a false-positive pass below because the run was // already scheduled by here. - NL_TEST_ASSERT(apSuite, !InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); + EXPECT_FALSE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); // Generate some events, which should get reported. - GenerateEvents(apSuite, apContext); + GenerateEvents(); // Urgent read handler should now be dirty, and reportable. - NL_TEST_ASSERT(apSuite, delegate.mpReadHandler->IsDirty()); - NL_TEST_ASSERT(apSuite, delegate.mpReadHandler->ShouldStartReporting()); - NL_TEST_ASSERT(apSuite, gReportScheduler->IsReadHandlerReportable(delegate.mpReadHandler)); + EXPECT_TRUE(delegate.mpReadHandler->IsDirty()); + EXPECT_TRUE(delegate.mpReadHandler->ShouldStartReporting()); + EXPECT_TRUE(gReportScheduler->IsReadHandlerReportable(delegate.mpReadHandler)); // Non-urgent read handler should not be reportable. - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mpReadHandler->IsDirty()); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mpReadHandler->ShouldStartReporting()); + EXPECT_FALSE(nonUrgentDelegate.mpReadHandler->IsDirty()); + EXPECT_FALSE(nonUrgentDelegate.mpReadHandler->ShouldStartReporting()); // Still no reporting should have happened. - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mGotEventResponse); + EXPECT_FALSE(delegate.mGotEventResponse); + EXPECT_FALSE(nonUrgentDelegate.mGotEventResponse); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // Should get those urgent events reported. - NL_TEST_ASSERT(apSuite, delegate.mGotEventResponse); + EXPECT_TRUE(delegate.mGotEventResponse); // Should get nothing reported on the non-urgent handler. - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mGotEventResponse); + EXPECT_FALSE(nonUrgentDelegate.mGotEventResponse); } else { // If we're using the sub-sync scheduler, we should have gotten the non-urgent event as well. - NL_TEST_ASSERT(apSuite, nonUrgentDelegate.mGotEventResponse); + EXPECT_TRUE(nonUrgentDelegate.mGotEventResponse); // Since we just sent a report for both our subscriptions, the min interval of the urgent subcription should have been - NL_TEST_ASSERT( - apSuite, gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler) > gMockClock.GetMonotonicTimestamp()); - - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMinTimestampForHandler(nonUrgentDelegate.mpReadHandler) > - gMockClock.GetMonotonicTimestamp()); - NL_TEST_ASSERT(apSuite, !delegate.mpReadHandler->IsDirty()); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mpReadHandler->IsDirty()); + EXPECT_GT(gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler), gMockClock.GetMonotonicTimestamp()); + + EXPECT_GT(gReportScheduler->GetMinTimestampForHandler(nonUrgentDelegate.mpReadHandler), + gMockClock.GetMonotonicTimestamp()); + + EXPECT_FALSE(delegate.mpReadHandler->IsDirty()); + EXPECT_FALSE(nonUrgentDelegate.mpReadHandler->IsDirty()); delegate.mGotEventResponse = false; nonUrgentDelegate.mGotEventResponse = false; // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Milliseconds32(2100)); - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); // No reporting should have happened. - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mGotEventResponse); + EXPECT_FALSE(delegate.mGotEventResponse); + EXPECT_FALSE(nonUrgentDelegate.mGotEventResponse); // The min-interval should have elapsed for both subscriptions, and our handlers should still // not be dirty or reportable. - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler) < - System::SystemClock().GetMonotonicTimestamp()); - NL_TEST_ASSERT(apSuite, - gReportScheduler->GetMinTimestampForHandler(nonUrgentDelegate.mpReadHandler) < - System::SystemClock().GetMonotonicTimestamp()); - NL_TEST_ASSERT(apSuite, !delegate.mpReadHandler->IsDirty()); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mpReadHandler->IsDirty()); - NL_TEST_ASSERT(apSuite, !delegate.mpReadHandler->ShouldStartReporting()); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mpReadHandler->ShouldStartReporting()); + EXPECT_LT(gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler), + System::SystemClock().GetMonotonicTimestamp()); + EXPECT_LT(gReportScheduler->GetMinTimestampForHandler(nonUrgentDelegate.mpReadHandler), + System::SystemClock().GetMonotonicTimestamp()); + EXPECT_FALSE(delegate.mpReadHandler->IsDirty()); + EXPECT_FALSE(nonUrgentDelegate.mpReadHandler->IsDirty()); + EXPECT_FALSE(delegate.mpReadHandler->ShouldStartReporting()); + EXPECT_FALSE(nonUrgentDelegate.mpReadHandler->ShouldStartReporting()); // There should be no reporting run scheduled. This is very important; // otherwise we can get a false-positive pass below because the run was // already scheduled by here. - NL_TEST_ASSERT(apSuite, !InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); + EXPECT_FALSE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); // Generate some events, which should get reported. - GenerateEvents(apSuite, apContext); + GenerateEvents(); // Urgent read handler should now be dirty, and reportable. - NL_TEST_ASSERT(apSuite, delegate.mpReadHandler->IsDirty()); - NL_TEST_ASSERT(apSuite, delegate.mpReadHandler->ShouldStartReporting()); - NL_TEST_ASSERT(apSuite, gReportScheduler->IsReadHandlerReportable(delegate.mpReadHandler)); + EXPECT_TRUE(delegate.mpReadHandler->IsDirty()); + EXPECT_TRUE(delegate.mpReadHandler->ShouldStartReporting()); + EXPECT_TRUE(gReportScheduler->IsReadHandlerReportable(delegate.mpReadHandler)); // Non-urgent read handler should not be reportable. - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mpReadHandler->IsDirty()); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mpReadHandler->ShouldStartReporting()); + EXPECT_FALSE(nonUrgentDelegate.mpReadHandler->IsDirty()); + EXPECT_FALSE(nonUrgentDelegate.mpReadHandler->ShouldStartReporting()); // Still no reporting should have happened. - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, !nonUrgentDelegate.mGotEventResponse); + EXPECT_FALSE(delegate.mGotEventResponse); + EXPECT_FALSE(nonUrgentDelegate.mGotEventResponse); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // Should get those urgent events reported and the non urgent reported for synchronisation - NL_TEST_ASSERT(apSuite, delegate.mGotEventResponse); - NL_TEST_ASSERT(apSuite, nonUrgentDelegate.mGotEventResponse); + EXPECT_TRUE(delegate.mGotEventResponse); + EXPECT_TRUE(nonUrgentDelegate.mGotEventResponse); } } // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestSubscribeWildcard(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestSubscribeWildcard) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mEventPathParamsListSize = 0; std::unique_ptr attributePathParams(new chip::app::AttributePathParams[2]); @@ -2575,18 +2369,17 @@ void TestReadInteraction::TestSubscribeWildcard(nlTestSuite * apSuite, void * ap printf("\nSend subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; attributePathParams.release(); - err = readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); + EXPECT_TRUE(delegate.mGotReport); #if CHIP_CONFIG_ENABLE_EVENTLIST_ATTRIBUTE // Mock attribute storage in src/app/util/mock/attribute-storage.cpp @@ -2628,10 +2421,10 @@ void TestReadInteraction::TestSubscribeWildcard(nlTestSuite * apSuite, void * ap // the initial list followed by additional items. constexpr size_t kExpectedAttributeResponse = 29 * 2 + (kMockAttribute4ListLength - 4) + (kMockAttribute4ListLength - 4); #endif - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == kExpectedAttributeResponse); - NL_TEST_ASSERT(apSuite, delegate.mNumArrayItems == 12); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ((unsigned) delegate.mNumAttributeResponse, kExpectedAttributeResponse); + EXPECT_EQ(delegate.mNumArrayItems, 12); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); // Set a concrete path dirty @@ -2640,18 +2433,17 @@ void TestReadInteraction::TestSubscribeWildcard(nlTestSuite * apSuite, void * ap delegate.mNumAttributeResponse = 0; AttributePathParams dirtyPath; - dirtyPath.mEndpointId = Test::kMockEndpoint2; - dirtyPath.mClusterId = Test::MockClusterId(3); - dirtyPath.mAttributeId = Test::MockAttributeId(1); + dirtyPath.mEndpointId = chip::Test::kMockEndpoint2; + dirtyPath.mClusterId = chip::Test::MockClusterId(3); + dirtyPath.mAttributeId = chip::Test::MockAttributeId(1); - err = engine->GetReportingEngine().SetDirty(dirtyPath); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); + EXPECT_TRUE(delegate.mGotReport); // We subscribed wildcard path twice, so we will receive two reports here. - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 2); + EXPECT_EQ(delegate.mNumAttributeResponse, 2); } // Set a endpoint dirty @@ -2661,10 +2453,9 @@ void TestReadInteraction::TestSubscribeWildcard(nlTestSuite * apSuite, void * ap delegate.mNumArrayItems = 0; AttributePathParams dirtyPath; - dirtyPath.mEndpointId = Test::kMockEndpoint3; + dirtyPath.mEndpointId = chip::Test::kMockEndpoint3; - err = engine->GetReportingEngine().SetDirty(dirtyPath); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath), CHIP_NO_ERROR); // // We need to DrainAndServiceIO() until attribute callback will be called. @@ -2674,7 +2465,7 @@ void TestReadInteraction::TestSubscribeWildcard(nlTestSuite * apSuite, void * ap do { last = delegate.mNumAttributeResponse; - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); } while (last != delegate.mNumAttributeResponse); // Mock endpoint3 has 13 attributes in total, and we subscribed twice. @@ -2686,38 +2477,36 @@ void TestReadInteraction::TestSubscribeWildcard(nlTestSuite * apSuite, void * ap // // Thus we should receive 13*2 + 4 + 3 = 33 attribute data in total. ChipLogError(DataManagement, "RESPO: %d\n", delegate.mNumAttributeResponse); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 33); - NL_TEST_ASSERT(apSuite, delegate.mNumArrayItems == 12); + EXPECT_EQ(delegate.mNumAttributeResponse, 33); + EXPECT_EQ(delegate.mNumArrayItems, 12); } } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } // Subscribe (wildcard, C3, A1), then setDirty (E2, C3, wildcard), receive one attribute after setDirty -void TestReadInteraction::TestSubscribePartialOverlap(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestSubscribePartialOverlap) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mEventPathParamsListSize = 0; std::unique_ptr attributePathParams(new chip::app::AttributePathParams[2]); - attributePathParams[0].mClusterId = Test::MockClusterId(3); - attributePathParams[0].mAttributeId = Test::MockAttributeId(1); + attributePathParams[0].mClusterId = chip::Test::MockClusterId(3); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(1); readPrepareParams.mpAttributePathParamsList = attributePathParams.get(); readPrepareParams.mAttributePathParamsListSize = 1; @@ -2726,22 +2515,21 @@ void TestReadInteraction::TestSubscribePartialOverlap(nlTestSuite * apSuite, voi printf("\nSend subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; attributePathParams.release(); - err = readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); + EXPECT_TRUE(delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(delegate.mNumAttributeResponse, 1); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); // Set a partial overlapped path dirty @@ -2750,50 +2538,47 @@ void TestReadInteraction::TestSubscribePartialOverlap(nlTestSuite * apSuite, voi delegate.mNumAttributeResponse = 0; AttributePathParams dirtyPath; - dirtyPath.mEndpointId = Test::kMockEndpoint2; - dirtyPath.mClusterId = Test::MockClusterId(3); + dirtyPath.mEndpointId = chip::Test::kMockEndpoint2; + dirtyPath.mClusterId = chip::Test::MockClusterId(3); - err = engine->GetReportingEngine().SetDirty(dirtyPath); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 1); - NL_TEST_ASSERT(apSuite, delegate.mReceivedAttributePaths[0].mEndpointId == Test::kMockEndpoint2); - NL_TEST_ASSERT(apSuite, delegate.mReceivedAttributePaths[0].mClusterId == Test::MockClusterId(3)); - NL_TEST_ASSERT(apSuite, delegate.mReceivedAttributePaths[0].mAttributeId == Test::MockAttributeId(1)); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(delegate.mNumAttributeResponse, 1); + EXPECT_EQ(delegate.mReceivedAttributePaths[0].mEndpointId, chip::Test::kMockEndpoint2); + EXPECT_EQ(delegate.mReceivedAttributePaths[0].mClusterId, chip::Test::MockClusterId(3)); + EXPECT_EQ(delegate.mReceivedAttributePaths[0].mAttributeId, chip::Test::MockAttributeId(1)); } } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } // Subscribe (E2, C3, A1), then setDirty (wildcard, wildcard, wildcard), receive one attribute after setDirty -void TestReadInteraction::TestSubscribeSetDirtyFullyOverlap(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestSubscribeSetDirtyFullyOverlap) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mEventPathParamsListSize = 0; std::unique_ptr attributePathParams(new chip::app::AttributePathParams[1]); - attributePathParams[0].mClusterId = Test::kMockEndpoint2; - attributePathParams[0].mClusterId = Test::MockClusterId(3); - attributePathParams[0].mAttributeId = Test::MockAttributeId(1); + attributePathParams[0].mClusterId = chip::Test::kMockEndpoint2; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(3); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(1); readPrepareParams.mpAttributePathParamsList = attributePathParams.get(); readPrepareParams.mAttributePathParamsListSize = 1; @@ -2802,22 +2587,21 @@ void TestReadInteraction::TestSubscribeSetDirtyFullyOverlap(nlTestSuite * apSuit printf("\nSend subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; attributePathParams.release(); - err = readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); + EXPECT_TRUE(delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(delegate.mNumAttributeResponse, 1); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); // Set a full overlapped path dirty and expect to receive one E2C3A1 @@ -2826,36 +2610,34 @@ void TestReadInteraction::TestSubscribeSetDirtyFullyOverlap(nlTestSuite * apSuit delegate.mNumAttributeResponse = 0; AttributePathParams dirtyPath; - err = engine->GetReportingEngine().SetDirty(dirtyPath); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 1); - NL_TEST_ASSERT(apSuite, delegate.mReceivedAttributePaths[0].mEndpointId == Test::kMockEndpoint2); - NL_TEST_ASSERT(apSuite, delegate.mReceivedAttributePaths[0].mClusterId == Test::MockClusterId(3)); - NL_TEST_ASSERT(apSuite, delegate.mReceivedAttributePaths[0].mAttributeId == Test::MockAttributeId(1)); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(delegate.mNumAttributeResponse, 1); + EXPECT_EQ(delegate.mReceivedAttributePaths[0].mEndpointId, chip::Test::kMockEndpoint2); + EXPECT_EQ(delegate.mReceivedAttributePaths[0].mClusterId, chip::Test::MockClusterId(3)); + EXPECT_EQ(delegate.mReceivedAttributePaths[0].mAttributeId, chip::Test::MockAttributeId(1)); } } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } // Verify that subscription can be shut down just after receiving SUBSCRIBE RESPONSE, // before receiving any subsequent REPORT DATA. -void TestReadInteraction::TestSubscribeEarlyShutdown(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestSubscribeEarlyShutdown) { - TestContext & ctx = *static_cast(apContext); - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); InteractionModelEngine & engine = *InteractionModelEngine::GetInstance(); MockInteractionModelApp delegate; // Initialize Interaction Model Engine - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); - NL_TEST_ASSERT(apSuite, engine.Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler) == CHIP_NO_ERROR); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); + EXPECT_EQ(engine.Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); // Subscribe to the attribute AttributePathParams attributePathParams; @@ -2863,7 +2645,7 @@ void TestReadInteraction::TestSubscribeEarlyShutdown(nlTestSuite * apSuite, void attributePathParams.mClusterId = kTestClusterId; attributePathParams.mAttributeId = 1; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = &attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; readPrepareParams.mMinIntervalFloorSeconds = 2; @@ -2873,47 +2655,46 @@ void TestReadInteraction::TestSubscribeEarlyShutdown(nlTestSuite * apSuite, void printf("Send subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - NL_TEST_ASSERT(apSuite, readClient.SendRequest(readPrepareParams) == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 1); - NL_TEST_ASSERT(apSuite, engine.GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); - NL_TEST_ASSERT(apSuite, engine.ActiveHandlerAt(0) != nullptr); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(delegate.mNumAttributeResponse, 1); + EXPECT_EQ(engine.GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); + ASSERT_NE(engine.ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine.ActiveHandlerAt(0); - NL_TEST_ASSERT(apSuite, delegate.mpReadHandler != nullptr); + ASSERT_NE(delegate.mpReadHandler, nullptr); } // Cleanup - NL_TEST_ASSERT(apSuite, engine.GetNumActiveReadClients() == 0); - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(engine.GetNumActiveReadClients(), 0u); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); engine.Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestSubscribeInvalidAttributePathRoundtrip(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeInvalidAttributePathRoundtrip) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); + + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[1]; readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mpAttributePathParamsList[0].mEndpointId = kTestEndpointId; @@ -2922,24 +2703,24 @@ void TestReadInteraction::TestSubscribeInvalidAttributePathRoundtrip(nlTestSuite readPrepareParams.mAttributePathParamsListSize = 1; - readPrepareParams.mSessionHolder.Grab(ctx.GetSessionBobToAlice()); + readPrepareParams.mSessionHolder.Grab(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mMinIntervalFloorSeconds = 0; readPrepareParams.mMaxIntervalCeilingSeconds = 1; printf("\nSend subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - NL_TEST_ASSERT(apSuite, readClient.SendRequest(readPrepareParams) == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); delegate.mNumAttributeResponse = 0; - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 0); + EXPECT_EQ(delegate.mNumAttributeResponse, 0); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); uint16_t minInterval; @@ -2948,26 +2729,25 @@ void TestReadInteraction::TestSubscribeInvalidAttributePathRoundtrip(nlTestSuite // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(maxInterval)); - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().IsRunScheduled()); - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().IsRunScheduled()); + EXPECT_TRUE(engine->GetReportingEngine().IsRunScheduled()); + EXPECT_TRUE(engine->GetReportingEngine().IsRunScheduled()); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 0); + EXPECT_EQ(delegate.mNumAttributeResponse, 0); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestReadShutdown(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestReadShutdown) { auto * engine = chip::app::InteractionModelEngine::GetInstance(); app::ReadClient * pClients[4]; - TestContext & ctx = *static_cast(apContext); MockInteractionModelApp delegate; // @@ -2975,7 +2755,7 @@ void TestReadInteraction::TestReadShutdown(nlTestSuite * apSuite, void * apConte // for (auto & client : pClients) { - client = Platform::New(engine, &ctx.GetExchangeManager(), delegate, + client = Platform::New(engine, &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); } @@ -3001,24 +2781,22 @@ void TestReadInteraction::TestReadShutdown(nlTestSuite * apSuite, void * apConte Platform::Delete(pClients[2]); } -void TestReadInteraction::TestSubscribeInvalidInterval(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestSubscribeInvalidInterval) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[1]; readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mpAttributePathParamsList[0].mEndpointId = kTestEndpointId; @@ -3027,43 +2805,41 @@ void TestReadInteraction::TestSubscribeInvalidInterval(nlTestSuite * apSuite, vo readPrepareParams.mAttributePathParamsListSize = 1; - readPrepareParams.mSessionHolder.Grab(ctx.GetSessionBobToAlice()); + readPrepareParams.mSessionHolder.Grab(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mMinIntervalFloorSeconds = 6; readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - NL_TEST_ASSERT(apSuite, readClient.SendRequest(readPrepareParams) == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_ERROR_INVALID_ARGUMENT); printf("\nSend subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestPostSubscribeRoundtripStatusReportTimeout(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestPostSubscribeRoundtripStatusReportTimeout) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); + + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -3095,25 +2871,24 @@ void TestReadInteraction::TestPostSubscribeRoundtripStatusReportTimeout(nlTestSu readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); delegate.mGotReport = false; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 2); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(delegate.mNumAttributeResponse, 2); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); - GenerateEvents(apSuite, apContext); + GenerateEvents(); chip::app::AttributePathParams dirtyPath1; dirtyPath1.mClusterId = kTestClusterId; dirtyPath1.mEndpointId = kTestEndpointId; @@ -3128,64 +2903,61 @@ void TestReadInteraction::TestPostSubscribeRoundtripStatusReportTimeout(nlTestSu delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; - err = engine->GetReportingEngine().SetDirty(dirtyPath1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = engine->GetReportingEngine().SetDirty(dirtyPath2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath1), CHIP_NO_ERROR); + + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath2), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 2); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(delegate.mNumAttributeResponse, 2); // Wait for max interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMaxIntervalCeilingSeconds)); - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; - ctx.ExpireSessionBobToAlice(); + mpTestContext->ExpireSessionBobToAlice(); + + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath1), CHIP_NO_ERROR); - err = engine->GetReportingEngine().SetDirty(dirtyPath1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = engine->GetReportingEngine().SetDirty(dirtyPath2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().IsRunScheduled()); + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath2), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + EXPECT_TRUE(engine->GetReportingEngine().IsRunScheduled()); - ctx.ExpireSessionAliceToBob(); - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().GetNumReportsInFlight() == 0); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 0); + mpTestContext->DrainAndServiceIO(); + + mpTestContext->ExpireSessionAliceToBob(); + EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 0u); + EXPECT_EQ(delegate.mNumAttributeResponse, 0); } // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } -void TestReadInteraction::TestSubscribeRoundtripStatusReportTimeout(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestSubscribeRoundtripStatusReportTimeout) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -3217,156 +2989,147 @@ void TestReadInteraction::TestSubscribeRoundtripStatusReportTimeout(nlTestSuite readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); delegate.mGotReport = false; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionAliceToBob(); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - ctx.ExpireSessionBobToAlice(); + mpTestContext->ExpireSessionBobToAlice(); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 0); - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().GetNumReportsInFlight() == 0); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 0); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); + EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 0u); + EXPECT_EQ(delegate.mNumAttributeResponse, 0); } // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } -void TestReadInteraction::TestReadChunkingStatusReportTimeout(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestReadChunkingStatusReportTimeout) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[1]; // Mock Attribute 4 is a big attribute, with 6 large OCTET_STRING - attributePathParams[0].mEndpointId = Test::kMockEndpoint3; - attributePathParams[0].mClusterId = Test::MockClusterId(2); - attributePathParams[0].mAttributeId = Test::MockAttributeId(4); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.ExpireSessionAliceToBob(); - ctx.DrainAndServiceIO(); - ctx.ExpireSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->DrainAndServiceIO(); + mpTestContext->ExpireSessionBobToAlice(); - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().GetNumReportsInFlight() == 0); + EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 0u); // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // ReadClient sends the read request, but handler fails to send the one report (SendMessage returns an error). // Since this is an un-chunked read, we are not in the AwaitingReportResponse state, so the "reports in flight" // counter should not increase. -void TestReadInteraction::TestReadReportFailure(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestReadReportFailure) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[1]; - attributePathParams[0].mEndpointId = Test::kMockEndpoint2; - attributePathParams[0].mClusterId = Test::MockClusterId(3); - attributePathParams[0].mAttributeId = Test::MockAttributeId(1); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint2; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(3); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(1); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - ctx.GetLoopback().mNumMessagesToAllowBeforeError = 1; - ctx.GetLoopback().mMessageSendError = CHIP_ERROR_INCORRECT_STATE; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeError = 1; + mpTestContext->GetLoopback().mMessageSendError = CHIP_ERROR_INCORRECT_STATE; + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().GetNumReportsInFlight() == 0); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 0); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 0u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); - ctx.GetLoopback().mNumMessagesToAllowBeforeError = 0; - ctx.GetLoopback().mMessageSendError = CHIP_NO_ERROR; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeError = 0; + mpTestContext->GetLoopback().mMessageSendError = CHIP_NO_ERROR; } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestSubscribeRoundtripChunkStatusReportTimeout(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestSubscribeRoundtripChunkStatusReportTimeout) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -3381,9 +3144,9 @@ void TestReadInteraction::TestSubscribeRoundtripChunkStatusReportTimeout(nlTestS chip::app::AttributePathParams attributePathParams[1]; // Mock Attribute 4 is a big attribute, with 6 large OCTET_STRING - attributePathParams[0].mEndpointId = Test::kMockEndpoint3; - attributePathParams[0].mClusterId = Test::MockClusterId(2); - attributePathParams[0].mAttributeId = Test::MockAttributeId(4); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; @@ -3395,50 +3158,47 @@ void TestReadInteraction::TestSubscribeRoundtripChunkStatusReportTimeout(nlTestS readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); delegate.mGotReport = false; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.ExpireSessionAliceToBob(); - ctx.DrainAndServiceIO(); - ctx.ExpireSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->DrainAndServiceIO(); + mpTestContext->ExpireSessionBobToAlice(); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 0); - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().GetNumReportsInFlight() == 0); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 0); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); + EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 0u); + EXPECT_EQ(delegate.mNumAttributeResponse, 0); } // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } -void TestReadInteraction::TestPostSubscribeRoundtripChunkStatusReportTimeout(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkStatusReportTimeout) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -3453,9 +3213,9 @@ void TestReadInteraction::TestPostSubscribeRoundtripChunkStatusReportTimeout(nlT chip::app::AttributePathParams attributePathParams[1]; // Mock Attribute 4 is a big attribute, with 6 large OCTET_STRING - attributePathParams[0].mEndpointId = Test::kMockEndpoint3; - attributePathParams[0].mClusterId = Test::MockClusterId(2); - attributePathParams[0].mAttributeId = Test::MockAttributeId(4); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; @@ -3467,81 +3227,78 @@ void TestReadInteraction::TestPostSubscribeRoundtripChunkStatusReportTimeout(nlT readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); delegate.mGotReport = false; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); - GenerateEvents(apSuite, apContext); + GenerateEvents(); chip::app::AttributePathParams dirtyPath1; - dirtyPath1.mClusterId = Test::MockClusterId(2); - dirtyPath1.mEndpointId = Test::kMockEndpoint3; - dirtyPath1.mAttributeId = Test::MockAttributeId(4); + dirtyPath1.mClusterId = chip::Test::MockClusterId(2); + dirtyPath1.mEndpointId = chip::Test::kMockEndpoint3; + dirtyPath1.mAttributeId = chip::Test::MockAttributeId(4); gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMaxIntervalCeilingSeconds)); - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); + + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath1), CHIP_NO_ERROR); - err = engine->GetReportingEngine().SetDirty(dirtyPath1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - ctx.GetLoopback().mDroppedMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // Drop status report for the first chunked report, then expire session, handler would be timeout - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().GetNumReportsInFlight() == 1); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 0); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 1u); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } -void TestReadInteraction::TestPostSubscribeRoundtripChunkReportTimeout(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkReportTimeout) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -3556,9 +3313,9 @@ void TestReadInteraction::TestPostSubscribeRoundtripChunkReportTimeout(nlTestSui chip::app::AttributePathParams attributePathParams[1]; // Mock Attribute 4 is a big attribute, with 6 large OCTET_STRING - attributePathParams[0].mEndpointId = Test::kMockEndpoint3; - attributePathParams[0].mClusterId = Test::MockClusterId(2); - attributePathParams[0].mAttributeId = Test::MockAttributeId(4); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; @@ -3570,80 +3327,77 @@ void TestReadInteraction::TestPostSubscribeRoundtripChunkReportTimeout(nlTestSui readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); delegate.mGotReport = false; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); - GenerateEvents(apSuite, apContext); + GenerateEvents(); chip::app::AttributePathParams dirtyPath1; - dirtyPath1.mClusterId = Test::MockClusterId(2); - dirtyPath1.mEndpointId = Test::kMockEndpoint3; - dirtyPath1.mAttributeId = Test::MockAttributeId(4); + dirtyPath1.mClusterId = chip::Test::MockClusterId(2); + dirtyPath1.mEndpointId = chip::Test::kMockEndpoint3; + dirtyPath1.mAttributeId = chip::Test::MockAttributeId(4); gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMaxIntervalCeilingSeconds)); - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); + + EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath1), CHIP_NO_ERROR); - err = engine->GetReportingEngine().SetDirty(dirtyPath1); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; // Drop second chunked report then expire session, client would be timeout - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 2; - ctx.GetLoopback().mDroppedMessageCount = 0; - - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().GetNumReportsInFlight() == 1); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 3); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); - - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_ERROR_TIMEOUT); - - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 2; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 1u); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 3u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + EXPECT_EQ(delegate.mError, CHIP_ERROR_TIMEOUT); + + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } -void TestReadInteraction::TestPostSubscribeRoundtripChunkReport(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkReport) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -3658,9 +3412,9 @@ void TestReadInteraction::TestPostSubscribeRoundtripChunkReport(nlTestSuite * ap chip::app::AttributePathParams attributePathParams[1]; // Mock Attribute 4 is a big attribute, with 6 large OCTET_STRING - attributePathParams[0].mEndpointId = Test::kMockEndpoint3; - attributePathParams[0].mClusterId = Test::MockClusterId(2); - attributePathParams[0].mAttributeId = Test::MockAttributeId(4); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; @@ -3672,30 +3426,29 @@ void TestReadInteraction::TestPostSubscribeRoundtripChunkReport(nlTestSuite * ap readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); delegate.mGotReport = false; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); - GenerateEvents(apSuite, apContext); + GenerateEvents(); chip::app::AttributePathParams dirtyPath1; - dirtyPath1.mClusterId = Test::MockClusterId(2); - dirtyPath1.mEndpointId = Test::kMockEndpoint3; - dirtyPath1.mAttributeId = Test::MockAttributeId(4); + dirtyPath1.mClusterId = chip::Test::MockClusterId(2); + dirtyPath1.mEndpointId = chip::Test::kMockEndpoint3; + dirtyPath1.mAttributeId = chip::Test::MockAttributeId(4); - err = engine->GetReportingEngine().SetDirty(dirtyPath1); + engine->GetReportingEngine().SetDirty(dirtyPath1); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; delegate.mNumArrayItems = 0; @@ -3703,16 +3456,16 @@ void TestReadInteraction::TestPostSubscribeRoundtripChunkReport(nlTestSuite * ap // wait for min interval 1 seconds(in test, we use 0.9second considering the time variation), expect no event is // received, then wait for 0.5 seconds, then all chunked dirty reports are sent out, which would not honor minInterval gMockClock.AdvanceMonotonic(System::Clock::Milliseconds32(900)); - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 0); + EXPECT_EQ(delegate.mNumAttributeResponse, 0); System::Clock::Timestamp startTime = gMockClock.GetMonotonicTimestamp(); // Increment in time is done by steps here to allow for multiple IO processing at the right time and allow the timer to // be rescheduled accordingly while (true) { - ctx.GetIOContext().DriveIO(); + mpTestContext->GetIOContext().DriveIO(); if ((gMockClock.GetMonotonicTimestamp() - startTime) >= System::Clock::Milliseconds32(500)) { break; @@ -3723,78 +3476,41 @@ void TestReadInteraction::TestPostSubscribeRoundtripChunkReport(nlTestSuite * ap // We get one chunk with 4 array elements, and then one chunk per // element, and the total size of the array is // kMockAttribute4ListLength. - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 1 + (kMockAttribute4ListLength - 4)); - NL_TEST_ASSERT(apSuite, delegate.mNumArrayItems == 6); + EXPECT_EQ(delegate.mNumAttributeResponse, 1 + (kMockAttribute4ListLength - 4)); + EXPECT_EQ(delegate.mNumArrayItems, 6); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); } namespace { -void CheckForInvalidAction(nlTestSuite * apSuite, Test::MessageCapturer & messageLog) +void CheckForInvalidAction(Test::MessageCapturer & messageLog) { - NL_TEST_ASSERT(apSuite, messageLog.MessageCount() == 1); - NL_TEST_ASSERT(apSuite, messageLog.IsMessageType(0, Protocols::InteractionModel::MsgType::StatusResponse)); + EXPECT_EQ(messageLog.MessageCount(), 1u); + EXPECT_TRUE(messageLog.IsMessageType(0, Protocols::InteractionModel::MsgType::StatusResponse)); CHIP_ERROR status; - NL_TEST_ASSERT(apSuite, - StatusResponse::ProcessStatusResponse(std::move(messageLog.MessagePayload(0)), status) == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, status == CHIP_IM_GLOBAL_STATUS(InvalidAction)); + EXPECT_EQ(StatusResponse::ProcessStatusResponse(std::move(messageLog.MessagePayload(0)), status), CHIP_NO_ERROR); + EXPECT_EQ(status, CHIP_IM_GLOBAL_STATUS(InvalidAction)); } } // anonymous namespace -/** - * Helper macro we can use to pretend we got a reply from the server in cases - * when the reply was actually dropped due to us not wanting the client's state - * machine to advance. - * - * When this macro is used, the client has sent a message and is waiting for an - * ack+response, and the server has sent a response that got dropped and is - * waiting for an ack (and maybe a response). - * - * What this macro then needs to do is: - * - * 1. Pretend that the client got an ack (and clear out the corresponding ack - * state). - * 2. Pretend that the client got a message from the server, with the id of the - * message that was dropped, which requires an ack, so the client will send - * that ack in its next message. - * - * This is a macro so we get useful line numbers on assertion failures - */ -#define PretendWeGotReplyFromServer(aSuite, aContext, aClientExchange) \ - { \ - Messaging::ReliableMessageMgr * localRm = (aContext).GetExchangeManager().GetReliableMessageMgr(); \ - Messaging::ExchangeContext * localExchange = aClientExchange; \ - NL_TEST_ASSERT(aSuite, localRm->TestGetCountRetransTable() == 2); \ - \ - localRm->ClearRetransTable(localExchange); \ - NL_TEST_ASSERT(aSuite, localRm->TestGetCountRetransTable() == 1); \ - \ - localRm->EnumerateRetransTable([localExchange](auto * entry) { \ - localExchange->SetPendingPeerAckMessageCounter(entry->retainedBuf.GetMessageCounter()); \ - return Loop::Break; \ - }); \ - } - // Read Client sends the read request, Read Handler drops the response, then test injects unknown status reponse message for // Read Client. -void TestReadInteraction::TestReadClientReceiveInvalidMessage(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientReceiveInvalidMessage) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -3809,78 +3525,79 @@ void TestReadInteraction::TestReadClientReceiveInvalidMessage(nlTestSuite * apSu readPrepareParams.mAttributePathParamsListSize = 2; { - app::ReadClient readClient(engine, &ctx.GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); + app::ReadClient readClient(engine, &mpTestContext->GetExchangeManager(), delegate, + chip::app::ReadClient::InteractionType::Read); + + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + mpTestContext->DrainAndServiceIO(); + + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); StatusResponseMessage::Builder response; response.Init(&writer); response.Status(Protocols::InteractionModel::Status::Busy); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::StatusResponse); - Test::MessageCapturer messageLog(ctx); + chip::Test::MessageCapturer messageLog(*mpTestContext); messageLog.mCaptureStandaloneAcks = false; // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*mpTestContext, readClient.mExchange.Get()); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; readClient.OnMessageReceived(readClient.mExchange.Get(), payloadHeader, std::move(msgBuf)); - ctx.DrainAndServiceIO(); + + mpTestContext->DrainAndServiceIO(); // The ReadHandler closed its exchange when it sent the Report Data (which we dropped). // Since we synthesized the StatusResponse to the ReadClient, instead of sending it from the ReadHandler, // the only messages here are the ReadClient's StatusResponse to the unexpected message and an MRP ack. - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(Busy)); + EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(Busy)); - CheckForInvalidAction(apSuite, messageLog); + CheckForInvalidAction(messageLog); } engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Read Client sends the subscribe request, Read Handler drops the response, then test injects unknown status response message // for Read Client. -void TestReadInteraction::TestSubscribeClientReceiveInvalidStatusResponse(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidStatusResponse) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -3898,25 +3615,26 @@ void TestReadInteraction::TestSubscribeClientReceiveInvalidStatusResponse(nlTest readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); + + mpTestContext->DrainAndServiceIO(); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); StatusResponseMessage::Builder response; response.Init(&writer); response.Status(Protocols::InteractionModel::Status::Busy); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::StatusResponse); @@ -3924,56 +3642,54 @@ void TestReadInteraction::TestSubscribeClientReceiveInvalidStatusResponse(nlTest // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*mpTestContext, readClient.mExchange.Get()); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; readClient.OnMessageReceived(readClient.mExchange.Get(), payloadHeader, std::move(msgBuf)); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // TODO: Need to validate what status is being sent to the ReadHandler // The ReadHandler's exchange is closed when we synthesize the subscribe response, since it sent the // Subscribe Response as the last message in the transaction. // Since we synthesized the subscribe response to the ReadClient, instead of sending it from the ReadHandler, // the only messages here are the ReadClient's StatusResponse to the unexpected message and an MRP ack. - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(Busy)); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 0); + EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(Busy)); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Read Client sends the subscribe request, Read Handler drops the response, then test injects well-formed status response // message with Success for Read Client, we expect the error with CHIP_ERROR_INVALID_MESSAGE_TYPE -void TestReadInteraction::TestSubscribeClientReceiveWellFormedStatusResponse(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveWellFormedStatusResponse) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -3991,25 +3707,26 @@ void TestReadInteraction::TestSubscribeClientReceiveWellFormedStatusResponse(nlT readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); + + mpTestContext->DrainAndServiceIO(); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); StatusResponseMessage::Builder response; response.Init(&writer); response.Status(Protocols::InteractionModel::Status::Success); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::StatusResponse); @@ -4017,55 +3734,53 @@ void TestReadInteraction::TestSubscribeClientReceiveWellFormedStatusResponse(nlT // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*mpTestContext, readClient.mExchange.Get()); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; readClient.OnMessageReceived(readClient.mExchange.Get(), payloadHeader, std::move(msgBuf)); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // TODO: Need to validate what status is being sent to the ReadHandler // The ReadHandler's exchange is still open when we synthesize the StatusResponse. // Since we synthesized the StatusResponse to the ReadClient, instead of sending it from the ReadHandler, // the only messages here are the ReadClient's StatusResponse to the unexpected message and an MRP ack. - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_ERROR_INVALID_MESSAGE_TYPE); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 0); + EXPECT_EQ(delegate.mError, CHIP_ERROR_INVALID_MESSAGE_TYPE); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Read Client sends the subscribe request, Read Handler drops the response, then test injects invalid report message for Read // Client. -void TestReadInteraction::TestSubscribeClientReceiveInvalidReportMessage(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidReportMessage) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -4083,24 +3798,25 @@ void TestReadInteraction::TestSubscribeClientReceiveInvalidReportMessage(nlTestS readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); + + mpTestContext->DrainAndServiceIO(); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); ReportDataMessage::Builder response; response.Init(&writer); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::ReportData); @@ -4108,56 +3824,54 @@ void TestReadInteraction::TestSubscribeClientReceiveInvalidReportMessage(nlTestS // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*mpTestContext, readClient.mExchange.Get()); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; readClient.OnMessageReceived(readClient.mExchange.Get(), payloadHeader, std::move(msgBuf)); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // TODO: Need to validate what status is being sent to the ReadHandler // The ReadHandler's exchange is still open when we synthesize the ReportData. // Since we synthesized the ReportData to the ReadClient, instead of sending it from the ReadHandler, // the only messages here are the ReadClient's StatusResponse to the unexpected message and an MRP ack. - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_ERROR_END_OF_TLV); + EXPECT_EQ(delegate.mError, CHIP_ERROR_END_OF_TLV); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 0); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Read Client create the subscription, handler sends unsolicited malformed report to client, // InteractionModelEngine::OnUnsolicitedReportData would process this malformed report and sends out status report -void TestReadInteraction::TestSubscribeClientReceiveUnsolicitedInvalidReportMessage(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedInvalidReportMessage) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -4175,61 +3889,61 @@ void TestReadInteraction::TestSubscribeClientReceiveUnsolicitedInvalidReportMess readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - ctx.GetLoopback().mSentMessageCount = 0; - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + mpTestContext->GetLoopback().mSentMessageCount = 0; + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 5); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 5u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); ReportDataMessage::Builder response; response.Init(&writer); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); - ctx.GetLoopback().mSentMessageCount = 0; - auto exchange = InteractionModelEngine::GetInstance()->GetExchangeManager()->NewContext( + mpTestContext->GetLoopback().mSentMessageCount = 0; + auto exchange = InteractionModelEngine::GetInstance()->GetExchangeManager()->NewContext( delegate.mpReadHandler->mSessionHandle.Get().Value(), delegate.mpReadHandler); + delegate.mpReadHandler->mExchangeCtx.Grab(exchange); - err = delegate.mpReadHandler->mExchangeCtx->SendMessage(Protocols::InteractionModel::MsgType::ReportData, std::move(msgBuf), - Messaging::SendMessageFlags::kExpectResponse); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + + EXPECT_EQ(delegate.mpReadHandler->mExchangeCtx->SendMessage(Protocols::InteractionModel::MsgType::ReportData, + std::move(msgBuf), + Messaging::SendMessageFlags::kExpectResponse), + CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); // The server sends a data report. // The client receives the data report data and sends out status report with invalid action. // The server acks the status report. - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 3); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 3u); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); } // Read Client sends the subscribe request, Read Handler drops the subscribe response, then test injects invalid subscribe // response message -void TestReadInteraction::TestSubscribeClientReceiveInvalidSubscribeResponseMessage(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidSubscribeResponseMessage) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -4247,19 +3961,20 @@ void TestReadInteraction::TestSubscribeClientReceiveInvalidSubscribeResponseMess readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 3; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 3; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); + + mpTestContext->DrainAndServiceIO(); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); SubscribeResponseMessage::Builder response; @@ -4267,7 +3982,7 @@ void TestReadInteraction::TestSubscribeClientReceiveInvalidSubscribeResponseMess response.SubscriptionId(readClient.mSubscriptionId + 1); response.MaxInterval(1); response.EndOfSubscribeResponseMessage(); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::SubscribeResponse); @@ -4275,55 +3990,52 @@ void TestReadInteraction::TestSubscribeClientReceiveInvalidSubscribeResponseMess // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*mpTestContext, readClient.mExchange.Get()); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 4); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 4u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; readClient.OnMessageReceived(readClient.mExchange.Get(), payloadHeader, std::move(msgBuf)); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // TODO: Need to validate what status is being sent to the ReadHandler // The ReadHandler's exchange is still open when we synthesize the subscribe response. // Since we synthesized the subscribe response to the ReadClient, instead of sending it from the ReadHandler, // the only messages here are the ReadClient's StatusResponse to the unexpected message and an MRP ack. - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_ERROR_INVALID_SUBSCRIPTION); + EXPECT_EQ(delegate.mError, CHIP_ERROR_INVALID_SUBSCRIPTION); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Read Client create the subscription, handler sends unsolicited malformed report with invalid subscription id to client, // InteractionModelEngine::OnUnsolicitedReportData would process this malformed report and sends out status report -void TestReadInteraction::TestSubscribeClientReceiveUnsolicitedReportMessageWithInvalidSubscriptionId(nlTestSuite * apSuite, - void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedReportMessageWithInvalidSubscriptionId) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -4341,20 +4053,19 @@ void TestReadInteraction::TestSubscribeClientReceiveUnsolicitedReportMessageWith readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - ctx.GetLoopback().mSentMessageCount = 0; - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + mpTestContext->GetLoopback().mSentMessageCount = 0; + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 5); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 5u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); ReportDataMessage::Builder response; @@ -4362,74 +4073,75 @@ void TestReadInteraction::TestSubscribeClientReceiveUnsolicitedReportMessageWith response.SubscriptionId(readClient.mSubscriptionId + 1); response.EndOfReportDataMessage(); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); - ctx.GetLoopback().mSentMessageCount = 0; - auto exchange = InteractionModelEngine::GetInstance()->GetExchangeManager()->NewContext( + mpTestContext->GetLoopback().mSentMessageCount = 0; + auto exchange = InteractionModelEngine::GetInstance()->GetExchangeManager()->NewContext( delegate.mpReadHandler->mSessionHandle.Get().Value(), delegate.mpReadHandler); + delegate.mpReadHandler->mExchangeCtx.Grab(exchange); - err = delegate.mpReadHandler->mExchangeCtx->SendMessage(Protocols::InteractionModel::MsgType::ReportData, std::move(msgBuf), - Messaging::SendMessageFlags::kExpectResponse); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + + EXPECT_EQ(delegate.mpReadHandler->mExchangeCtx->SendMessage(Protocols::InteractionModel::MsgType::ReportData, + std::move(msgBuf), + Messaging::SendMessageFlags::kExpectResponse), + CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); // The server sends a data report. // The client receives the data report data and sends out status report with invalid subsciption. // The server should respond with a status report of its own, leading to 4 messages (because // the client would ack the server's status report), just sends an ack to the status report it got. - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 3); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 3u); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); } // TestReadChunkingInvalidSubscriptionId will try to read a few large attributes, the report won't fit into the MTU and result // in chunking, second report has different subscription id from the first one, read client sends out the status report with // invalid subscription -void TestReadInteraction::TestReadChunkingInvalidSubscriptionId(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadChunkingInvalidSubscriptionId) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, !delegate.mGotEventResponse); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); + EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[1]; // Mock Attribute 4 is a big attribute, with 6 large OCTET_STRING - attributePathParams[0].mEndpointId = Test::kMockEndpoint3; - attributePathParams[0].mClusterId = Test::MockClusterId(2); - attributePathParams[0].mAttributeId = Test::MockAttributeId(4); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 3; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 3; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); ReportDataMessage::Builder response; @@ -4440,229 +4152,223 @@ void TestReadInteraction::TestReadChunkingInvalidSubscriptionId(nlTestSuite * ap payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::ReportData); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*mpTestContext, readClient.mExchange.Get()); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 4); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 4u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; readClient.OnMessageReceived(readClient.mExchange.Get(), payloadHeader, std::move(msgBuf)); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // TODO: Need to validate what status is being sent to the ReadHandler // The ReadHandler's exchange is still open when we synthesize the report data message. // Since we synthesized the second report data message to the ReadClient with invalid subscription id, instead of // sending it from the ReadHandler, the only messages here are the ReadClient's StatusResponse to the unexpected message // and an MRP ack. - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_ERROR_INVALID_SUBSCRIPTION); + EXPECT_EQ(delegate.mError, CHIP_ERROR_INVALID_SUBSCRIPTION); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Read Client sends a malformed subscribe request, interaction model engine fails to parse the request and generates a status // report to client, and client is closed. -void TestReadInteraction::TestReadHandlerMalformedSubscribeRequest(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedSubscribeRequest) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); + System::PacketBufferHandle msgBuf; ReadRequestMessage::Builder request; System::PacketBufferTLVWriter writer; chip::app::InitWriterWithSpaceReserved(writer, 0); - err = request.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = writer.Finalize(&msgBuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + + EXPECT_EQ(request.Init(&writer), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); auto exchange = readClient.mpExchangeMgr->NewContext(readPrepareParams.mSessionHolder.Get().Value(), &readClient); - NL_TEST_ASSERT(apSuite, exchange != nullptr); + ASSERT_NE(exchange, nullptr); readClient.mExchange.Grab(exchange); readClient.MoveToState(app::ReadClient::ClientState::AwaitingInitialReport); - err = readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::ReadRequest, std::move(msgBuf), - Messaging::SendFlags(Messaging::SendMessageFlags::kExpectResponse)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(InvalidAction)); + + EXPECT_EQ(readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::ReadRequest, std::move(msgBuf), + Messaging::SendFlags(Messaging::SendMessageFlags::kExpectResponse)), + CHIP_NO_ERROR); + + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } // Read Client sends a malformed read request, interaction model engine fails to parse the request and generates a status report // to client, and client is closed. -void TestReadInteraction::TestReadHandlerMalformedReadRequest1(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedReadRequest1) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); + System::PacketBufferHandle msgBuf; ReadRequestMessage::Builder request; System::PacketBufferTLVWriter writer; chip::app::InitWriterWithSpaceReserved(writer, 0); - err = request.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - err = writer.Finalize(&msgBuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + + EXPECT_EQ(request.Init(&writer), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); auto exchange = readClient.mpExchangeMgr->NewContext(readPrepareParams.mSessionHolder.Get().Value(), &readClient); - NL_TEST_ASSERT(apSuite, exchange != nullptr); + ASSERT_NE(exchange, nullptr); readClient.mExchange.Grab(exchange); readClient.MoveToState(app::ReadClient::ClientState::AwaitingInitialReport); - err = readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::ReadRequest, std::move(msgBuf), - Messaging::SendFlags(Messaging::SendMessageFlags::kExpectResponse)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(InvalidAction)); + EXPECT_EQ(readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::ReadRequest, std::move(msgBuf), + Messaging::SendFlags(Messaging::SendMessageFlags::kExpectResponse)), + CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } // Read Client sends a malformed read request, read handler fails to parse the request and generates a status report to client, // and client is closed. -void TestReadInteraction::TestReadHandlerMalformedReadRequest2(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedReadRequest2) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); + System::PacketBufferHandle msgBuf; ReadRequestMessage::Builder request; System::PacketBufferTLVWriter writer; chip::app::InitWriterWithSpaceReserved(writer, 0); - err = request.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, request.EndOfReadRequestMessage() == CHIP_NO_ERROR); - err = writer.Finalize(&msgBuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(request.Init(&writer), CHIP_NO_ERROR); + EXPECT_EQ(request.EndOfReadRequestMessage(), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); auto exchange = readClient.mpExchangeMgr->NewContext(readPrepareParams.mSessionHolder.Get().Value(), &readClient); - NL_TEST_ASSERT(apSuite, exchange != nullptr); + ASSERT_NE(exchange, nullptr); readClient.mExchange.Grab(exchange); readClient.MoveToState(app::ReadClient::ClientState::AwaitingInitialReport); - err = readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::ReadRequest, std::move(msgBuf), - Messaging::SendFlags(Messaging::SendMessageFlags::kExpectResponse)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + EXPECT_EQ(readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::ReadRequest, std::move(msgBuf), + Messaging::SendFlags(Messaging::SendMessageFlags::kExpectResponse)), + CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); ChipLogError(DataManagement, "The error is %s", ErrorStr(delegate.mError)); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(InvalidAction)); + EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } // Read Client creates a subscription with the server, server sends chunked reports, after the handler sends out the first // chunked report, client sends out invalid write request message, handler sends status report with invalid action and closes -void TestReadInteraction::TestSubscribeSendUnknownMessage(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendUnknownMessage) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); chip::app::AttributePathParams attributePathParams[1]; // Mock Attribute 4 is a big attribute, with 6 large OCTET_STRING - attributePathParams[0].mEndpointId = Test::kMockEndpoint3; - attributePathParams[0].mClusterId = Test::MockClusterId(2); - attributePathParams[0].mAttributeId = Test::MockAttributeId(4); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); + + mpTestContext->DrainAndServiceIO(); // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*mpTestContext, readClient.mExchange.Get()); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); - ctx.GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; // Server sends out status report, client should send status report along with Piggybacking ack, but we don't do that // Instead, we send out unknown message to server @@ -4674,72 +4380,69 @@ void TestReadInteraction::TestSubscribeSendUnknownMessage(nlTestSuite * apSuite, request.Init(&writer); writer.Finalize(&msgBuf); - err = readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::WriteRequest, std::move(msgBuf)); - ctx.DrainAndServiceIO(); + readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::WriteRequest, std::move(msgBuf)); + mpTestContext->DrainAndServiceIO(); // client sends invalid write request, server sends out status report with invalid action and closes, client replies // with status report server replies with MRP Ack - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 4); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 0); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 4u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Read Client creates a subscription with the server, server sends chunked reports, after the handler sends out invalid status // report, client sends out invalid status report message, handler sends status report with invalid action and close -void TestReadInteraction::TestSubscribeSendInvalidStatusReport(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendInvalidStatusReport) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); chip::app::AttributePathParams attributePathParams[1]; // Mock Attribute 4 is a big attribute, with 6 large OCTET_STRING - attributePathParams[0].mEndpointId = Test::kMockEndpoint3; - attributePathParams[0].mClusterId = Test::MockClusterId(2); - attributePathParams[0].mAttributeId = Test::MockAttributeId(4); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - ctx.GetLoopback().mDroppedMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; - err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*mpTestContext, readClient.mExchange.Get()); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); - ctx.GetLoopback().mSentMessageCount = 0; + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + mpTestContext->GetLoopback().mSentMessageCount = 0; - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); System::PacketBufferHandle msgBuf; StatusResponseMessage::Builder request; @@ -4748,176 +4451,169 @@ void TestReadInteraction::TestSubscribeSendInvalidStatusReport(nlTestSuite * apS request.Init(&writer); writer.Finalize(&msgBuf); - err = readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::StatusResponse, std::move(msgBuf)); - ctx.DrainAndServiceIO(); + readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::StatusResponse, std::move(msgBuf)); + mpTestContext->DrainAndServiceIO(); // client sends malformed status response, server sends out status report with invalid action and close, client replies // with status report server replies with MRP Ack - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 4); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers() == 0); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 4u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Read Client sends a malformed subscribe request, the server fails to parse the request and generates a status report to the // client, and client closes itself. -void TestReadInteraction::TestReadHandlerInvalidSubscribeRequest(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerInvalidSubscribeRequest) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); + System::PacketBufferHandle msgBuf; ReadRequestMessage::Builder request; System::PacketBufferTLVWriter writer; chip::app::InitWriterWithSpaceReserved(writer, 0); - err = request.Init(&writer); - err = writer.Finalize(&msgBuf); + request.Init(&writer); + writer.Finalize(&msgBuf); auto exchange = readClient.mpExchangeMgr->NewContext(readPrepareParams.mSessionHolder.Get().Value(), &readClient); - NL_TEST_ASSERT(apSuite, exchange != nullptr); + ASSERT_NE(exchange, nullptr); readClient.mExchange.Grab(exchange); readClient.MoveToState(app::ReadClient::ClientState::AwaitingInitialReport); - err = readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::SubscribeRequest, std::move(msgBuf), - Messaging::SendFlags(Messaging::SendMessageFlags::kExpectResponse)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(InvalidAction)); + EXPECT_EQ(readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::SubscribeRequest, std::move(msgBuf), + Messaging::SendFlags(Messaging::SendMessageFlags::kExpectResponse)), + CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } // Create the subscription, then remove the corresponding fabric in client and handler, the corresponding // client and handler would be released as well. -void TestReadInteraction::TestSubscribeInvalidateFabric(nlTestSuite * apSuite, void * apContext) +TEST_F(TestReadInteraction, TestSubscribeInvalidateFabric) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = new chip::app::AttributePathParams[1]; readPrepareParams.mAttributePathParamsListSize = 1; - readPrepareParams.mpAttributePathParamsList[0].mEndpointId = Test::kMockEndpoint3; - readPrepareParams.mpAttributePathParamsList[0].mClusterId = Test::MockClusterId(2); - readPrepareParams.mpAttributePathParamsList[0].mAttributeId = Test::MockAttributeId(1); + readPrepareParams.mpAttributePathParamsList[0].mEndpointId = chip::Test::kMockEndpoint3; + readPrepareParams.mpAttributePathParamsList[0].mClusterId = chip::Test::MockClusterId(2); + readPrepareParams.mpAttributePathParamsList[0].mAttributeId = chip::Test::MockAttributeId(1); readPrepareParams.mMinIntervalFloorSeconds = 0; readPrepareParams.mMaxIntervalCeilingSeconds = 0; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; - err = readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); - ctx.GetFabricTable().Delete(ctx.GetAliceFabricIndex()); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 0); - ctx.GetFabricTable().Delete(ctx.GetBobFabricIndex()); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_ERROR_IM_FABRIC_DELETED); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateAliceFabric(); - ctx.CreateBobFabric(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->GetFabricTable().Delete(mpTestContext->GetAliceFabricIndex()); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 0u); + mpTestContext->GetFabricTable().Delete(mpTestContext->GetBobFabricIndex()); + EXPECT_EQ(delegate.mError, CHIP_ERROR_IM_FABRIC_DELETED); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateAliceFabric(); + mpTestContext->CreateBobFabric(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestReadInteraction::TestShutdownSubscription(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestShutdownSubscription) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - GenerateEvents(apSuite, apContext); + GenerateEvents(); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = new chip::app::AttributePathParams[1]; readPrepareParams.mAttributePathParamsListSize = 1; - readPrepareParams.mpAttributePathParamsList[0].mEndpointId = Test::kMockEndpoint3; - readPrepareParams.mpAttributePathParamsList[0].mClusterId = Test::MockClusterId(2); - readPrepareParams.mpAttributePathParamsList[0].mAttributeId = Test::MockAttributeId(1); + readPrepareParams.mpAttributePathParamsList[0].mEndpointId = chip::Test::kMockEndpoint3; + readPrepareParams.mpAttributePathParamsList[0].mClusterId = chip::Test::MockClusterId(2); + readPrepareParams.mpAttributePathParamsList[0].mAttributeId = chip::Test::MockAttributeId(1); readPrepareParams.mMinIntervalFloorSeconds = 0; readPrepareParams.mMaxIntervalCeilingSeconds = 0; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; - err = readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); engine->ShutdownSubscription(chip::ScopedNodeId(readClient.GetPeerNodeId(), readClient.GetFabricIndex()), readClient.GetSubscriptionId().Value()); - NL_TEST_ASSERT(apSuite, readClient.IsIdle()); + EXPECT_TRUE(readClient.IsIdle()); } engine->Shutdown(); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } /** @@ -4925,23 +4621,21 @@ void TestReadInteraction::TestShutdownSubscription(nlTestSuite * apSuite, void * * session it has is defunct. Makes sure we correctly tear down the ReadHandler * and don't increment the "reports in flight" count. */ -void TestReadInteraction::TestSubscriptionReportWithDefunctSession(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscriptionReportWithDefunctSession) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), gReportScheduler); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), + CHIP_NO_ERROR); - AttributePathParams subscribePath(Test::kMockEndpoint3, Test::MockClusterId(2), Test::MockAttributeId(1)); + AttributePathParams subscribePath(chip::Test::kMockEndpoint3, chip::Test::MockClusterId(2), chip::Test::MockAttributeId(1)); - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = &subscribePath; readPrepareParams.mAttributePathParamsListSize = 1; @@ -4949,40 +4643,39 @@ void TestReadInteraction::TestSubscriptionReportWithDefunctSession(nlTestSuite * readPrepareParams.mMaxIntervalCeilingSeconds = 0; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; - err = readClient.SendSubscribeRequest(std::move(readPrepareParams)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readClient.SendSubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Read) == 0); - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().GetNumReportsInFlight() == 0); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(delegate.mNumAttributeResponse, 1); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Read), 0u); + EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 0u); - NL_TEST_ASSERT(apSuite, engine->ActiveHandlerAt(0) != nullptr); + ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); auto * readHandler = engine->ActiveHandlerAt(0); // Verify that the session we will reset later is the one we will mess // with now. - NL_TEST_ASSERT(apSuite, SessionHandle(*readHandler->GetSession()) == ctx.GetSessionAliceToBob()); + EXPECT_EQ(SessionHandle(*readHandler->GetSession()), mpTestContext->GetSessionAliceToBob()); // Test that we send reports as needed. delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; engine->GetReportingEngine().SetDirty(subscribePath); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 1); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Read) == 0); - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().GetNumReportsInFlight() == 0); + EXPECT_TRUE(delegate.mGotReport); + EXPECT_EQ(delegate.mNumAttributeResponse, 1); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Read), 0u); + EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 0u); // Test that if the session is defunct we don't send reports and clean // up properly. @@ -4991,146 +4684,22 @@ void TestReadInteraction::TestSubscriptionReportWithDefunctSession(nlTestSuite * delegate.mNumAttributeResponse = 0; engine->GetReportingEngine().SetDirty(subscribePath); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, !delegate.mGotReport); - NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 0); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe) == 0); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Read) == 0); - NL_TEST_ASSERT(apSuite, engine->GetReportingEngine().GetNumReportsInFlight() == 0); + EXPECT_FALSE(delegate.mGotReport); + EXPECT_EQ(delegate.mNumAttributeResponse, 0); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 0u); + EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Read), 0u); + EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 0u); } engine->Shutdown(); - NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); // Get rid of our defunct session. - ctx.ExpireSessionAliceToBob(); - ctx.CreateSessionAliceToBob(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->CreateSessionAliceToBob(); } } // namespace app } // namespace chip - -namespace { - -const nlTest sTests[] = { - NL_TEST_DEF("TestReadRoundtrip", chip::app::TestReadInteraction::TestReadRoundtrip), - NL_TEST_DEF("TestReadRoundtripWithDataVersionFilter", chip::app::TestReadInteraction::TestReadRoundtripWithDataVersionFilter), - NL_TEST_DEF("TestReadRoundtripWithNoMatchPathDataVersionFilter", - chip::app::TestReadInteraction::TestReadRoundtripWithNoMatchPathDataVersionFilter), - NL_TEST_DEF("TestReadRoundtripWithMultiSamePathDifferentDataVersionFilter", - chip::app::TestReadInteraction::TestReadRoundtripWithMultiSamePathDifferentDataVersionFilter), - NL_TEST_DEF("TestReadRoundtripWithSameDifferentPathsDataVersionFilter", - chip::app::TestReadInteraction::TestReadRoundtripWithSameDifferentPathsDataVersionFilter), - NL_TEST_DEF("TestReadWildcard", chip::app::TestReadInteraction::TestReadWildcard), - NL_TEST_DEF("TestReadChunking", chip::app::TestReadInteraction::TestReadChunking), - NL_TEST_DEF("TestSetDirtyBetweenChunks", chip::app::TestReadInteraction::TestSetDirtyBetweenChunks), - NL_TEST_DEF("CheckReadClient", chip::app::TestReadInteraction::TestReadClient), - NL_TEST_DEF("TestReadUnexpectedSubscriptionId", chip::app::TestReadInteraction::TestReadUnexpectedSubscriptionId), - NL_TEST_DEF("CheckReadHandler", chip::app::TestReadInteraction::TestReadHandler), - NL_TEST_DEF("TestReadClientGenerateAttributePathList", chip::app::TestReadInteraction::TestReadClientGenerateAttributePathList), - NL_TEST_DEF("TestReadClientGenerateInvalidAttributePathList", - chip::app::TestReadInteraction::TestReadClientGenerateInvalidAttributePathList), - NL_TEST_DEF("TestReadClientGenerateOneEventPaths", chip::app::TestReadInteraction::TestReadClientGenerateOneEventPaths), - NL_TEST_DEF("TestReadClientGenerateTwoEventPaths", chip::app::TestReadInteraction::TestReadClientGenerateTwoEventPaths), - NL_TEST_DEF("TestReadClientInvalidReport", chip::app::TestReadInteraction::TestReadClientInvalidReport), - NL_TEST_DEF("TestReadClientInvalidAttributeId", chip::app::TestReadInteraction::TestReadClientInvalidAttributeId), - NL_TEST_DEF("TestReadHandlerInvalidAttributePath", chip::app::TestReadInteraction::TestReadHandlerInvalidAttributePath), - NL_TEST_DEF("TestProcessSubscribeRequest", chip::app::TestReadInteraction::TestProcessSubscribeRequest), -#if CHIP_CONFIG_ENABLE_ICD_SERVER - NL_TEST_DEF("TestICDProcessSubscribeRequestSupMaxIntervalCeiling", - chip::app::TestReadInteraction::TestICDProcessSubscribeRequestSupMaxIntervalCeiling), - NL_TEST_DEF("TestICDProcessSubscribeRequestInfMaxIntervalCeiling", - chip::app::TestReadInteraction::TestICDProcessSubscribeRequestInfMaxIntervalCeiling), - NL_TEST_DEF("TestICDProcessSubscribeRequestSupMinInterval", - chip::app::TestReadInteraction::TestICDProcessSubscribeRequestSupMinInterval), - NL_TEST_DEF("TestICDProcessSubscribeRequestMaxMinInterval", - chip::app::TestReadInteraction::TestICDProcessSubscribeRequestMaxMinInterval), - NL_TEST_DEF("TestICDProcessSubscribeRequestInvalidIdleModeDuration", - chip::app::TestReadInteraction::TestICDProcessSubscribeRequestInvalidIdleModeDuration), -#endif // #if CHIP_CONFIG_ENABLE_ICD_SERVER - NL_TEST_DEF("TestSubscribeRoundtrip", chip::app::TestReadInteraction::TestSubscribeRoundtrip), - NL_TEST_DEF("TestSubscribeEarlyReport", chip::app::TestReadInteraction::TestSubscribeEarlyReport), - NL_TEST_DEF("TestPostSubscribeRoundtripChunkReport", chip::app::TestReadInteraction::TestPostSubscribeRoundtripChunkReport), - NL_TEST_DEF("TestReadClientReceiveInvalidMessage", chip::app::TestReadInteraction::TestReadClientReceiveInvalidMessage), - NL_TEST_DEF("TestSubscribeClientReceiveInvalidStatusResponse", - chip::app::TestReadInteraction::TestSubscribeClientReceiveInvalidStatusResponse), - NL_TEST_DEF("TestSubscribeClientReceiveWellFormedStatusResponse", - chip::app::TestReadInteraction::TestSubscribeClientReceiveWellFormedStatusResponse), - NL_TEST_DEF("TestSubscribeClientReceiveInvalidReportMessage", - chip::app::TestReadInteraction::TestSubscribeClientReceiveInvalidReportMessage), - NL_TEST_DEF("TestSubscribeClientReceiveUnsolicitedInvalidReportMessage", - chip::app::TestReadInteraction::TestSubscribeClientReceiveUnsolicitedInvalidReportMessage), - NL_TEST_DEF("TestSubscribeClientReceiveInvalidSubscribeResponseMessage", - chip::app::TestReadInteraction::TestSubscribeClientReceiveInvalidSubscribeResponseMessage), - NL_TEST_DEF("TestSubscribeClientReceiveUnsolicitedReportMessageWithInvalidSubscriptionId", - chip::app::TestReadInteraction::TestSubscribeClientReceiveUnsolicitedReportMessageWithInvalidSubscriptionId), - NL_TEST_DEF("TestReadChunkingInvalidSubscriptionId", chip::app::TestReadInteraction::TestReadChunkingInvalidSubscriptionId), - NL_TEST_DEF("TestReadHandlerMalformedReadRequest1", chip::app::TestReadInteraction::TestReadHandlerMalformedReadRequest1), - NL_TEST_DEF("TestReadHandlerMalformedReadRequest2", chip::app::TestReadInteraction::TestReadHandlerMalformedReadRequest2), - NL_TEST_DEF("TestReadHandlerMalformedSubscribeRequest", - chip::app::TestReadInteraction::TestReadHandlerMalformedSubscribeRequest), - NL_TEST_DEF("TestSubscribeSendUnknownMessage", chip::app::TestReadInteraction::TestSubscribeSendUnknownMessage), - NL_TEST_DEF("TestSubscribeSendInvalidStatusReport", chip::app::TestReadInteraction::TestSubscribeSendInvalidStatusReport), - NL_TEST_DEF("TestReadHandlerInvalidSubscribeRequest", chip::app::TestReadInteraction::TestReadHandlerInvalidSubscribeRequest), - NL_TEST_DEF("TestSubscribeInvalidateFabric", chip::app::TestReadInteraction::TestSubscribeInvalidateFabric), - NL_TEST_DEF("TestShutdownSubscription", chip::app::TestReadInteraction::TestShutdownSubscription), - NL_TEST_DEF("TestSubscribeUrgentWildcardEvent", chip::app::TestReadInteraction::TestSubscribeUrgentWildcardEvent), - NL_TEST_DEF("TestSubscribeWildcard", chip::app::TestReadInteraction::TestSubscribeWildcard), - NL_TEST_DEF("TestSubscribePartialOverlap", chip::app::TestReadInteraction::TestSubscribePartialOverlap), - NL_TEST_DEF("TestSubscribeSetDirtyFullyOverlap", chip::app::TestReadInteraction::TestSubscribeSetDirtyFullyOverlap), - NL_TEST_DEF("TestSubscribeEarlyShutdown", chip::app::TestReadInteraction::TestSubscribeEarlyShutdown), - NL_TEST_DEF("TestSubscribeInvalidAttributePathRoundtrip", - chip::app::TestReadInteraction::TestSubscribeInvalidAttributePathRoundtrip), - NL_TEST_DEF("TestReadInvalidAttributePathRoundtrip", chip::app::TestReadInteraction::TestReadInvalidAttributePathRoundtrip), - NL_TEST_DEF("TestSubscribeInvalidInterval", chip::app::TestReadInteraction::TestSubscribeInvalidInterval), - NL_TEST_DEF("TestSubscribeRoundtripStatusReportTimeout", - chip::app::TestReadInteraction::TestSubscribeRoundtripStatusReportTimeout), - NL_TEST_DEF("TestPostSubscribeRoundtripStatusReportTimeout", - chip::app::TestReadInteraction::TestPostSubscribeRoundtripStatusReportTimeout), - NL_TEST_DEF("TestReadChunkingStatusReportTimeout", chip::app::TestReadInteraction::TestReadChunkingStatusReportTimeout), - NL_TEST_DEF("TestReadReportFailure", chip::app::TestReadInteraction::TestReadReportFailure), - NL_TEST_DEF("TestSubscribeRoundtripChunkStatusReportTimeout", - chip::app::TestReadInteraction::TestSubscribeRoundtripChunkStatusReportTimeout), - NL_TEST_DEF("TestPostSubscribeRoundtripChunkStatusReportTimeout", - chip::app::TestReadInteraction::TestPostSubscribeRoundtripChunkStatusReportTimeout), - NL_TEST_DEF("TestPostSubscribeRoundtripChunkReportTimeout", - chip::app::TestReadInteraction::TestPostSubscribeRoundtripChunkReportTimeout), - NL_TEST_DEF("TestReadShutdown", chip::app::TestReadInteraction::TestReadShutdown), - NL_TEST_DEF("TestSubscriptionReportWithDefunctSession", - chip::app::TestReadInteraction::TestSubscriptionReportWithDefunctSession), - NL_TEST_SENTINEL(), -}; - -nlTestSuite sSuite = { - "TestReadInteraction", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; - -nlTestSuite sSyncSuite = { - "TestSyncReadInteraction", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestSyncContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestSyncContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestSyncContext, SetUp), - NL_TEST_WRAP_METHOD(TestSyncContext, TearDown), -}; - -} // namespace - -int TestReadInteraction() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -int TestSyncReadInteraction() -{ - return chip::ExecuteTestsWithContext(&sSyncSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestReadInteraction) -CHIP_REGISTER_TEST_SUITE(TestSyncReadInteraction) diff --git a/src/app/tests/TestReportScheduler.cpp b/src/app/tests/TestReportScheduler.cpp index b7289f5f2daa90..dc54395149bbe4 100644 --- a/src/app/tests/TestReportScheduler.cpp +++ b/src/app/tests/TestReportScheduler.cpp @@ -20,11 +20,10 @@ #include #include #include -#include -#include +#include #include -#include - +#include +#include namespace { using TestContext = chip::Test::AppContext; @@ -53,6 +52,85 @@ using Milliseconds64 = System::Clock::Milliseconds64; static const size_t kNumMaxReadHandlers = 16; +class TestReportScheduler : public ::testing::Test +{ +public: + static void SetUpTestSuite() + { + mpTestContext = new chip::Test::AppContext; + mpTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + if (mpTestContext != nullptr) + { + delete mpTestContext; + } + } + + void SetUp() override + { + + if (mpTestContext != nullptr) + { + mpTestContext->SetUp(); + } + } + void TearDown() override + { + if (mpTestContext != nullptr) + { + mpTestContext->TearDown(); + } + } + + void TestReadHandlerList(); + void TestReportTiming(); + void TestObserverCallbacks(); + void TestSynchronizedScheduler(); + + /// @brief Mimicks the various operations that happen on a subscription transaction after a read handler was created so that + /// readhandlers are in the expected state for further tests. + /// @param readHandler + /// @param scheduler + static CHIP_ERROR MockReadHandlerSubscriptionTransaction(ReadHandler * readHandler, ReportScheduler * scheduler, + uint8_t min_interval_seconds, uint8_t max_interval_seconds) + { + ReturnErrorOnFailure(readHandler->SetMaxReportingInterval(max_interval_seconds)); + ReturnErrorOnFailure(readHandler->SetMinReportingIntervalForTests(min_interval_seconds)); + readHandler->ClearStateFlag(ReadHandler::ReadHandlerFlags::PrimingReports); + readHandler->SetStateFlag(ReadHandler::ReadHandlerFlags::ActiveSubscription); + scheduler->OnSubscriptionEstablished(readHandler); + readHandler->MoveToState(ReadHandler::HandlerState::CanStartReporting); + + return CHIP_NO_ERROR; + } + + static ReadHandler * GetReadHandlerFromPool(ReportScheduler * scheduler, uint32_t target) + { + uint32_t i = 0; + ReadHandler * ret = nullptr; + + scheduler->mNodesPool.ForEachActiveObject([target, &i, &ret](ReadHandlerNode * node) { + if (i == target) + { + ret = node->GetReadHandler(); + return Loop::Break; + } + + i++; + return Loop::Continue; + }); + + return ret; + } + + static chip::Test::AppContext * mpTestContext; +}; + +chip::Test::AppContext * TestReportScheduler::mpTestContext = nullptr; + class TestTimerDelegate : public ReportScheduler::TimerDelegate { public: @@ -217,621 +295,553 @@ ReportSchedulerImpl sScheduler(&sTestTimerDelegate); TestTimerSynchronizedDelegate sTestTimerSynchronizedDelegate; SynchronizedReportSchedulerImpl syncScheduler(&sTestTimerSynchronizedDelegate); -class TestReportScheduler +TEST_F_FROM_FIXTURE(TestReportScheduler, TestReadHandlerList) { -public: - /// @brief Mimicks the various operations that happen on a subscription transaction after a read handler was created so that - /// readhandlers are in the expected state for further tests. - /// @param readHandler - /// @param scheduler - static CHIP_ERROR MockReadHandlerSubscriptionTransaction(ReadHandler * readHandler, ReportScheduler * scheduler, - uint8_t min_interval_seconds, uint8_t max_interval_seconds) - { - ReturnErrorOnFailure(readHandler->SetMaxReportingInterval(max_interval_seconds)); - ReturnErrorOnFailure(readHandler->SetMinReportingIntervalForTests(min_interval_seconds)); - readHandler->ClearStateFlag(ReadHandler::ReadHandlerFlags::PrimingReports); - readHandler->SetStateFlag(ReadHandler::ReadHandlerFlags::ActiveSubscription); - scheduler->OnSubscriptionEstablished(readHandler); - readHandler->MoveToState(ReadHandler::HandlerState::CanStartReporting); - return CHIP_NO_ERROR; - } - - static ReadHandler * GetReadHandlerFromPool(ReportScheduler * scheduler, uint32_t target) - { - uint32_t i = 0; - ReadHandler * ret = nullptr; - - scheduler->mNodesPool.ForEachActiveObject([target, &i, &ret](ReadHandlerNode * node) { - if (i == target) - { - ret = node->GetReadHandler(); - return Loop::Break; - } + NullReadHandlerCallback nullCallback; + // exchange context + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); - i++; - return Loop::Continue; - }); + // Read handler pool + ObjectPool readHandlerPool; - return ret; - } + // Initialize mock timestamp + sTestTimerDelegate.SetMockSystemTimestamp(Milliseconds64(0)); - static void TestReadHandlerList(nlTestSuite * aSuite, void * aContext) + for (size_t i = 0; i < kNumMaxReadHandlers; i++) { - TestContext & ctx = *static_cast(aContext); - NullReadHandlerCallback nullCallback; - // exchange context - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(nullptr, false); - - // Read handler pool - ObjectPool readHandlerPool; - - // Initialize mock timestamp - sTestTimerDelegate.SetMockSystemTimestamp(Milliseconds64(0)); - - for (size_t i = 0; i < kNumMaxReadHandlers; i++) - { - ReadHandler * readHandler = - readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &sScheduler); - sScheduler.OnSubscriptionEstablished(readHandler); - NL_TEST_ASSERT(aSuite, nullptr != readHandler); - VerifyOrReturn(nullptr != readHandler); - NL_TEST_ASSERT(aSuite, nullptr != sScheduler.FindReadHandlerNode(readHandler)); - } - - NL_TEST_ASSERT(aSuite, readHandlerPool.Allocated() == kNumMaxReadHandlers); - NL_TEST_ASSERT(aSuite, sScheduler.GetNumReadHandlers() == kNumMaxReadHandlers); - NL_TEST_ASSERT(aSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 1); - - // Test unregister first ReadHandler - uint32_t target = 0; - ReadHandler * firstReadHandler = GetReadHandlerFromPool(&sScheduler, target); - - NL_TEST_ASSERT(aSuite, nullptr != firstReadHandler); - sScheduler.OnReadHandlerDestroyed(firstReadHandler); - NL_TEST_ASSERT(aSuite, sScheduler.GetNumReadHandlers() == kNumMaxReadHandlers - 1); - NL_TEST_ASSERT(aSuite, nullptr == sScheduler.FindReadHandlerNode(firstReadHandler)); - - // Test unregister middle ReadHandler - target = static_cast(sScheduler.GetNumReadHandlers() / 2); - ReadHandler * middleReadHandler = GetReadHandlerFromPool(&sScheduler, target); - - NL_TEST_ASSERT(aSuite, nullptr != middleReadHandler); - sScheduler.OnReadHandlerDestroyed(middleReadHandler); - NL_TEST_ASSERT(aSuite, sScheduler.GetNumReadHandlers() == kNumMaxReadHandlers - 2); - NL_TEST_ASSERT(aSuite, nullptr == sScheduler.FindReadHandlerNode(middleReadHandler)); - - // Test unregister last ReadHandler - target = static_cast(sScheduler.GetNumReadHandlers() - 1); - ReadHandler * lastReadHandler = GetReadHandlerFromPool(&sScheduler, target); - sScheduler.OnReadHandlerDestroyed(lastReadHandler); - NL_TEST_ASSERT(aSuite, sScheduler.GetNumReadHandlers() == kNumMaxReadHandlers - 3); - NL_TEST_ASSERT(aSuite, nullptr == sScheduler.FindReadHandlerNode(lastReadHandler)); - - sScheduler.UnregisterAllHandlers(); - // Confirm all ReadHandlers are unregistered from the scheduler - NL_TEST_ASSERT(aSuite, sScheduler.GetNumReadHandlers() == 0); - readHandlerPool.ForEachActiveObject([&](ReadHandler * handler) { - NL_TEST_ASSERT(aSuite, nullptr == sScheduler.FindReadHandlerNode(handler)); - return Loop::Continue; - }); - - readHandlerPool.ReleaseAll(); - exchangeCtx->Close(); - NL_TEST_ASSERT(aSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + ReadHandler * readHandler = + readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &sScheduler); + sScheduler.OnSubscriptionEstablished(readHandler); + ASSERT_NE(nullptr, readHandler); + ASSERT_NE(nullptr, sScheduler.FindReadHandlerNode(readHandler)); } - static void TestReportTiming(nlTestSuite * aSuite, void * aContext) - { - TestContext & ctx = *static_cast(aContext); - NullReadHandlerCallback nullCallback; - // exchange context - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(nullptr, false); + EXPECT_EQ(readHandlerPool.Allocated(), kNumMaxReadHandlers); + EXPECT_EQ(sScheduler.GetNumReadHandlers(), kNumMaxReadHandlers); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 1u); + + // Test unregister first ReadHandler + uint32_t target = 0; + ReadHandler * firstReadHandler = GetReadHandlerFromPool(&sScheduler, target); + + ASSERT_NE(nullptr, firstReadHandler); + sScheduler.OnReadHandlerDestroyed(firstReadHandler); + EXPECT_EQ(sScheduler.GetNumReadHandlers(), kNumMaxReadHandlers - 1); + EXPECT_EQ(nullptr, sScheduler.FindReadHandlerNode(firstReadHandler)); + + // Test unregister middle ReadHandler + target = static_cast(sScheduler.GetNumReadHandlers() / 2); + ReadHandler * middleReadHandler = GetReadHandlerFromPool(&sScheduler, target); + + ASSERT_NE(nullptr, middleReadHandler); + sScheduler.OnReadHandlerDestroyed(middleReadHandler); + EXPECT_EQ(sScheduler.GetNumReadHandlers(), kNumMaxReadHandlers - 2); + EXPECT_EQ(nullptr, sScheduler.FindReadHandlerNode(middleReadHandler)); + + // Test unregister last ReadHandler + target = static_cast(sScheduler.GetNumReadHandlers() - 1); + ReadHandler * lastReadHandler = GetReadHandlerFromPool(&sScheduler, target); + sScheduler.OnReadHandlerDestroyed(lastReadHandler); + EXPECT_EQ(sScheduler.GetNumReadHandlers(), kNumMaxReadHandlers - 3); + EXPECT_EQ(nullptr, sScheduler.FindReadHandlerNode(lastReadHandler)); + + sScheduler.UnregisterAllHandlers(); + // Confirm all ReadHandlers are unregistered from the scheduler + EXPECT_EQ(sScheduler.GetNumReadHandlers(), 0u); + readHandlerPool.ForEachActiveObject([&](ReadHandler * handler) { + EXPECT_EQ(nullptr, sScheduler.FindReadHandlerNode(handler)); + return Loop::Continue; + }); + + readHandlerPool.ReleaseAll(); + exchangeCtx->Close(); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); +} - // Read handler pool - ObjectPool readHandlerPool; +TEST_F_FROM_FIXTURE(TestReportScheduler, TestReportTiming) +{ - // Initialize mock timestamp - sTestTimerDelegate.SetMockSystemTimestamp(Milliseconds64(0)); + NullReadHandlerCallback nullCallback; + // exchange context + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + + // Read handler pool + ObjectPool readHandlerPool; + + // Initialize mock timestamp + sTestTimerDelegate.SetMockSystemTimestamp(Milliseconds64(0)); + + // Dirty read handler, will be triggered at min interval + // Test OnReadHandler created + ReadHandler * readHandler1 = + readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &sScheduler); + + EXPECT_EQ(CHIP_NO_ERROR, MockReadHandlerSubscriptionTransaction(readHandler1, &sScheduler, 1, 2)); + readHandler1->ForceDirtyState(); + + // Clean read handler, will be triggered at max interval + ReadHandler * readHandler2 = + readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &sScheduler); + EXPECT_EQ(CHIP_NO_ERROR, MockReadHandlerSubscriptionTransaction(readHandler2, &sScheduler, 0, 3)); + + // Clean read handler, will be triggered at max interval, but will be cancelled before + ReadHandler * readHandler3 = + readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &sScheduler); + EXPECT_EQ(CHIP_NO_ERROR, MockReadHandlerSubscriptionTransaction(readHandler3, &sScheduler, 0, 3)); + + // Confirms that none of the ReadHandlers are currently reportable + EXPECT_FALSE(sScheduler.IsReportableNow(readHandler1)); + EXPECT_FALSE(sScheduler.IsReportableNow(readHandler2)); + EXPECT_FALSE(sScheduler.IsReportableNow(readHandler3)); + + // Simulate system clock increment + sTestTimerDelegate.IncrementMockTimestamp(Milliseconds64(1100)); + + // Checks that the first ReadHandler is reportable after 1 second since it is dirty and min interval has expired + EXPECT_TRUE(sScheduler.IsReportableNow(readHandler1)); + EXPECT_FALSE(sScheduler.IsReportableNow(readHandler2)); + EXPECT_FALSE(sScheduler.IsReportableNow(readHandler3)); + + EXPECT_TRUE(sScheduler.IsReportScheduled(readHandler3)); + sScheduler.CancelReport(readHandler3); + EXPECT_FALSE(sScheduler.IsReportScheduled(readHandler3)); + + // Simulate system clock increment + sTestTimerDelegate.IncrementMockTimestamp(Milliseconds64(2000)); + + // Checks that all ReadHandlers are reportable + EXPECT_TRUE(sScheduler.IsReportableNow(readHandler1)); + EXPECT_TRUE(sScheduler.IsReportableNow(readHandler2)); + // Even if its timer got cancelled, readHandler3 should still be considered reportable as the max interval has expired + // and it is in generating report state + EXPECT_TRUE(sScheduler.IsReportableNow(readHandler3)); + + // Clear dirty flag on readHandler1 and confirm it is still reportable by time + readHandler1->ClearForceDirtyFlag(); + EXPECT_TRUE(sScheduler.IsReportableNow(readHandler1)); + + sScheduler.UnregisterAllHandlers(); + readHandlerPool.ReleaseAll(); + exchangeCtx->Close(); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); +} - // Dirty read handler, will be triggered at min interval - // Test OnReadHandler created - ReadHandler * readHandler1 = - readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &sScheduler); - NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == MockReadHandlerSubscriptionTransaction(readHandler1, &sScheduler, 1, 2)); - readHandler1->ForceDirtyState(); +TEST_F_FROM_FIXTURE(TestReportScheduler, TestObserverCallbacks) +{ - // Clean read handler, will be triggered at max interval - ReadHandler * readHandler2 = - readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &sScheduler); - NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == MockReadHandlerSubscriptionTransaction(readHandler2, &sScheduler, 0, 3)); + NullReadHandlerCallback nullCallback; + // exchange context + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); - // Clean read handler, will be triggered at max interval, but will be cancelled before - ReadHandler * readHandler3 = - readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &sScheduler); - NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == MockReadHandlerSubscriptionTransaction(readHandler3, &sScheduler, 0, 3)); - - // Confirms that none of the ReadHandlers are currently reportable - NL_TEST_ASSERT(aSuite, !sScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, !sScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, !sScheduler.IsReportableNow(readHandler3)); - - // Simulate system clock increment - sTestTimerDelegate.IncrementMockTimestamp(Milliseconds64(1100)); - - // Checks that the first ReadHandler is reportable after 1 second since it is dirty and min interval has expired - NL_TEST_ASSERT(aSuite, sScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, !sScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, !sScheduler.IsReportableNow(readHandler3)); - - NL_TEST_ASSERT(aSuite, sScheduler.IsReportScheduled(readHandler3)); - sScheduler.CancelReport(readHandler3); - NL_TEST_ASSERT(aSuite, !sScheduler.IsReportScheduled(readHandler3)); - - // Simulate system clock increment - sTestTimerDelegate.IncrementMockTimestamp(Milliseconds64(2000)); - - // Checks that all ReadHandlers are reportable - NL_TEST_ASSERT(aSuite, sScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, sScheduler.IsReportableNow(readHandler2)); - // Even if its timer got cancelled, readHandler3 should still be considered reportable as the max interval has expired - // and it is in generating report state - NL_TEST_ASSERT(aSuite, sScheduler.IsReportableNow(readHandler3)); - - // Clear dirty flag on readHandler1 and confirm it is still reportable by time - readHandler1->ClearForceDirtyFlag(); - NL_TEST_ASSERT(aSuite, sScheduler.IsReportableNow(readHandler1)); - - sScheduler.UnregisterAllHandlers(); - readHandlerPool.ReleaseAll(); - exchangeCtx->Close(); - NL_TEST_ASSERT(aSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); - } + // Read handler pool + ObjectPool readHandlerPool; - static void TestObserverCallbacks(nlTestSuite * aSuite, void * aContext) - { - TestContext & ctx = *static_cast(aContext); - NullReadHandlerCallback nullCallback; - // exchange context - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(nullptr, false); + // Initialize mock timestamp + sTestTimerDelegate.SetMockSystemTimestamp(Milliseconds64(0)); - // Read handler pool - ObjectPool readHandlerPool; + ReadHandler * readHandler = + readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &sScheduler); - // Initialize mock timestamp - sTestTimerDelegate.SetMockSystemTimestamp(Milliseconds64(0)); + EXPECT_EQ(CHIP_NO_ERROR, MockReadHandlerSubscriptionTransaction(readHandler, &sScheduler, 1, 2)); - ReadHandler * readHandler = - readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &sScheduler); - NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == MockReadHandlerSubscriptionTransaction(readHandler, &sScheduler, 1, 2)); + // Verifies OnSubscriptionEstablished registered the ReadHandler in the scheduler + ASSERT_NE(nullptr, sScheduler.FindReadHandlerNode(readHandler)); - // Verifies OnSubscriptionEstablished registered the ReadHandler in the scheduler - NL_TEST_ASSERT(aSuite, nullptr != sScheduler.FindReadHandlerNode(readHandler)); + // Should have registered the read handler in the scheduler and scheduled a report + EXPECT_EQ(sScheduler.GetNumReadHandlers(), 1u); - // Should have registered the read handler in the scheduler and scheduled a report - NL_TEST_ASSERT(aSuite, sScheduler.GetNumReadHandlers() == 1); + ReadHandlerNode * node = sScheduler.FindReadHandlerNode(readHandler); - ReadHandlerNode * node = sScheduler.FindReadHandlerNode(readHandler); + // Test OnReportingIntervalsChanged modified the intervals and re-scheduled a report + EXPECT_EQ(node->GetMinTimestamp().count(), 1000u); + EXPECT_EQ(node->GetMaxTimestamp().count(), 2000u); - // Test OnReportingIntervalsChanged modified the intervals and re-scheduled a report - NL_TEST_ASSERT(aSuite, node->GetMinTimestamp().count() == 1000); - NL_TEST_ASSERT(aSuite, node->GetMaxTimestamp().count() == 2000); + EXPECT_TRUE(sScheduler.IsReportScheduled(readHandler)); - NL_TEST_ASSERT(aSuite, sScheduler.IsReportScheduled(readHandler)); + ASSERT_NE(nullptr, node); + EXPECT_EQ(node->GetReadHandler(), readHandler); - NL_TEST_ASSERT(aSuite, nullptr != node); - VerifyOrReturn(nullptr != node); - NL_TEST_ASSERT(aSuite, node->GetReadHandler() == readHandler); + // Test OnBecameReportable + readHandler->ForceDirtyState(); + // Should have changed the scheduled timeout to the handler's min interval, to check, we wait for the min interval to + // expire + // Simulate system clock increment + sTestTimerDelegate.IncrementMockTimestamp(Milliseconds64(1100)); - // Test OnBecameReportable - readHandler->ForceDirtyState(); - // Should have changed the scheduled timeout to the handler's min interval, to check, we wait for the min interval to - // expire - // Simulate system clock increment - sTestTimerDelegate.IncrementMockTimestamp(Milliseconds64(1100)); + // Check that no report is scheduled since the min interval has expired, the timer should now be stopped + EXPECT_FALSE(sScheduler.IsReportScheduled(readHandler)); - // Check that no report is scheduled since the min interval has expired, the timer should now be stopped - NL_TEST_ASSERT(aSuite, !sScheduler.IsReportScheduled(readHandler)); + // Test OnSubscriptionReportSent + readHandler->ClearForceDirtyFlag(); + readHandler->mObserver->OnSubscriptionReportSent(readHandler); + // Should have changed the scheduled timeout to the handlers max interval, to check, we wait for the min interval to + // confirm it is not expired yet so the report should still be scheduled - // Test OnSubscriptionReportSent - readHandler->ClearForceDirtyFlag(); - readHandler->mObserver->OnSubscriptionReportSent(readHandler); - // Should have changed the scheduled timeout to the handlers max interval, to check, we wait for the min interval to - // confirm it is not expired yet so the report should still be scheduled + EXPECT_TRUE(sScheduler.IsReportScheduled(readHandler)); + // Simulate system clock increment + sTestTimerDelegate.IncrementMockTimestamp(Milliseconds64(1100)); - NL_TEST_ASSERT(aSuite, sScheduler.IsReportScheduled(readHandler)); - // Simulate system clock increment - sTestTimerDelegate.IncrementMockTimestamp(Milliseconds64(1100)); + // Check that the report is still scheduled as the max interval has not expired yet and the dirty flag was cleared + EXPECT_TRUE(sScheduler.IsReportScheduled(readHandler)); + // Simulate system clock increment + sTestTimerDelegate.IncrementMockTimestamp(Milliseconds64(2100)); - // Check that the report is still scheduled as the max interval has not expired yet and the dirty flag was cleared - NL_TEST_ASSERT(aSuite, sScheduler.IsReportScheduled(readHandler)); - // Simulate system clock increment - sTestTimerDelegate.IncrementMockTimestamp(Milliseconds64(2100)); + // Check that no report is scheduled since the max interval should have expired, the timer should now be stopped + EXPECT_FALSE(sScheduler.IsReportScheduled(readHandler)); - // Check that no report is scheduled since the max interval should have expired, the timer should now be stopped - NL_TEST_ASSERT(aSuite, !sScheduler.IsReportScheduled(readHandler)); + // Test OnReadHandlerDestroyed + readHandler->mObserver->OnReadHandlerDestroyed(readHandler); + // Should have unregistered the read handler in the scheduler and cancelled the report + EXPECT_FALSE(sScheduler.IsReportScheduled(readHandler)); + EXPECT_EQ(sScheduler.GetNumReadHandlers(), 0u); + EXPECT_EQ(nullptr, sScheduler.FindReadHandlerNode(readHandler)); - // Test OnReadHandlerDestroyed - readHandler->mObserver->OnReadHandlerDestroyed(readHandler); - // Should have unregistered the read handler in the scheduler and cancelled the report - NL_TEST_ASSERT(aSuite, !sScheduler.IsReportScheduled(readHandler)); - NL_TEST_ASSERT(aSuite, sScheduler.GetNumReadHandlers() == 0); - NL_TEST_ASSERT(aSuite, nullptr == sScheduler.FindReadHandlerNode(readHandler)); + readHandlerPool.ReleaseAll(); + exchangeCtx->Close(); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); +} - readHandlerPool.ReleaseAll(); - exchangeCtx->Close(); - NL_TEST_ASSERT(aSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); - } +TEST_F_FROM_FIXTURE(TestReportScheduler, TestSynchronizedScheduler) +{ - static void TestSynchronizedScheduler(nlTestSuite * aSuite, void * aContext) - { - TestContext & ctx = *static_cast(aContext); - NullReadHandlerCallback nullCallback; - // exchange context - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(nullptr, false); - - // First test: ReadHandler 2 merge on ReadHandler 1 max interval - // Read handler pool - ObjectPool readHandlerPool; - - // Initialize the mock system time - sTestTimerSynchronizedDelegate.SetMockSystemTimestamp(System::Clock::Milliseconds64(0)); - - ReadHandler * readHandler1 = - readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &syncScheduler); - NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == MockReadHandlerSubscriptionTransaction(readHandler1, &syncScheduler, 0, 2)); - ReadHandlerNode * node1 = syncScheduler.FindReadHandlerNode(readHandler1); - - ReadHandler * readHandler2 = - readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &syncScheduler); - NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == MockReadHandlerSubscriptionTransaction(readHandler2, &syncScheduler, 1, 3)); - ReadHandlerNode * node2 = syncScheduler.FindReadHandlerNode(readHandler2); - - // Confirm all handler are currently registered in the scheduler - NL_TEST_ASSERT(aSuite, syncScheduler.GetNumReadHandlers() == 2); - - // Confirm that a report emission is scheduled - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportScheduled(readHandler1)); - - // Validates that the lowest max is selected as the common max timestamp - NL_TEST_ASSERT(aSuite, syncScheduler.mNextMaxTimestamp == node1->GetMaxTimestamp()); - // Validates that the highest reportable min is selected as the common min interval (0 here) - NL_TEST_ASSERT(aSuite, syncScheduler.mNextMinTimestamp == node1->GetMinTimestamp()); - // Validates that the next report emission is scheduled on the common max timestamp - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == syncScheduler.mNextMaxTimestamp); - - // Simulate waiting for the max interval to expire (2s) - sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(2000)); - - // Confirm that both handlers are now reportable since the timer has expired (readHandler1 from its max and readHandler2 - // from its sync) - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler2)); - // Confirm timeout has expired and no report is scheduled, an engine run would typically happen here - NL_TEST_ASSERT(aSuite, !sScheduler.IsReportScheduled(readHandler1)); - NL_TEST_ASSERT(aSuite, !sScheduler.IsReportScheduled(readHandler2)); - - // Simulate a report emission for readHandler1 - readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); - // Simulate a report emission for readHandler2 - readHandler2->mObserver->OnSubscriptionReportSent(readHandler2); - - // Validate that the max timestamp for both readhandlers got updated and that the next report emission is scheduled on - // the new max timestamp for readhandler1 - NL_TEST_ASSERT(aSuite, node1->GetMaxTimestamp() > sTestTimerSynchronizedDelegate.GetCurrentMonotonicTimestamp()); - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == node1->GetMaxTimestamp()); - - // Confirm behavior when a read handler becomes dirty - readHandler2->ForceDirtyState(); - // OnBecomeReportable should have been called on ForceDirtyState because readHandler callbacks are now integrated - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler1)); - // Simulate wait enough for min timestamp of readHandler2 to be reached (1s) - sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1000)); - - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler1)); - - // Confirm that the next report emission is scheduled on the min timestamp of readHandler2 (now) as it is the highest - // reportable - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == node2->GetMinTimestamp()); - NL_TEST_ASSERT(aSuite, node1->CanBeSynced() == true); - - // Simulate a report emission for readHandler1 - readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler1)); - - // ReadHandler 2 should still be reportable since it hasn't emitted a report yet - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler2)); - readHandler2->ClearForceDirtyFlag(); - readHandler2->mObserver->OnSubscriptionReportSent(readHandler2); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - - // Simulate ReadHandler 1 becoming dirty after ReadHandler 2 past min will trigger a report emission for both - - // Wait past ReadHandler 2 min - sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1100)); - // No handler should be reportable yet - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler1)); - readHandler1->ForceDirtyState(); - - // Both read handlers should now be reportable since the ForceDirty should immediately trigger the timer expiration callback - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler1)); - - // Simulate a report emission for readHandler1 - readHandler1->ClearForceDirtyFlag(); - readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler1)); - - readHandler2->mObserver->OnSubscriptionReportSent(readHandler2); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - - // Confirm both handlers are not reportable anymore - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler1)); - - // Validate next report scheduled on the max timestamp of readHandler1 - NL_TEST_ASSERT(aSuite, node1->GetMaxTimestamp() > sTestTimerSynchronizedDelegate.GetCurrentMonotonicTimestamp()); - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == node1->GetMaxTimestamp()); - - // Simulate readHandler1 becoming dirty after less than 1 seconds, since it is reportable now, this will Schedule an Engine - // run immediately - sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(900)); - readHandler1->ForceDirtyState(); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - - // Simulate a report emission for readHandler1 - readHandler1->ClearForceDirtyFlag(); - readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - - // The next report should be scheduler on the max timestamp of readHandler1 - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == node1->GetMaxTimestamp()); - - sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(2000)); - // Confirm node 2 can now be synced since the scheduler timer has fired on the max timestamp of readHandler1 - NL_TEST_ASSERT(aSuite, node2->CanBeSynced() == true); - - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler2)); - readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); - readHandler2->mObserver->OnSubscriptionReportSent(readHandler2); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == node1->GetMaxTimestamp()); - - // Simulate a new ReadHandler being added with a min timestamp that will force a conflict - - // Wait for 1 second, nothing should happen here - sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1000)); - - ReadHandler * readHandler3 = - readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &syncScheduler); - NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == MockReadHandlerSubscriptionTransaction(readHandler3, &syncScheduler, 2, 3)); - ReadHandlerNode * node3 = syncScheduler.FindReadHandlerNode(readHandler3); - - // Confirm all handler are currently registered in the scheduler - NL_TEST_ASSERT(aSuite, syncScheduler.GetNumReadHandlers() == 3); - - // Since the min interval on readHandler3 is 2, it should be above the current max timestamp, therefore the next report - // should still happen on the max timestamp of readHandler1 and the sync should be done on future reports - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == node1->GetMaxTimestamp()); - // The min timestamp should also not have changed since the min of readhandler3 is higher than the current max - NL_TEST_ASSERT(aSuite, syncScheduler.mNextMinTimestamp == node2->GetMinTimestamp()); - - sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1000)); - - // Confirm that readHandler1 and readHandler 2 are now reportable, whilst readHandler3 is not - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler3)); - readHandler1->mObserver->OnBecameReportable(readHandler1); - readHandler2->mObserver->OnBecameReportable(readHandler2); - - // Simulate a report emission for readHandler1 and readHandler2 - readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); - readHandler1->mObserver->OnSubscriptionReportSent(readHandler2); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - - // Confirm that next report is scheduled on the max timestamp of readHandler3 and other 2 readHandlers are synced - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == node3->GetMaxTimestamp()); - - sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(2000)); - // Confirm nodes 1 and 2 can now be synced since the scheduler timer has fired on the max timestamp of readHandler1 - NL_TEST_ASSERT(aSuite, node1->CanBeSynced() == true); - NL_TEST_ASSERT(aSuite, node2->CanBeSynced() == true); - - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler3)); - readHandler1->mObserver->OnBecameReportable(readHandler1); - readHandler2->mObserver->OnBecameReportable(readHandler2); - readHandler3->mObserver->OnBecameReportable(readHandler3); - // Engine run should happen here and send all reports - readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); - readHandler2->mObserver->OnSubscriptionReportSent(readHandler2); - readHandler3->mObserver->OnSubscriptionReportSent(readHandler3); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler3)); - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == node1->GetMaxTimestamp()); - - // Now simulate a new readHandler being added with a max forcing a conflict - ReadHandler * readHandler4 = - readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &syncScheduler); - NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == MockReadHandlerSubscriptionTransaction(readHandler4, &syncScheduler, 0, 1)); - ReadHandlerNode * node4 = syncScheduler.FindReadHandlerNode(readHandler4); - - // Confirm all handler are currently registered in the scheduler - NL_TEST_ASSERT(aSuite, syncScheduler.GetNumReadHandlers() == 4); - - // Confirm next report is scheduled on the max timestamp of readHandler4 - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == node4->GetMaxTimestamp()); - - sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1100)); - // Confirm node 1 and 2 can now be synced since the scheduler timer has fired on the max timestamp of readHandler4 - NL_TEST_ASSERT(aSuite, node1->CanBeSynced() == true); - NL_TEST_ASSERT(aSuite, node2->CanBeSynced() == true); - // Confirm handler 3 cannot be synched on a later timestamp since its min is higher than the max of readHandler4 - NL_TEST_ASSERT(aSuite, node3->CanBeSynced() == false); - - // Confirm readHandler1, 2 and 4 are reportable - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler4)); - - // Confirm readHandler3 is not reportable - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler3)); - readHandler4->mObserver->OnBecameReportable(readHandler1); - readHandler4->mObserver->OnBecameReportable(readHandler2); - readHandler4->mObserver->OnBecameReportable(readHandler4); - readHandler4->mObserver->OnSubscriptionReportSent(readHandler1); - readHandler4->mObserver->OnSubscriptionReportSent(readHandler2); - readHandler4->mObserver->OnSubscriptionReportSent(readHandler4); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler4)); - - sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1000)); - - // Confirm readHandler3 is reportable and other handlers are synced - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler3)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler4)); - syncScheduler.OnBecameReportable(readHandler1); - syncScheduler.OnBecameReportable(readHandler2); - syncScheduler.OnBecameReportable(readHandler3); - syncScheduler.OnBecameReportable(readHandler4); - syncScheduler.OnSubscriptionReportSent(readHandler1); - syncScheduler.OnSubscriptionReportSent(readHandler2); - syncScheduler.OnSubscriptionReportSent(readHandler3); - syncScheduler.OnSubscriptionReportSent(readHandler4); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler3)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler4)); - - // Next emission should be scheduled on the max timestamp of readHandler4 as it is the most restrictive - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == node4->GetMaxTimestamp()); - - sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1000)); - // Confirm node 1 and 2 can now be synced since the scheduler timer has fired on the max timestamp of readHandler4 - NL_TEST_ASSERT(aSuite, node1->CanBeSynced() == true); - NL_TEST_ASSERT(aSuite, node2->CanBeSynced() == true); - // Confirm node 3 still cannot sync - NL_TEST_ASSERT(aSuite, node3->CanBeSynced() == false); - - // Confirm readHandler 1-2-4 are reportable - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler4)); - - // Confirm readHandler3 is not reportable because of its min interval - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler3)); - - syncScheduler.OnReadHandlerDestroyed(readHandler1); - syncScheduler.OnReadHandlerDestroyed(readHandler2); - syncScheduler.OnReadHandlerDestroyed(readHandler3); - syncScheduler.OnReadHandlerDestroyed(readHandler4); - - // Reset all handlers - // Test case: Scheduler 1 and 2 are reportable but min2 > max1, they should sync only when possible (min2 = 3, max1 = 2) - NL_TEST_ASSERT(aSuite, syncScheduler.GetNumReadHandlers() == 0); - - readHandler1->MoveToState(ReadHandler::HandlerState::Idle); - NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == MockReadHandlerSubscriptionTransaction(readHandler1, &syncScheduler, 0, 2)); - - // Forcing the dirty flag to make the scheduler call Engine::ScheduleRun() immediately - readHandler1->ForceDirtyState(); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler1)); - - readHandler2->MoveToState(ReadHandler::HandlerState::Idle); - NL_TEST_ASSERT(aSuite, CHIP_NO_ERROR == MockReadHandlerSubscriptionTransaction(readHandler2, &syncScheduler, 3, 4)); - readHandler2->ForceDirtyState(); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - - node1 = syncScheduler.FindReadHandlerNode(readHandler1); - node2 = syncScheduler.FindReadHandlerNode(readHandler2); - - readHandler1->ClearForceDirtyFlag(); // report got emited so clear dirty flag - syncScheduler.OnSubscriptionReportSent(readHandler1); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - - // Confirm next report is scheduled on the max timestamp of readHandler1 and readhandler2 is not synced - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == node1->GetMaxTimestamp()); - // Node 2's sync timestamp should have remained unaffected since its min is higher - NL_TEST_ASSERT(aSuite, node2->CanBeSynced() == false); - - sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(2000)); - // Verify handler 1 became reportable - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - syncScheduler.OnBecameReportable(readHandler1); - - // simulate run with only readhandler1 reportable - syncScheduler.OnSubscriptionReportSent(readHandler1); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, !syncScheduler.IsReportableNow(readHandler2)); - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == node2->GetMinTimestamp()); - - sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1000)); - NL_TEST_ASSERT(aSuite, node1->CanBeSynced() == true); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler1)); - NL_TEST_ASSERT(aSuite, syncScheduler.IsReportableNow(readHandler2)); - - readHandler2->ClearForceDirtyFlag(); - syncScheduler.OnSubscriptionReportSent(readHandler1); - syncScheduler.OnSubscriptionReportSent(readHandler2); - - NL_TEST_ASSERT(aSuite, syncScheduler.mNextReportTimestamp == node1->GetMaxTimestamp()); - NL_TEST_ASSERT(aSuite, node2->CanBeSynced() == false); - - syncScheduler.UnregisterAllHandlers(); - readHandlerPool.ReleaseAll(); - exchangeCtx->Close(); - NL_TEST_ASSERT(aSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); - } -}; + NullReadHandlerCallback nullCallback; + // exchange context + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + + // First test: ReadHandler 2 merge on ReadHandler 1 max interval + // Read handler pool + ObjectPool readHandlerPool; + + // Initialize the mock system time + sTestTimerSynchronizedDelegate.SetMockSystemTimestamp(System::Clock::Milliseconds64(0)); + + ReadHandler * readHandler1 = + readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &syncScheduler); + + EXPECT_EQ(CHIP_NO_ERROR, MockReadHandlerSubscriptionTransaction(readHandler1, &syncScheduler, 0, 2)); + ReadHandlerNode * node1 = syncScheduler.FindReadHandlerNode(readHandler1); + + ReadHandler * readHandler2 = + readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &syncScheduler); + EXPECT_EQ(CHIP_NO_ERROR, MockReadHandlerSubscriptionTransaction(readHandler2, &syncScheduler, 1, 3)); + + ReadHandlerNode * node2 = syncScheduler.FindReadHandlerNode(readHandler2); + + // Confirm all handler are currently registered in the scheduler + EXPECT_EQ(syncScheduler.GetNumReadHandlers(), 2u); + + // Confirm that a report emission is scheduled + EXPECT_TRUE(syncScheduler.IsReportScheduled(readHandler1)); + + // Validates that the lowest max is selected as the common max timestamp + EXPECT_EQ(syncScheduler.mNextMaxTimestamp, node1->GetMaxTimestamp()); + // Validates that the highest reportable min is selected as the common min interval (0 here) + EXPECT_EQ(syncScheduler.mNextMinTimestamp, node1->GetMinTimestamp()); + // Validates that the next report emission is scheduled on the common max timestamp + EXPECT_EQ(syncScheduler.mNextReportTimestamp, syncScheduler.mNextMaxTimestamp); + + // Simulate waiting for the max interval to expire (2s) + sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(2000)); + + // Confirm that both handlers are now reportable since the timer has expired (readHandler1 from its max and readHandler2 + // from its sync) + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler2)); + // Confirm timeout has expired and no report is scheduled, an engine run would typically happen here + EXPECT_FALSE(sScheduler.IsReportScheduled(readHandler1)); + EXPECT_FALSE(sScheduler.IsReportScheduled(readHandler2)); + + // Simulate a report emission for readHandler1 + readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); + // Simulate a report emission for readHandler2 + readHandler2->mObserver->OnSubscriptionReportSent(readHandler2); + + // Validate that the max timestamp for both readhandlers got updated and that the next report emission is scheduled on + // the new max timestamp for readhandler1 + EXPECT_GT(node1->GetMaxTimestamp(), sTestTimerSynchronizedDelegate.GetCurrentMonotonicTimestamp()); + EXPECT_EQ(syncScheduler.mNextReportTimestamp, node1->GetMaxTimestamp()); + + // Confirm behavior when a read handler becomes dirty + readHandler2->ForceDirtyState(); + // OnBecomeReportable should have been called on ForceDirtyState because readHandler callbacks are now integrated + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler1)); + // Simulate wait enough for min timestamp of readHandler2 to be reached (1s) + sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1000)); + + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler1)); + + // Confirm that the next report emission is scheduled on the min timestamp of readHandler2 (now) as it is the highest + // reportable + EXPECT_EQ(syncScheduler.mNextReportTimestamp, node2->GetMinTimestamp()); + EXPECT_TRUE(node1->CanBeSynced()); + + // Simulate a report emission for readHandler1 + readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler1)); + + // ReadHandler 2 should still be reportable since it hasn't emitted a report yet + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler2)); + readHandler2->ClearForceDirtyFlag(); + readHandler2->mObserver->OnSubscriptionReportSent(readHandler2); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + + // Simulate ReadHandler 1 becoming dirty after ReadHandler 2 past min will trigger a report emission for both + + // Wait past ReadHandler 2 min + sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1100)); + // No handler should be reportable yet + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler1)); + readHandler1->ForceDirtyState(); + + // Both read handlers should now be reportable since the ForceDirty should immediately trigger the timer expiration callback + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler1)); + + // Simulate a report emission for readHandler1 + readHandler1->ClearForceDirtyFlag(); + readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler1)); + + readHandler2->mObserver->OnSubscriptionReportSent(readHandler2); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + + // Confirm both handlers are not reportable anymore + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler1)); + + // Validate next report scheduled on the max timestamp of readHandler1 + EXPECT_GT(node1->GetMaxTimestamp(), sTestTimerSynchronizedDelegate.GetCurrentMonotonicTimestamp()); + EXPECT_EQ(syncScheduler.mNextReportTimestamp, node1->GetMaxTimestamp()); + + // Simulate readHandler1 becoming dirty after less than 1 seconds, since it is reportable now, this will Schedule an Engine + // run immediately + sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(900)); + readHandler1->ForceDirtyState(); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + + // Simulate a report emission for readHandler1 + readHandler1->ClearForceDirtyFlag(); + readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + + // The next report should be scheduler on the max timestamp of readHandler1 + EXPECT_EQ(syncScheduler.mNextReportTimestamp, node1->GetMaxTimestamp()); + + sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(2000)); + // Confirm node 2 can now be synced since the scheduler timer has fired on the max timestamp of readHandler1 + EXPECT_TRUE(node2->CanBeSynced()); + + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler2)); + readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); + readHandler2->mObserver->OnSubscriptionReportSent(readHandler2); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_EQ(syncScheduler.mNextReportTimestamp, node1->GetMaxTimestamp()); + + // Simulate a new ReadHandler being added with a min timestamp that will force a conflict + + // Wait for 1 second, nothing should happen here + sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1000)); + + ReadHandler * readHandler3 = + readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &syncScheduler); + + EXPECT_EQ(CHIP_NO_ERROR, MockReadHandlerSubscriptionTransaction(readHandler3, &syncScheduler, 2, 3)); + ReadHandlerNode * node3 = syncScheduler.FindReadHandlerNode(readHandler3); + + // Confirm all handler are currently registered in the scheduler + EXPECT_EQ(syncScheduler.GetNumReadHandlers(), 3u); + + // Since the min interval on readHandler3 is 2, it should be above the current max timestamp, therefore the next report + // should still happen on the max timestamp of readHandler1 and the sync should be done on future reports + EXPECT_EQ(syncScheduler.mNextReportTimestamp, node1->GetMaxTimestamp()); + // The min timestamp should also not have changed since the min of readhandler3 is higher than the current max + EXPECT_EQ(syncScheduler.mNextMinTimestamp, node2->GetMinTimestamp()); + + sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1000)); + + // Confirm that readHandler1 and readHandler 2 are now reportable, whilst readHandler3 is not + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler3)); + readHandler1->mObserver->OnBecameReportable(readHandler1); + readHandler2->mObserver->OnBecameReportable(readHandler2); + + // Simulate a report emission for readHandler1 and readHandler2 + readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); + readHandler1->mObserver->OnSubscriptionReportSent(readHandler2); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + + // Confirm that next report is scheduled on the max timestamp of readHandler3 and other 2 readHandlers are synced + EXPECT_EQ(syncScheduler.mNextReportTimestamp, node3->GetMaxTimestamp()); + + sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(2000)); + // Confirm nodes 1 and 2 can now be synced since the scheduler timer has fired on the max timestamp of readHandler1 + EXPECT_TRUE(node1->CanBeSynced()); + EXPECT_TRUE(node2->CanBeSynced()); + + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler3)); + readHandler1->mObserver->OnBecameReportable(readHandler1); + readHandler2->mObserver->OnBecameReportable(readHandler2); + readHandler3->mObserver->OnBecameReportable(readHandler3); + // Engine run should happen here and send all reports + readHandler1->mObserver->OnSubscriptionReportSent(readHandler1); + readHandler2->mObserver->OnSubscriptionReportSent(readHandler2); + readHandler3->mObserver->OnSubscriptionReportSent(readHandler3); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler3)); + EXPECT_EQ(syncScheduler.mNextReportTimestamp, node1->GetMaxTimestamp()); + + // Now simulate a new readHandler being added with a max forcing a conflict + ReadHandler * readHandler4 = + readHandlerPool.CreateObject(nullCallback, exchangeCtx, ReadHandler::InteractionType::Subscribe, &syncScheduler); + + EXPECT_EQ(CHIP_NO_ERROR, MockReadHandlerSubscriptionTransaction(readHandler4, &syncScheduler, 0, 1)); + ReadHandlerNode * node4 = syncScheduler.FindReadHandlerNode(readHandler4); + + // Confirm all handler are currently registered in the scheduler + EXPECT_EQ(syncScheduler.GetNumReadHandlers(), 4u); + + // Confirm next report is scheduled on the max timestamp of readHandler4 + EXPECT_EQ(syncScheduler.mNextReportTimestamp, node4->GetMaxTimestamp()); + + sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1100)); + // Confirm node 1 and 2 can now be synced since the scheduler timer has fired on the max timestamp of readHandler4 + EXPECT_TRUE(node1->CanBeSynced()); + EXPECT_TRUE(node2->CanBeSynced()); + // Confirm handler 3 cannot be synched on a later timestamp since its min is higher than the max of readHandler4 + EXPECT_FALSE(node3->CanBeSynced()); + + // Confirm readHandler1, 2 and 4 are reportable + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler4)); + + // Confirm readHandler3 is not reportable + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler3)); + readHandler4->mObserver->OnBecameReportable(readHandler1); + readHandler4->mObserver->OnBecameReportable(readHandler2); + readHandler4->mObserver->OnBecameReportable(readHandler4); + readHandler4->mObserver->OnSubscriptionReportSent(readHandler1); + readHandler4->mObserver->OnSubscriptionReportSent(readHandler2); + readHandler4->mObserver->OnSubscriptionReportSent(readHandler4); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler4)); + + sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1000)); + + // Confirm readHandler3 is reportable and other handlers are synced + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler3)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler4)); + syncScheduler.OnBecameReportable(readHandler1); + syncScheduler.OnBecameReportable(readHandler2); + syncScheduler.OnBecameReportable(readHandler3); + syncScheduler.OnBecameReportable(readHandler4); + syncScheduler.OnSubscriptionReportSent(readHandler1); + syncScheduler.OnSubscriptionReportSent(readHandler2); + syncScheduler.OnSubscriptionReportSent(readHandler3); + syncScheduler.OnSubscriptionReportSent(readHandler4); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler3)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler4)); + + // Next emission should be scheduled on the max timestamp of readHandler4 as it is the most restrictive + EXPECT_EQ(syncScheduler.mNextReportTimestamp, node4->GetMaxTimestamp()); + + sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1000)); + // Confirm node 1 and 2 can now be synced since the scheduler timer has fired on the max timestamp of readHandler4 + EXPECT_TRUE(node1->CanBeSynced()); + EXPECT_TRUE(node2->CanBeSynced()); + // Confirm node 3 still cannot sync + EXPECT_FALSE(node3->CanBeSynced()); + + // Confirm readHandler 1-2-4 are reportable + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler4)); + + // Confirm readHandler3 is not reportable because of its min interval + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler3)); + + syncScheduler.OnReadHandlerDestroyed(readHandler1); + syncScheduler.OnReadHandlerDestroyed(readHandler2); + syncScheduler.OnReadHandlerDestroyed(readHandler3); + syncScheduler.OnReadHandlerDestroyed(readHandler4); + + // Reset all handlers + // Test case: Scheduler 1 and 2 are reportable but min2 > max1, they should sync only when possible (min2 = 3, max1 = 2) + EXPECT_EQ(syncScheduler.GetNumReadHandlers(), 0u); + + readHandler1->MoveToState(ReadHandler::HandlerState::Idle); + EXPECT_EQ(CHIP_NO_ERROR, MockReadHandlerSubscriptionTransaction(readHandler1, &syncScheduler, 0, 2)); + + // Forcing the dirty flag to make the scheduler call Engine::ScheduleRun() immediately + readHandler1->ForceDirtyState(); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler1)); + + readHandler2->MoveToState(ReadHandler::HandlerState::Idle); + EXPECT_EQ(CHIP_NO_ERROR, MockReadHandlerSubscriptionTransaction(readHandler2, &syncScheduler, 3, 4)); + readHandler2->ForceDirtyState(); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + + node1 = syncScheduler.FindReadHandlerNode(readHandler1); + node2 = syncScheduler.FindReadHandlerNode(readHandler2); + + readHandler1->ClearForceDirtyFlag(); // report got emited so clear dirty flag + syncScheduler.OnSubscriptionReportSent(readHandler1); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + + // Confirm next report is scheduled on the max timestamp of readHandler1 and readhandler2 is not synced + EXPECT_EQ(syncScheduler.mNextReportTimestamp, node1->GetMaxTimestamp()); + // Node 2's sync timestamp should have remained unaffected since its min is higher + EXPECT_FALSE(node2->CanBeSynced()); + + sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(2000)); + // Verify handler 1 became reportable + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + syncScheduler.OnBecameReportable(readHandler1); + + // simulate run with only readhandler1 reportable + syncScheduler.OnSubscriptionReportSent(readHandler1); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_FALSE(syncScheduler.IsReportableNow(readHandler2)); + EXPECT_EQ(syncScheduler.mNextReportTimestamp, node2->GetMinTimestamp()); + + sTestTimerSynchronizedDelegate.IncrementMockTimestamp(System::Clock::Milliseconds64(1000)); + EXPECT_TRUE(node1->CanBeSynced()); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler1)); + EXPECT_TRUE(syncScheduler.IsReportableNow(readHandler2)); + + readHandler2->ClearForceDirtyFlag(); + syncScheduler.OnSubscriptionReportSent(readHandler1); + syncScheduler.OnSubscriptionReportSent(readHandler2); + + EXPECT_EQ(syncScheduler.mNextReportTimestamp, node1->GetMaxTimestamp()); + EXPECT_FALSE(node2->CanBeSynced()); + + syncScheduler.UnregisterAllHandlers(); + readHandlerPool.ReleaseAll(); + exchangeCtx->Close(); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); +} } // namespace reporting } // namespace app } // namespace chip - -namespace { - -/** - * Test Suite. It lists all the test functions. - */ - -static nlTest sTests[] = { - NL_TEST_DEF("TestReadHandlerList", chip::app::reporting::TestReportScheduler::TestReadHandlerList), - NL_TEST_DEF("TestReportTiming", chip::app::reporting::TestReportScheduler::TestReportTiming), - NL_TEST_DEF("TestObserverCallbacks", chip::app::reporting::TestReportScheduler::TestObserverCallbacks), - NL_TEST_DEF("TestSynchronizedScheduler", chip::app::reporting::TestReportScheduler::TestSynchronizedScheduler), - NL_TEST_SENTINEL(), -}; - -nlTestSuite sSuite = { - "TestReportScheduler", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; - -} // namespace - -int TestReportScheduler() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestReportScheduler); diff --git a/src/app/tests/TestReportingEngine.cpp b/src/app/tests/TestReportingEngine.cpp index 459c9752016e48..97d179b4e72dcc 100644 --- a/src/app/tests/TestReportingEngine.cpp +++ b/src/app/tests/TestReportingEngine.cpp @@ -22,6 +22,8 @@ * */ +#include + #include #include #include @@ -32,13 +34,10 @@ #include #include #include -#include -#include +#include #include #include - -#include -#include +#include using TestContext = chip::Test::AppContext; @@ -51,57 +50,41 @@ constexpr chip::AttributeId kTestFieldId2 = 2; namespace app { namespace reporting { -class TestReportingEngine + +std::unique_ptr mpTestContext; + +class TestReportingEngine : public ::testing::Test { public: - static void TestBuildAndSendSingleReportData(nlTestSuite * apSuite, void * apContext); - static void TestMergeOverlappedAttributePath(nlTestSuite * apSuite, void * apContext); - static void TestMergeAttributePathWhenDirtySetPoolExhausted(nlTestSuite * apSuite, void * apContext); + static void SetUpTestSuite() + { -private: + mpTestContext = std::make_unique(); + ASSERT_NE(mpTestContext, nullptr); + mpTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + mpTestContext.reset(); + } + void SetUp() { mpTestContext->SetUp(); } + void TearDown() { mpTestContext->TearDown(); } + + template + static bool VerifyDirtySetContent(const Args &... args); static bool InsertToDirtySet(const AttributePathParams & aPath); + void TestBuildAndSendSingleReportData(); + void TestMergeOverlappedAttributePath(); + void TestMergeAttributePathWhenDirtySetPoolExhausted(); + +private: struct ExpectedDirtySetContent : public AttributePathParams { ExpectedDirtySetContent(const AttributePathParams & path) : AttributePathParams(path) {} bool verified = false; }; - - template - static bool VerifyDirtySetContent(const Args &... args) - { - const int size = sizeof...(args); - ExpectedDirtySetContent content[size] = { ExpectedDirtySetContent(args)... }; - - if (InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.ForEachActiveObject([&](auto * path) { - for (int i = 0; i < size; i++) - { - if (static_cast(content[i]) == static_cast(*path)) - { - content[i].verified = true; - return Loop::Continue; - } - } - ChipLogDetail(DataManagement, "Dirty path Endpoint %x Cluster %" PRIx32 ", Attribute %" PRIx32 " is not expected", - path->mEndpointId, path->mClusterId, path->mAttributeId); - return Loop::Break; - }) == Loop::Break) - { - return false; - } - - for (int i = 0; i < size; i++) - { - if (!content[i].verified) - { - ChipLogDetail(DataManagement, - "Dirty path Endpoint %x Cluster %" PRIx32 ", Attribute %" PRIx32 " is not found in the dirty set", - content[i].mEndpointId, content[i].mClusterId, content[i].mAttributeId); - return false; - } - } - return true; - } }; class TestExchangeDelegate : public Messaging::ExchangeDelegate @@ -126,59 +109,98 @@ class DummyDelegate : public ReadHandler::ManagementCallback } }; -void TestReportingEngine::TestBuildAndSendSingleReportData(nlTestSuite * apSuite, void * apContext) +template +bool TestReportingEngine::VerifyDirtySetContent(const Args &... args) +{ + const int size = sizeof...(args); + ExpectedDirtySetContent content[size] = { ExpectedDirtySetContent(args)... }; + + if (InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.ForEachActiveObject([&](auto * path) { + for (int i = 0; i < size; i++) + { + if (static_cast(content[i]) == static_cast(*path)) + { + content[i].verified = true; + return Loop::Continue; + } + } + ChipLogDetail(DataManagement, "Dirty path Endpoint %x Cluster %" PRIx32 ", Attribute %" PRIx32 " is not expected", + path->mEndpointId, path->mClusterId, path->mAttributeId); + return Loop::Break; + }) == Loop::Break) + { + return false; + } + + for (int i = 0; i < size; i++) + { + if (!content[i].verified) + { + ChipLogDetail(DataManagement, + "Dirty path Endpoint %x Cluster %" PRIx32 ", Attribute %" PRIx32 " is not found in the dirty set", + content[i].mEndpointId, content[i].mClusterId, content[i].mAttributeId); + return false; + } + } + return true; +} + +bool TestReportingEngine::InsertToDirtySet(const AttributePathParams & aPath) +{ + auto path = InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.CreateObject(); + VerifyOrReturnError(path != nullptr, false); + *path = aPath; + path->mGeneration = InteractionModelEngine::GetInstance()->GetReportingEngine().GetDirtySetGeneration(); + return true; +} + +TEST_F_FROM_FIXTURE(TestReportingEngine, TestBuildAndSendSingleReportData) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBufferTLVWriter writer; System::PacketBufferHandle readRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); ReadRequestMessage::Builder readRequestBuilder; DummyDelegate dummy; - err = InteractionModelEngine::GetInstance()->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), - app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(InteractionModelEngine::GetInstance()->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); TestExchangeDelegate delegate; - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(&delegate); + Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(&delegate); writer.Init(std::move(readRequestbuf)); - err = readRequestBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readRequestBuilder.Init(&writer), CHIP_NO_ERROR); AttributePathIBs::Builder & attributePathListBuilder = readRequestBuilder.CreateAttributeRequests(); - NL_TEST_ASSERT(apSuite, readRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(readRequestBuilder.GetError(), CHIP_NO_ERROR); AttributePathIB::Builder & attributePathBuilder1 = attributePathListBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); attributePathBuilder1.Node(1).Endpoint(kTestEndpointId).Cluster(kTestClusterId).Attribute(kTestFieldId1).EndOfAttributePathIB(); - NL_TEST_ASSERT(apSuite, attributePathBuilder1.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder1.GetError(), CHIP_NO_ERROR); AttributePathIB::Builder & attributePathBuilder2 = attributePathListBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathListBuilder.GetError(), CHIP_NO_ERROR); attributePathBuilder2.Node(1).Endpoint(kTestEndpointId).Cluster(kTestClusterId).Attribute(kTestFieldId2).EndOfAttributePathIB(); - NL_TEST_ASSERT(apSuite, attributePathBuilder2.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder2.GetError(), CHIP_NO_ERROR); attributePathListBuilder.EndOfAttributePathIBs(); - NL_TEST_ASSERT(apSuite, readRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(readRequestBuilder.GetError(), CHIP_NO_ERROR); readRequestBuilder.IsFabricFiltered(false).EndOfReadRequestMessage(); - NL_TEST_ASSERT(apSuite, readRequestBuilder.GetError() == CHIP_NO_ERROR); - err = writer.Finalize(&readRequestbuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(readRequestBuilder.GetError(), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&readRequestbuf), CHIP_NO_ERROR); app::ReadHandler readHandler(dummy, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, app::reporting::GetDefaultReportScheduler()); readHandler.OnInitialRequest(std::move(readRequestbuf)); - err = InteractionModelEngine::GetInstance()->GetReportingEngine().BuildAndSendSingleReportData(&readHandler); - ctx.DrainAndServiceIO(); + EXPECT_EQ(InteractionModelEngine::GetInstance()->GetReportingEngine().BuildAndSendSingleReportData(&readHandler), + CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); } -void TestReportingEngine::TestMergeOverlappedAttributePath(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReportingEngine, TestMergeOverlappedAttributePath) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - err = InteractionModelEngine::GetInstance()->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), - app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(InteractionModelEngine::GetInstance()->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); AttributePathParams * clusterInfo = InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.CreateObject(); clusterInfo->mEndpointId = 1; @@ -190,8 +212,7 @@ void TestReportingEngine::TestMergeOverlappedAttributePath(nlTestSuite * apSuite testClusterInfo.mEndpointId = 1; testClusterInfo.mClusterId = 1; testClusterInfo.mAttributeId = 3; - NL_TEST_ASSERT(apSuite, - !InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); + EXPECT_FALSE(InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); } { AttributePathParams testClusterInfo; @@ -199,8 +220,7 @@ void TestReportingEngine::TestMergeOverlappedAttributePath(nlTestSuite * apSuite testClusterInfo.mClusterId = 1; testClusterInfo.mAttributeId = 1; testClusterInfo.mListIndex = 2; - NL_TEST_ASSERT(apSuite, - InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); + EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); } { @@ -208,17 +228,15 @@ void TestReportingEngine::TestMergeOverlappedAttributePath(nlTestSuite * apSuite testClusterInfo.mEndpointId = 1; testClusterInfo.mClusterId = 1; testClusterInfo.mAttributeId = kInvalidAttributeId; - NL_TEST_ASSERT(apSuite, - InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); + EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); } { AttributePathParams testClusterInfo; testClusterInfo.mClusterId = kInvalidClusterId; testClusterInfo.mAttributeId = kInvalidAttributeId; - NL_TEST_ASSERT(apSuite, - InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); - NL_TEST_ASSERT(apSuite, clusterInfo->mClusterId == kInvalidClusterId && clusterInfo->mAttributeId == kInvalidAttributeId); + EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); + EXPECT_TRUE(clusterInfo->mClusterId == kInvalidClusterId && clusterInfo->mAttributeId == kInvalidAttributeId); } { @@ -226,31 +244,18 @@ void TestReportingEngine::TestMergeOverlappedAttributePath(nlTestSuite * apSuite testClusterInfo.mEndpointId = kInvalidEndpointId; testClusterInfo.mClusterId = kInvalidClusterId; testClusterInfo.mAttributeId = kInvalidAttributeId; - NL_TEST_ASSERT(apSuite, - InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); - NL_TEST_ASSERT(apSuite, - clusterInfo->mEndpointId == kInvalidEndpointId && clusterInfo->mClusterId == kInvalidClusterId && - clusterInfo->mAttributeId == kInvalidAttributeId); + EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); + EXPECT_TRUE(clusterInfo->mEndpointId == kInvalidEndpointId && clusterInfo->mClusterId == kInvalidClusterId && + clusterInfo->mAttributeId == kInvalidAttributeId); } InteractionModelEngine::GetInstance()->GetReportingEngine().Shutdown(); } -bool TestReportingEngine::InsertToDirtySet(const AttributePathParams & aPath) -{ - auto path = InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.CreateObject(); - VerifyOrReturnError(path != nullptr, false); - *path = aPath; - path->mGeneration = InteractionModelEngine::GetInstance()->GetReportingEngine().GetDirtySetGeneration(); - return true; -} - -void TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestReportingEngine, TestMergeAttributePathWhenDirtySetPoolExhausted) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - err = InteractionModelEngine::GetInstance()->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), - app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(InteractionModelEngine::GetInstance()->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.ReleaseAll(); InteractionModelEngine::GetInstance()->GetReportingEngine().BumpDirtySetGeneration(); @@ -259,13 +264,12 @@ void TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted(nlTest // -> Expected behavior: The dirty set is replaced by a wildcard attribute path under the same cluster. for (AttributeId i = 1; i <= CHIP_IM_SERVER_MAX_NUM_DIRTY_SET; i++) { - NL_TEST_ASSERT(apSuite, InsertToDirtySet(AttributePathParams(kTestEndpointId, kTestClusterId, i))); + EXPECT_TRUE(InsertToDirtySet(AttributePathParams(kTestEndpointId, kTestClusterId, i))); } - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == - InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( - AttributePathParams(kTestEndpointId, kTestClusterId, CHIP_IM_SERVER_MAX_NUM_DIRTY_SET + 1))); - NL_TEST_ASSERT(apSuite, VerifyDirtySetContent(AttributePathParams(kTestEndpointId, kTestClusterId))); + EXPECT_EQ(CHIP_NO_ERROR, + InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( + AttributePathParams(kTestEndpointId, kTestClusterId, CHIP_IM_SERVER_MAX_NUM_DIRTY_SET + 1))); + EXPECT_TRUE(VerifyDirtySetContent(AttributePathParams(kTestEndpointId, kTestClusterId))); InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.ReleaseAll(); @@ -273,13 +277,12 @@ void TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted(nlTest // -> Expected behavior: The dirty set is replaced by a wildcard cluster path under the same endpoint. for (ClusterId i = 1; i <= CHIP_IM_SERVER_MAX_NUM_DIRTY_SET; i++) { - NL_TEST_ASSERT(apSuite, InsertToDirtySet(AttributePathParams(kTestEndpointId, i, 1))); + EXPECT_TRUE(InsertToDirtySet(AttributePathParams(kTestEndpointId, i, 1))); } - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == - InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( - AttributePathParams(kTestEndpointId, ClusterId(CHIP_IM_SERVER_MAX_NUM_DIRTY_SET + 1), 1))); - NL_TEST_ASSERT(apSuite, VerifyDirtySetContent(AttributePathParams(kTestEndpointId, kInvalidClusterId))); + EXPECT_EQ(CHIP_NO_ERROR, + InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( + AttributePathParams(kTestEndpointId, ClusterId(CHIP_IM_SERVER_MAX_NUM_DIRTY_SET + 1), 1))); + EXPECT_TRUE(VerifyDirtySetContent(AttributePathParams(kTestEndpointId, kInvalidClusterId))); InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.ReleaseAll(); @@ -287,29 +290,27 @@ void TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted(nlTest // -> Expected behavior: The dirty set is replaced by a wildcard endpoint. for (EndpointId i = 1; i <= CHIP_IM_SERVER_MAX_NUM_DIRTY_SET; i++) { - NL_TEST_ASSERT(apSuite, InsertToDirtySet(AttributePathParams(EndpointId(i), i, i))); + EXPECT_TRUE(InsertToDirtySet(AttributePathParams(EndpointId(i), i, i))); } - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == - InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( - AttributePathParams(EndpointId(CHIP_IM_SERVER_MAX_NUM_DIRTY_SET + 1), 1, 1))); - NL_TEST_ASSERT(apSuite, VerifyDirtySetContent(AttributePathParams())); + EXPECT_EQ(CHIP_NO_ERROR, + InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( + AttributePathParams(EndpointId(CHIP_IM_SERVER_MAX_NUM_DIRTY_SET + 1), 1, 1))); + EXPECT_TRUE(VerifyDirtySetContent(AttributePathParams())); InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.ReleaseAll(); // Case 4: All existing dirty paths are under the same cluster, the new path comes from another cluster. - // -> Expected behavior: The existing paths are merged into one single wildcard attribute path. New path is inserted as-is. + // -> Expected behavior: The existing paths are merged into one single wildcard attribute path. New path is inserted + // as-is. for (EndpointId i = 1; i <= CHIP_IM_SERVER_MAX_NUM_DIRTY_SET; i++) { - NL_TEST_ASSERT(apSuite, InsertToDirtySet(AttributePathParams(kTestEndpointId, kTestClusterId, i))); + EXPECT_TRUE(InsertToDirtySet(AttributePathParams(kTestEndpointId, kTestClusterId, i))); } - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == - InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( - AttributePathParams(kTestEndpointId + 1, kTestClusterId + 1, 1))); - NL_TEST_ASSERT(apSuite, - VerifyDirtySetContent(AttributePathParams(kTestEndpointId, kTestClusterId), - AttributePathParams(kTestEndpointId + 1, kTestClusterId + 1, 1))); + EXPECT_EQ(CHIP_NO_ERROR, + InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( + AttributePathParams(kTestEndpointId + 1, kTestClusterId + 1, 1))); + EXPECT_TRUE(VerifyDirtySetContent(AttributePathParams(kTestEndpointId, kTestClusterId), + AttributePathParams(kTestEndpointId + 1, kTestClusterId + 1, 1))); InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.ReleaseAll(); @@ -317,15 +318,13 @@ void TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted(nlTest // -> Expected behavior: The existing paths are merged into one single wildcard cluster path. New path is inserted as-is. for (EndpointId i = 1; i <= CHIP_IM_SERVER_MAX_NUM_DIRTY_SET; i++) { - NL_TEST_ASSERT(apSuite, InsertToDirtySet(AttributePathParams(kTestEndpointId, i, 1))); + EXPECT_TRUE(InsertToDirtySet(AttributePathParams(kTestEndpointId, i, 1))); } - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == - InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( - AttributePathParams(kTestEndpointId + 1, kTestClusterId + 1, 1))); - NL_TEST_ASSERT(apSuite, - VerifyDirtySetContent(AttributePathParams(kTestEndpointId, kInvalidClusterId), - AttributePathParams(kTestEndpointId + 1, kTestClusterId + 1, 1))); + EXPECT_EQ(CHIP_NO_ERROR, + InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( + AttributePathParams(kTestEndpointId + 1, kTestClusterId + 1, 1))); + EXPECT_TRUE(VerifyDirtySetContent(AttributePathParams(kTestEndpointId, kInvalidClusterId), + AttributePathParams(kTestEndpointId + 1, kTestClusterId + 1, 1))); InteractionModelEngine::GetInstance()->GetReportingEngine().Shutdown(); } @@ -333,35 +332,3 @@ void TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted(nlTest } // namespace reporting } // namespace app } // namespace chip - -namespace { -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("CheckBuildAndSendSingleReportData", chip::app::reporting::TestReportingEngine::TestBuildAndSendSingleReportData), - NL_TEST_DEF("TestMergeOverlappedAttributePath", chip::app::reporting::TestReportingEngine::TestMergeOverlappedAttributePath), - NL_TEST_DEF("TestMergeAttributePathWhenDirtySetPoolExhausted", chip::app::reporting::TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted), - NL_TEST_SENTINEL() -}; -// clang-format on - -// clang-format off -nlTestSuite sSuite = -{ - "TestReportingEngine", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; -// clang-format on - -} // namespace - -int TestReportingEngine() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestReportingEngine) diff --git a/src/app/tests/TestSimpleSubscriptionResumptionStorage.cpp b/src/app/tests/TestSimpleSubscriptionResumptionStorage.cpp index 9f9b164e87cc07..3d7f5bfd663e18 100644 --- a/src/app/tests/TestSimpleSubscriptionResumptionStorage.cpp +++ b/src/app/tests/TestSimpleSubscriptionResumptionStorage.cpp @@ -105,8 +105,7 @@ TEST_F(TestSimpleSubscriptionResumptionStorage, TestSubscriptionCount) EXPECT_EQ(count, std::make_unsigned_t(CHIP_IM_MAX_NUM_SUBSCRIPTIONS / 2)); // Delete all and verify iterator counts 0 - CHIP_ERROR err = subscriptionStorage.DeleteAll(46); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(subscriptionStorage.DeleteAll(46), CHIP_NO_ERROR); iterator = subscriptionStorage.IterateSubscriptions(); EXPECT_EQ(iterator->Count(), 0u); @@ -129,9 +128,9 @@ TEST_F(TestSimpleSubscriptionResumptionStorage, TestSubscriptionMaxCount) // First set a large MaxCount before Init uint16_t countMaxToSave = 2 * CHIP_IM_MAX_NUM_SUBSCRIPTIONS; - CHIP_ERROR err = storage.SyncSetKeyValue(chip::DefaultStorageKeyAllocator::SubscriptionResumptionMaxCount().KeyName(), - &countMaxToSave, sizeof(uint16_t)); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(storage.SyncSetKeyValue(chip::DefaultStorageKeyAllocator::SubscriptionResumptionMaxCount().KeyName(), &countMaxToSave, + sizeof(uint16_t)), + CHIP_NO_ERROR); // Then write something beyond CHIP_IM_MAX_NUM_SUBSCRIPTIONS chip::Platform::ScopedMemoryBuffer junkBytes; @@ -147,8 +146,8 @@ TEST_F(TestSimpleSubscriptionResumptionStorage, TestSubscriptionMaxCount) // First check the MaxCount is reset to CHIP_IM_MAX_NUM_SUBSCRIPTIONS uint16_t countMax = 0; uint16_t len = sizeof(countMax); - err = storage.SyncGetKeyValue(chip::DefaultStorageKeyAllocator::SubscriptionResumptionMaxCount().KeyName(), &countMax, len); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(storage.SyncGetKeyValue(chip::DefaultStorageKeyAllocator::SubscriptionResumptionMaxCount().KeyName(), &countMax, len), + CHIP_NO_ERROR); EXPECT_EQ(countMax, CHIP_IM_MAX_NUM_SUBSCRIPTIONS); // Then check the fake sub is no more @@ -221,13 +220,9 @@ TEST_F(TestSimpleSubscriptionResumptionStorage, TestSubscriptionState) subscriptionInfo3.mEventPaths[1].mEventId = 8; subscriptionInfo2.mEventPaths[1].mIsUrgentEvent = false; - CHIP_ERROR err; - err = subscriptionStorage.Save(subscriptionInfo1); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = subscriptionStorage.Save(subscriptionInfo2); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = subscriptionStorage.Save(subscriptionInfo3); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(subscriptionStorage.Save(subscriptionInfo1), CHIP_NO_ERROR); + EXPECT_EQ(subscriptionStorage.Save(subscriptionInfo2), CHIP_NO_ERROR); + EXPECT_EQ(subscriptionStorage.Save(subscriptionInfo3), CHIP_NO_ERROR); auto * iterator = subscriptionStorage.IterateSubscriptions(); EXPECT_EQ(iterator->Count(), 3u); @@ -265,8 +260,8 @@ TEST_F(TestSimpleSubscriptionResumptionStorage, TestSubscriptionState) uint16_t countMax = 0; uint16_t len = sizeof(countMax); - err = storage.SyncGetKeyValue(chip::DefaultStorageKeyAllocator::SubscriptionResumptionMaxCount().KeyName(), &countMax, len); - EXPECT_EQ(err, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(storage.SyncGetKeyValue(chip::DefaultStorageKeyAllocator::SubscriptionResumptionMaxCount().KeyName(), &countMax, len), + CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } static constexpr chip::TLV::Tag kTestValue1Tag = chip::TLV::ContextTag(30); diff --git a/src/app/tests/TestTimedHandler.cpp b/src/app/tests/TestTimedHandler.cpp index 64e174a2b9e7d7..2625257781d314 100644 --- a/src/app/tests/TestTimedHandler.cpp +++ b/src/app/tests/TestTimedHandler.cpp @@ -21,16 +21,14 @@ #include #include #include +#include #include -#include -#include #include #include +#include #include #include -#include - using TestContext = chip::Test::AppContext; namespace chip { @@ -39,25 +37,34 @@ namespace app { using namespace Messaging; using namespace Protocols::InteractionModel; -class TestTimedHandler +namespace { + +class TestTimedHandler : public ::testing::Test { public: - static void TestInvokeFastEnough(nlTestSuite * aSuite, void * aContext); - static void TestWriteFastEnough(nlTestSuite * aSuite, void * aContext); + static void SetUpTestSuite() + { - static void TestInvokeTooSlow(nlTestSuite * aSuite, void * aContext); - static void TestWriteTooSlow(nlTestSuite * aSuite, void * aContext); + mpTestContext = new TestContext; + mpTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + delete mpTestContext; + } - static void TestInvokeNeverComes(nlTestSuite * aSuite, void * aContext); + void SetUp() override { mpTestContext->SetUp(); } + void TearDown() override { mpTestContext->TearDown(); } -private: - static void TestFollowingMessageFastEnough(nlTestSuite * aSuite, void * aContext, MsgType aMsgType); - static void TestFollowingMessageTooSlow(nlTestSuite * aSuite, void * aContext, MsgType aMsgType); + static TestContext * mpTestContext; - static void GenerateTimedRequest(nlTestSuite * aSuite, uint16_t aTimeoutValue, System::PacketBufferHandle & aPayload); + static void TestFollowingMessageFastEnough(MsgType aMsgType); + static void TestFollowingMessageTooSlow(MsgType aMsgType); + static void GenerateTimedRequest(uint16_t aTimeoutValue, System::PacketBufferHandle & aPayload); }; -namespace { +TestContext * TestTimedHandler::mpTestContext = nullptr; class TestExchangeDelegate : public Messaging::ExchangeDelegate { @@ -93,97 +100,90 @@ class TestExchangeDelegate : public Messaging::ExchangeDelegate } // anonymous namespace -void TestTimedHandler::GenerateTimedRequest(nlTestSuite * aSuite, uint16_t aTimeoutValue, System::PacketBufferHandle & aPayload) +void TestTimedHandler::GenerateTimedRequest(uint16_t aTimeoutValue, System::PacketBufferHandle & aPayload) { aPayload = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - NL_TEST_ASSERT(aSuite, !aPayload.IsNull()); + ASSERT_FALSE(aPayload.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(aPayload)); TimedRequestMessage::Builder builder; - CHIP_ERROR err = builder.Init(&writer); - NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(builder.Init(&writer), CHIP_NO_ERROR); builder.TimeoutMs(aTimeoutValue); - NL_TEST_ASSERT(aSuite, builder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(builder.GetError(), CHIP_NO_ERROR); - err = writer.Finalize(&aPayload); - NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&aPayload), CHIP_NO_ERROR); } -void TestTimedHandler::TestFollowingMessageFastEnough(nlTestSuite * aSuite, void * aContext, MsgType aMsgType) +void TestTimedHandler::TestFollowingMessageFastEnough(MsgType aMsgType) { - TestContext & ctx = *static_cast(aContext); System::PacketBufferHandle payload; - GenerateTimedRequest(aSuite, 500, payload); + GenerateTimedRequest(500, payload); TestExchangeDelegate delegate; - ExchangeContext * exchange = ctx.NewExchangeToAlice(&delegate); - NL_TEST_ASSERT(aSuite, exchange != nullptr); + ExchangeContext * exchange = mpTestContext->NewExchangeToAlice(&delegate); + ASSERT_NE(exchange, nullptr); - NL_TEST_ASSERT(aSuite, !delegate.mNewMessageReceived); + EXPECT_FALSE(delegate.mNewMessageReceived); delegate.mKeepExchangeOpen = true; - CHIP_ERROR err = exchange->SendMessage(MsgType::TimedRequest, std::move(payload), SendMessageFlags::kExpectResponse); - NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(exchange->SendMessage(MsgType::TimedRequest, std::move(payload), SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(aSuite, delegate.mNewMessageReceived); - NL_TEST_ASSERT(aSuite, delegate.mLastMessageWasStatus); - NL_TEST_ASSERT(aSuite, delegate.mError == CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); + EXPECT_TRUE(delegate.mNewMessageReceived); + EXPECT_TRUE(delegate.mLastMessageWasStatus); + EXPECT_EQ(delegate.mError, CHIP_NO_ERROR); // Send an empty payload, which will error out but not with the // UNSUPPORTED_ACCESS status we expect if we miss our timeout. payload = MessagePacketBuffer::New(0); - NL_TEST_ASSERT(aSuite, !payload.IsNull()); + ASSERT_FALSE(payload.IsNull()); delegate.mKeepExchangeOpen = false; delegate.mNewMessageReceived = false; - err = exchange->SendMessage(aMsgType, std::move(payload), SendMessageFlags::kExpectResponse); - NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(exchange->SendMessage(aMsgType, std::move(payload), SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(aSuite, delegate.mNewMessageReceived); - NL_TEST_ASSERT(aSuite, delegate.mLastMessageWasStatus); - NL_TEST_ASSERT(aSuite, StatusIB(delegate.mError).mStatus != Status::UnsupportedAccess); + mpTestContext->DrainAndServiceIO(); + EXPECT_TRUE(delegate.mNewMessageReceived); + EXPECT_TRUE(delegate.mLastMessageWasStatus); + EXPECT_NE(StatusIB(delegate.mError).mStatus, Status::UnsupportedAccess); } -void TestTimedHandler::TestInvokeFastEnough(nlTestSuite * aSuite, void * aContext) +TEST_F(TestTimedHandler, TestInvokeFastEnough) { - TestFollowingMessageFastEnough(aSuite, aContext, MsgType::InvokeCommandRequest); + TestTimedHandler::TestFollowingMessageFastEnough(MsgType::InvokeCommandRequest); } -void TestTimedHandler::TestWriteFastEnough(nlTestSuite * aSuite, void * aContext) +TEST_F(TestTimedHandler, TestWriteFastEnough) { - TestFollowingMessageFastEnough(aSuite, aContext, MsgType::WriteRequest); + TestFollowingMessageFastEnough(MsgType::WriteRequest); } -void TestTimedHandler::TestFollowingMessageTooSlow(nlTestSuite * aSuite, void * aContext, MsgType aMsgType) +void TestTimedHandler::TestFollowingMessageTooSlow(MsgType aMsgType) { - TestContext & ctx = *static_cast(aContext); System::PacketBufferHandle payload; - GenerateTimedRequest(aSuite, 50, payload); + GenerateTimedRequest(50, payload); TestExchangeDelegate delegate; - ExchangeContext * exchange = ctx.NewExchangeToAlice(&delegate); - NL_TEST_ASSERT(aSuite, exchange != nullptr); + ExchangeContext * exchange = mpTestContext->NewExchangeToAlice(&delegate); + ASSERT_NE(exchange, nullptr); - NL_TEST_ASSERT(aSuite, !delegate.mNewMessageReceived); + EXPECT_FALSE(delegate.mNewMessageReceived); delegate.mKeepExchangeOpen = true; - CHIP_ERROR err = exchange->SendMessage(MsgType::TimedRequest, std::move(payload), SendMessageFlags::kExpectResponse); - NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(exchange->SendMessage(MsgType::TimedRequest, std::move(payload), SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(aSuite, delegate.mNewMessageReceived); - NL_TEST_ASSERT(aSuite, delegate.mLastMessageWasStatus); - NL_TEST_ASSERT(aSuite, delegate.mError == CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); + EXPECT_TRUE(delegate.mNewMessageReceived); + EXPECT_TRUE(delegate.mLastMessageWasStatus); + EXPECT_EQ(delegate.mError, CHIP_NO_ERROR); // Sleep for > 50ms so we miss our time window. chip::test_utils::SleepMillis(75); @@ -191,50 +191,48 @@ void TestTimedHandler::TestFollowingMessageTooSlow(nlTestSuite * aSuite, void * // Send an empty payload, which will error out but not with the // UNSUPPORTED_ACCESS status we expect if we miss our timeout. payload = MessagePacketBuffer::New(0); - NL_TEST_ASSERT(aSuite, !payload.IsNull()); + EXPECT_FALSE(payload.IsNull()); delegate.mKeepExchangeOpen = false; delegate.mNewMessageReceived = false; - err = exchange->SendMessage(aMsgType, std::move(payload), SendMessageFlags::kExpectResponse); - NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(exchange->SendMessage(aMsgType, std::move(payload), SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(aSuite, delegate.mNewMessageReceived); - NL_TEST_ASSERT(aSuite, delegate.mLastMessageWasStatus); - NL_TEST_ASSERT(aSuite, StatusIB(delegate.mError).mStatus == Status::UnsupportedAccess); + mpTestContext->DrainAndServiceIO(); + EXPECT_TRUE(delegate.mNewMessageReceived); + EXPECT_TRUE(delegate.mLastMessageWasStatus); + EXPECT_EQ(StatusIB(delegate.mError).mStatus, Status::UnsupportedAccess); } -void TestTimedHandler::TestInvokeTooSlow(nlTestSuite * aSuite, void * aContext) +TEST_F(TestTimedHandler, TestInvokeTooSlow) { - TestFollowingMessageTooSlow(aSuite, aContext, MsgType::InvokeCommandRequest); + TestFollowingMessageTooSlow(MsgType::InvokeCommandRequest); } -void TestTimedHandler::TestWriteTooSlow(nlTestSuite * aSuite, void * aContext) +// TEST(TestTimedHandler, TestTimedHandler::TestWriteTooSlow) +TEST_F(TestTimedHandler, TestWriteTooSlow) { - TestFollowingMessageTooSlow(aSuite, aContext, MsgType::WriteRequest); + TestFollowingMessageTooSlow(MsgType::WriteRequest); } -void TestTimedHandler::TestInvokeNeverComes(nlTestSuite * aSuite, void * aContext) +TEST_F(TestTimedHandler, TestInvokeNeverComes) { - TestContext & ctx = *static_cast(aContext); System::PacketBufferHandle payload; - GenerateTimedRequest(aSuite, 50, payload); + GenerateTimedRequest(50, payload); TestExchangeDelegate delegate; - ExchangeContext * exchange = ctx.NewExchangeToAlice(&delegate); - NL_TEST_ASSERT(aSuite, exchange != nullptr); + ExchangeContext * exchange = mpTestContext->NewExchangeToAlice(&delegate); + ASSERT_NE(exchange, nullptr); - NL_TEST_ASSERT(aSuite, !delegate.mNewMessageReceived); + EXPECT_FALSE(delegate.mNewMessageReceived); - CHIP_ERROR err = exchange->SendMessage(MsgType::TimedRequest, std::move(payload), SendMessageFlags::kExpectResponse); - NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(exchange->SendMessage(MsgType::TimedRequest, std::move(payload), SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(aSuite, delegate.mNewMessageReceived); - NL_TEST_ASSERT(aSuite, delegate.mLastMessageWasStatus); - NL_TEST_ASSERT(aSuite, delegate.mError == CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); + EXPECT_TRUE(delegate.mNewMessageReceived); + EXPECT_TRUE(delegate.mLastMessageWasStatus); + EXPECT_EQ(delegate.mError, CHIP_NO_ERROR); // Do nothing else; exchange on the server remains open. We are testing to // see whether shutdown cleans it up properly. @@ -242,40 +240,3 @@ void TestTimedHandler::TestInvokeNeverComes(nlTestSuite * aSuite, void * aContex } // namespace app } // namespace chip - -namespace { - -/** - * Test Suite. It lists all the test functions. - */ - -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("TimedHandlerTestInvokeFastEnough", chip::app::TestTimedHandler::TestInvokeFastEnough), - NL_TEST_DEF("TimedHandlerTestInvokeTooSlow", chip::app::TestTimedHandler::TestInvokeTooSlow), - NL_TEST_DEF("TimedHandlerTestInvokeNeverComes", chip::app::TestTimedHandler::TestInvokeNeverComes), - NL_TEST_SENTINEL() -}; -// clang-format on - -// clang-format off -nlTestSuite sSuite = -{ - "TestTimedHandler", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; -// clang-format on - -} // namespace - -int TestTimedHandler() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestTimedHandler) diff --git a/src/app/tests/TestWriteInteraction.cpp b/src/app/tests/TestWriteInteraction.cpp index 7aa2dba303bf0f..3f03b976e2937f 100644 --- a/src/app/tests/TestWriteInteraction.cpp +++ b/src/app/tests/TestWriteInteraction.cpp @@ -16,6 +16,9 @@ * limitations under the License. */ +#include +#include + #include #include #include @@ -25,19 +28,16 @@ #include #include #include +#include #include #include #include #include #include -#include -#include +#include #include #include - -#include -#include -#include +#include namespace { @@ -49,67 +49,70 @@ chip::TestPersistentStorageDelegate gTestStorage; chip::Crypto::DefaultSessionKeystore gSessionKeystore; chip::Credentials::GroupDataProviderImpl gGroupsProvider(kMaxGroupsPerFabric, kMaxGroupKeysPerFabric); -class TestContext : public chip::Test::AppContext +using TestContext = chip::Test::AppContext; + +} // namespace + +namespace chip { +namespace app { +class TestWriteInteraction : public ::testing::Test { public: - // Performs setup for each individual test in the test suite + static void SetUpTestSuite() + { + mpTestContext = new TestContext; + mpTestContext->SetUpTestSuite(); + } + + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + delete mpTestContext; + } void SetUp() override { - chip::Test::AppContext::SetUp(); + + mpTestContext->SetUp(); gTestStorage.ClearStorage(); gGroupsProvider.SetStorageDelegate(&gTestStorage); gGroupsProvider.SetSessionKeystore(&gSessionKeystore); - // TODO: use ASSERT_EQ, once transition to pw_unit_test is complete - VerifyOrDie(gGroupsProvider.Init() == CHIP_NO_ERROR); + ASSERT_EQ(gGroupsProvider.Init(), CHIP_NO_ERROR); chip::Credentials::SetGroupDataProvider(&gGroupsProvider); uint8_t buf[sizeof(chip::CompressedFabricId)]; chip::MutableByteSpan span(buf); - VerifyOrDie(GetBobFabric()->GetCompressedFabricIdBytes(span) == CHIP_NO_ERROR); - VerifyOrDie(chip::GroupTesting::InitData(&gGroupsProvider, GetBobFabricIndex(), span) == CHIP_NO_ERROR); + ASSERT_EQ(mpTestContext->GetBobFabric()->GetCompressedFabricIdBytes(span), CHIP_NO_ERROR); + ASSERT_EQ(chip::GroupTesting::InitData(&gGroupsProvider, mpTestContext->GetBobFabricIndex(), span), CHIP_NO_ERROR); } - - // Performs teardown for each individual test in the test suite void TearDown() override { chip::Credentials::GroupDataProvider * provider = chip::Credentials::GetGroupDataProvider(); if (provider != nullptr) + { provider->Finish(); - chip::Test::AppContext::TearDown(); + } + mpTestContext->TearDown(); } -}; -} // namespace + static TestContext * mpTestContext; -namespace chip { -namespace app { -class TestWriteInteraction -{ -public: - static void TestWriteClient(nlTestSuite * apSuite, void * apContext); - static void TestWriteClientGroup(nlTestSuite * apSuite, void * apContext); - static void TestWriteHandler(nlTestSuite * apSuite, void * apContext); - static void TestWriteRoundtrip(nlTestSuite * apSuite, void * apContext); - static void TestWriteInvalidMessage1(nlTestSuite * apSuite, void * apContext); - static void TestWriteInvalidMessage2(nlTestSuite * apSuite, void * apContext); - static void TestWriteInvalidMessage3(nlTestSuite * apSuite, void * apContext); - static void TestWriteInvalidMessage4(nlTestSuite * apSuite, void * apContext); - static void TestWriteRoundtripWithClusterObjects(nlTestSuite * apSuite, void * apContext); - static void TestWriteRoundtripWithClusterObjectsVersionMatch(nlTestSuite * apSuite, void * apContext); - static void TestWriteRoundtripWithClusterObjectsVersionMismatch(nlTestSuite * apSuite, void * apContext); -#if CONFIG_BUILD_FOR_HOST_UNIT_TEST - static void TestWriteHandlerReceiveInvalidMessage(nlTestSuite * apSuite, void * apContext); - static void TestWriteHandlerInvalidateFabric(nlTestSuite * apSuite, void * apContext); -#endif -private: - static void AddAttributeDataIB(nlTestSuite * apSuite, void * apContext, WriteClient & aWriteClient); - static void AddAttributeStatus(nlTestSuite * apSuite, void * apContext, WriteHandler & aWriteHandler); - static void GenerateWriteRequest(nlTestSuite * apSuite, void * apContext, bool aIsTimedWrite, - System::PacketBufferHandle & aPayload); - static void GenerateWriteResponse(nlTestSuite * apSuite, void * apContext, System::PacketBufferHandle & aPayload); + void TestWriteClient(); + void TestWriteClientGroup(); + void TestWriteHandlerReceiveInvalidMessage(); + void TestWriteInvalidMessage1(); + void TestWriteInvalidMessage2(); + void TestWriteInvalidMessage3(); + void TestWriteInvalidMessage4(); + + static void AddAttributeDataIB(WriteClient & aWriteClient); + static void AddAttributeStatus(WriteHandler & aWriteHandler); + static void GenerateWriteRequest(bool aIsTimedWrite, System::PacketBufferHandle & aPayload); + static void GenerateWriteResponse(System::PacketBufferHandle & aPayload); }; +TestContext * TestWriteInteraction::mpTestContext = nullptr; + class TestExchangeDelegate : public Messaging::ExchangeDelegate { CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * ec, const PayloadHeader & payloadHeader, @@ -146,235 +149,208 @@ class TestWriteClientCallback : public chip::app::WriteClient::Callback CHIP_ERROR mError = CHIP_NO_ERROR; }; -void TestWriteInteraction::AddAttributeDataIB(nlTestSuite * apSuite, void * apContext, WriteClient & aWriteClient) +void TestWriteInteraction::AddAttributeDataIB(WriteClient & aWriteClient) { - CHIP_ERROR err = CHIP_NO_ERROR; AttributePathParams attributePathParams; bool attributeValue = true; attributePathParams.mEndpointId = 2; attributePathParams.mClusterId = 3; attributePathParams.mAttributeId = 4; - err = aWriteClient.EncodeAttribute(attributePathParams, attributeValue); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(aWriteClient.EncodeAttribute(attributePathParams, attributeValue), CHIP_NO_ERROR); } -void TestWriteInteraction::AddAttributeStatus(nlTestSuite * apSuite, void * apContext, WriteHandler & aWriteHandler) +void TestWriteInteraction::AddAttributeStatus(WriteHandler & aWriteHandler) { - CHIP_ERROR err = CHIP_NO_ERROR; ConcreteAttributePath attributePath(2, 3, 4); - err = aWriteHandler.AddStatus(attributePath, Protocols::InteractionModel::Status::Success); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(aWriteHandler.AddStatus(attributePath, Protocols::InteractionModel::Status::Success), CHIP_NO_ERROR); } -void TestWriteInteraction::GenerateWriteRequest(nlTestSuite * apSuite, void * apContext, bool aIsTimedWrite, - System::PacketBufferHandle & aPayload) +void TestWriteInteraction::GenerateWriteRequest(bool aIsTimedWrite, System::PacketBufferHandle & aPayload) { - CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBufferTLVWriter writer; writer.Init(std::move(aPayload)); WriteRequestMessage::Builder writeRequestBuilder; - err = writeRequestBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writeRequestBuilder.Init(&writer), CHIP_NO_ERROR); writeRequestBuilder.TimedRequest(aIsTimedWrite); - NL_TEST_ASSERT(apSuite, writeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(writeRequestBuilder.GetError(), CHIP_NO_ERROR); AttributeDataIBs::Builder & attributeDataIBsBuilder = writeRequestBuilder.CreateWriteRequests(); - NL_TEST_ASSERT(apSuite, writeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(writeRequestBuilder.GetError(), CHIP_NO_ERROR); AttributeDataIB::Builder & attributeDataIBBuilder = attributeDataIBsBuilder.CreateAttributeDataIBBuilder(); - NL_TEST_ASSERT(apSuite, attributeDataIBsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeDataIBsBuilder.GetError(), CHIP_NO_ERROR); attributeDataIBBuilder.DataVersion(0); - NL_TEST_ASSERT(apSuite, attributeDataIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeDataIBBuilder.GetError(), CHIP_NO_ERROR); AttributePathIB::Builder & attributePathBuilder = attributeDataIBBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathBuilder.GetError() == CHIP_NO_ERROR); - err = attributePathBuilder.Node(1) - .Endpoint(2) - .Cluster(3) - .Attribute(4) - .ListIndex(DataModel::Nullable()) - .EndOfAttributePathIB(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder.GetError(), CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder.Node(1) + .Endpoint(2) + .Cluster(3) + .Attribute(4) + .ListIndex(DataModel::Nullable()) + .EndOfAttributePathIB(), + CHIP_NO_ERROR); // Construct attribute data { chip::TLV::TLVWriter * pWriter = attributeDataIBBuilder.GetWriter(); chip::TLV::TLVType dummyType = chip::TLV::kTLVType_NotSpecified; - err = pWriter->StartContainer(chip::TLV::ContextTag(AttributeDataIB::Tag::kData), chip::TLV::kTLVType_Structure, dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ( + pWriter->StartContainer(chip::TLV::ContextTag(AttributeDataIB::Tag::kData), chip::TLV::kTLVType_Structure, dummyType), + CHIP_NO_ERROR); - err = pWriter->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(pWriter->PutBoolean(chip::TLV::ContextTag(1), true), CHIP_NO_ERROR); - err = pWriter->EndContainer(dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(pWriter->EndContainer(dummyType), CHIP_NO_ERROR); } attributeDataIBBuilder.EndOfAttributeDataIB(); - NL_TEST_ASSERT(apSuite, attributeDataIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeDataIBBuilder.GetError(), CHIP_NO_ERROR); attributeDataIBsBuilder.EndOfAttributeDataIBs(); - NL_TEST_ASSERT(apSuite, attributeDataIBsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeDataIBsBuilder.GetError(), CHIP_NO_ERROR); writeRequestBuilder.EndOfWriteRequestMessage(); - NL_TEST_ASSERT(apSuite, writeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(writeRequestBuilder.GetError(), CHIP_NO_ERROR); - err = writer.Finalize(&aPayload); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&aPayload), CHIP_NO_ERROR); } -void TestWriteInteraction::GenerateWriteResponse(nlTestSuite * apSuite, void * apContext, System::PacketBufferHandle & aPayload) +void TestWriteInteraction::GenerateWriteResponse(System::PacketBufferHandle & aPayload) { - CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBufferTLVWriter writer; writer.Init(std::move(aPayload)); WriteResponseMessage::Builder writeResponseBuilder; - err = writeResponseBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writeResponseBuilder.Init(&writer), CHIP_NO_ERROR); AttributeStatusIBs::Builder & attributeStatusesBuilder = writeResponseBuilder.CreateWriteResponses(); - NL_TEST_ASSERT(apSuite, attributeStatusesBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeStatusesBuilder.GetError(), CHIP_NO_ERROR); AttributeStatusIB::Builder & attributeStatusIBBuilder = attributeStatusesBuilder.CreateAttributeStatus(); - NL_TEST_ASSERT(apSuite, attributeStatusIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeStatusIBBuilder.GetError(), CHIP_NO_ERROR); AttributePathIB::Builder & attributePathBuilder = attributeStatusIBBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathBuilder.GetError() == CHIP_NO_ERROR); - err = attributePathBuilder.Node(1) - .Endpoint(2) - .Cluster(3) - .Attribute(4) - .ListIndex(DataModel::Nullable()) - .EndOfAttributePathIB(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder.GetError(), CHIP_NO_ERROR); + EXPECT_EQ(attributePathBuilder.Node(1) + .Endpoint(2) + .Cluster(3) + .Attribute(4) + .ListIndex(DataModel::Nullable()) + .EndOfAttributePathIB(), + CHIP_NO_ERROR); StatusIB::Builder & statusIBBuilder = attributeStatusIBBuilder.CreateErrorStatus(); StatusIB statusIB; statusIB.mStatus = chip::Protocols::InteractionModel::Status::InvalidSubscription; - NL_TEST_ASSERT(apSuite, statusIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(statusIBBuilder.GetError(), CHIP_NO_ERROR); statusIBBuilder.EncodeStatusIB(statusIB); - err = statusIBBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(statusIBBuilder.GetError(), CHIP_NO_ERROR); attributeStatusIBBuilder.EndOfAttributeStatusIB(); - NL_TEST_ASSERT(apSuite, attributeStatusIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeStatusIBBuilder.GetError(), CHIP_NO_ERROR); attributeStatusesBuilder.EndOfAttributeStatuses(); - NL_TEST_ASSERT(apSuite, attributeStatusesBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeStatusesBuilder.GetError(), CHIP_NO_ERROR); writeResponseBuilder.EndOfWriteResponseMessage(); - NL_TEST_ASSERT(apSuite, writeResponseBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(writeResponseBuilder.GetError(), CHIP_NO_ERROR); - err = writer.Finalize(&aPayload); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&aPayload), CHIP_NO_ERROR); } -void TestWriteInteraction::TestWriteClient(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteClient) { - TestContext & ctx = *static_cast(apContext); - - CHIP_ERROR err = CHIP_NO_ERROR; TestWriteClientCallback callback; - app::WriteClient writeClient(&ctx.GetExchangeManager(), &callback, /* aTimedWriteTimeoutMs = */ NullOptional); + app::WriteClient writeClient(&mpTestContext->GetExchangeManager(), &callback, /* aTimedWriteTimeoutMs = */ NullOptional); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - AddAttributeDataIB(apSuite, apContext, writeClient); + AddAttributeDataIB(writeClient); - err = writeClient.SendWriteRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - GenerateWriteResponse(apSuite, apContext, buf); + GenerateWriteResponse(buf); - err = writeClient.ProcessWriteResponseMessage(std::move(buf)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writeClient.ProcessWriteResponseMessage(std::move(buf)), CHIP_NO_ERROR); writeClient.Close(); - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); } -void TestWriteInteraction::TestWriteClientGroup(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteClientGroup) { - TestContext & ctx = *static_cast(apContext); - - CHIP_ERROR err = CHIP_NO_ERROR; TestWriteClientCallback callback; - app::WriteClient writeClient(&ctx.GetExchangeManager(), &callback, /* aTimedWriteTimeoutMs = */ NullOptional); + app::WriteClient writeClient(&mpTestContext->GetExchangeManager(), &callback, /* aTimedWriteTimeoutMs = */ NullOptional); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - AddAttributeDataIB(apSuite, apContext, writeClient); - - SessionHandle groupSession = ctx.GetSessionBobToFriends(); - NL_TEST_ASSERT(apSuite, groupSession->IsGroupSession()); + AddAttributeDataIB(writeClient); - err = writeClient.SendWriteRequest(groupSession); + SessionHandle groupSession = mpTestContext->GetSessionBobToFriends(); + EXPECT_TRUE(groupSession->IsGroupSession()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writeClient.SendWriteRequest(groupSession), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); // The WriteClient should be shutdown once we SendWriteRequest for group. - NL_TEST_ASSERT(apSuite, writeClient.mState == WriteClient::State::AwaitingDestruction); + EXPECT_EQ(writeClient.mState, WriteClient::State::AwaitingDestruction); } -void TestWriteInteraction::TestWriteHandler(nlTestSuite * apSuite, void * apContext) +TEST_F(TestWriteInteraction, TestWriteHandler) { using namespace Protocols::InteractionModel; - TestContext & ctx = *static_cast(apContext); - constexpr bool allBooleans[] = { true, false }; for (auto messageIsTimed : allBooleans) { for (auto transactionIsTimed : allBooleans) { - CHIP_ERROR err = CHIP_NO_ERROR; app::WriteHandler writeHandler; System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - err = writeHandler.Init(chip::app::InteractionModelEngine::GetInstance()); - GenerateWriteRequest(apSuite, apContext, messageIsTimed, buf); + writeHandler.Init(chip::app::InteractionModelEngine::GetInstance()); + + GenerateWriteRequest(messageIsTimed, buf); TestExchangeDelegate delegate; - Messaging::ExchangeContext * exchange = ctx.NewExchangeToBob(&delegate); + Messaging::ExchangeContext * exchange = mpTestContext->NewExchangeToBob(&delegate); Status status = writeHandler.OnWriteRequest(exchange, std::move(buf), transactionIsTimed); if (messageIsTimed == transactionIsTimed) { - NL_TEST_ASSERT(apSuite, status == Status::Success); + EXPECT_EQ(status, Status::Success); } else { - NL_TEST_ASSERT(apSuite, status == Status::UnsupportedAccess); + EXPECT_EQ(status, Status::UnsupportedAccess); } - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); } } } -void TestWriteInteraction::TestWriteRoundtripWithClusterObjects(nlTestSuite * apSuite, void * apContext) +TEST_F(TestWriteInteraction, TestWriteRoundtripWithClusterObjects) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -395,54 +371,52 @@ void TestWriteInteraction::TestWriteRoundtripWithClusterObjects(nlTestSuite * ap // Spec A.11.2 strings SHALL NOT include a terminating null character to mark the end of a string. dataTx.e = chip::Span(charSpanData, strlen(charSpanData)); - writeClient.EncodeAttribute(attributePathParams, dataTx); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writeClient.EncodeAttribute(attributePathParams, dataTx), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 0); + EXPECT_EQ(callback.mOnSuccessCalled, 0); - err = writeClient.SendWriteRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 1); + EXPECT_EQ(callback.mOnSuccessCalled, 1); { app::Clusters::UnitTesting::Structs::SimpleStruct::Type dataRx; TLV::TLVReader reader; reader.Init(chip::Test::attributeDataTLV, chip::Test::attributeDataTLVLen); reader.Next(); - NL_TEST_ASSERT(apSuite, CHIP_NO_ERROR == DataModel::Decode(reader, dataRx)); - NL_TEST_ASSERT(apSuite, dataRx.a == dataTx.a); - NL_TEST_ASSERT(apSuite, dataRx.b == dataTx.b); - NL_TEST_ASSERT(apSuite, dataRx.d.data_equal(dataTx.d)); + EXPECT_EQ(CHIP_NO_ERROR, DataModel::Decode(reader, dataRx)); + EXPECT_EQ(dataRx.a, dataTx.a); + EXPECT_EQ(dataRx.b, dataTx.b); + EXPECT_TRUE(dataRx.d.data_equal(dataTx.d)); // Equals to dataRx.e.size() == dataTx.e.size() && memncmp(dataRx.e.data(), dataTx.e.data(), dataTx.e.size()) == 0 - NL_TEST_ASSERT(apSuite, dataRx.e.data_equal(dataTx.e)); + EXPECT_TRUE(dataRx.e.data_equal(dataTx.e)); } - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 1 && callback.mOnErrorCalled == 0 && callback.mOnDoneCalled == 1); + EXPECT_EQ(callback.mOnSuccessCalled, 1); + EXPECT_EQ(callback.mOnErrorCalled, 0); + EXPECT_EQ(callback.mOnDoneCalled, 1); // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); engine->Shutdown(); } -void TestWriteInteraction::TestWriteRoundtripWithClusterObjectsVersionMatch(nlTestSuite * apSuite, void * apContext) +TEST_F(TestWriteInteraction, TestWriteRoundtripWithClusterObjectsVersionMatch) { - TestContext & ctx = *static_cast(apContext); - - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -457,41 +431,38 @@ void TestWriteInteraction::TestWriteRoundtripWithClusterObjectsVersionMatch(nlTe Optional version(kAcceptedDataVersion); - writeClient.EncodeAttribute(attributePathParams, dataTx, version); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writeClient.EncodeAttribute(attributePathParams, dataTx, version), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 0); + EXPECT_EQ(callback.mOnSuccessCalled, 0); - err = writeClient.SendWriteRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, - callback.mOnSuccessCalled == 1 && callback.mOnErrorCalled == 0 && callback.mOnDoneCalled == 1 && - callback.mStatus.mStatus == Protocols::InteractionModel::Status::Success); + EXPECT_EQ(callback.mOnSuccessCalled, 1); + EXPECT_EQ(callback.mOnErrorCalled, 0); + EXPECT_EQ(callback.mOnDoneCalled, 1); + EXPECT_EQ(callback.mStatus.mStatus, Protocols::InteractionModel::Status::Success); // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); engine->Shutdown(); } -void TestWriteInteraction::TestWriteRoundtripWithClusterObjectsVersionMismatch(nlTestSuite * apSuite, void * apContext) +TEST_F(TestWriteInteraction, TestWriteRoundtripWithClusterObjectsVersionMismatch) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -508,59 +479,59 @@ void TestWriteInteraction::TestWriteRoundtripWithClusterObjectsVersionMismatch(n DataModel::Nullable dataTx; dataTx.SetNonNull(dataTxValue); Optional version(chip::Test::kRejectedDataVersion); - writeClient.EncodeAttribute(attributePathParams, dataTx, version); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 0); + EXPECT_EQ(writeClient.EncodeAttribute(attributePathParams, dataTx, version), CHIP_NO_ERROR); + + EXPECT_EQ(callback.mOnSuccessCalled, 0); - err = writeClient.SendWriteRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, - callback.mOnSuccessCalled == 1 && callback.mOnErrorCalled == 0 && callback.mOnDoneCalled == 1 && - callback.mStatus.mStatus == Protocols::InteractionModel::Status::DataVersionMismatch); + EXPECT_EQ(callback.mOnSuccessCalled, 1); + EXPECT_EQ(callback.mOnErrorCalled, 0); + EXPECT_EQ(callback.mOnDoneCalled, 1); + EXPECT_EQ(callback.mStatus.mStatus, Protocols::InteractionModel::Status::DataVersionMismatch); // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); engine->Shutdown(); } -void TestWriteInteraction::TestWriteRoundtrip(nlTestSuite * apSuite, void * apContext) +TEST_F(TestWriteInteraction, TestWriteRoundtrip) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - AddAttributeDataIB(apSuite, apContext, writeClient); - - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 0 && callback.mOnErrorCalled == 0 && callback.mOnDoneCalled == 0); + AddAttributeDataIB(writeClient); - err = writeClient.SendWriteRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(callback.mOnSuccessCalled, 0); + EXPECT_EQ(callback.mOnErrorCalled, 0); + EXPECT_EQ(callback.mOnDoneCalled, 0); - ctx.DrainAndServiceIO(); + EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 1 && callback.mOnErrorCalled == 0 && callback.mOnDoneCalled == 1); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(callback.mOnSuccessCalled, 1); + EXPECT_EQ(callback.mOnErrorCalled, 0); + EXPECT_EQ(callback.mOnDoneCalled, 1); // By now we should have closed all exchanges and sent all pending acks, so // there should be no queued-up things in the retransmit table. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); engine->Shutdown(); } @@ -568,200 +539,160 @@ void TestWriteInteraction::TestWriteRoundtrip(nlTestSuite * apSuite, void * apCo // This test creates a chunked write request, we drop the second write chunk message, then write handler receives unknown // report message and sends out a status report with invalid action. #if CONFIG_BUILD_FOR_HOST_UNIT_TEST -void TestWriteInteraction::TestWriteHandlerReceiveInvalidMessage(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteHandlerReceiveInvalidMessage) { - TestContext & ctx = *static_cast(apContext); - auto sessionHandle = ctx.GetSessionBobToAlice(); + auto sessionHandle = mpTestContext->GetSessionBobToAlice(); app::AttributePathParams attributePath(2, 3, 4); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback writeCallback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); // Reserve all except the last 128 bytes, so that we make sure to chunk. - app::WriteClient writeClient(&ctx.GetExchangeManager(), &writeCallback, Optional::Missing(), + app::WriteClient writeClient(&mpTestContext->GetExchangeManager(), &writeCallback, Optional::Missing(), static_cast(kMaxSecureSduLengthBytes - 128) /* reserved buffer size */); ByteSpan list[5]; - err = writeClient.EncodeAttribute(attributePath, app::DataModel::List(list, 5)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writeClient.EncodeAttribute(attributePath, app::DataModel::List(list, 5)), CHIP_NO_ERROR); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 2; - err = writeClient.SendWriteRequest(sessionHandle); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 2; + EXPECT_EQ(writeClient.SendWriteRequest(sessionHandle), CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers() == 1); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 3); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + EXPECT_EQ(InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 1u); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 3u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); ReportDataMessage::Builder response; response.Init(&writer); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::ReportData); auto * writeHandler = InteractionModelEngine::GetInstance()->ActiveWriteHandlerAt(0); + rm->ClearRetransTable(writeClient.mExchangeCtx.Get()); rm->ClearRetransTable(writeHandler->mExchangeCtx.Get()); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; writeHandler->OnMessageReceived(writeHandler->mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, writeCallback.mLastErrorReason.mStatus == Protocols::InteractionModel::Status::InvalidAction); - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers() == 0); + EXPECT_EQ(writeCallback.mLastErrorReason.mStatus, Protocols::InteractionModel::Status::InvalidAction); + EXPECT_EQ(InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 0u); engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // This test is to create Chunked write requests, we drop the message since the 3rd message, then remove fabrics for client and // handler, the corresponding client and handler would be released as well. -void TestWriteInteraction::TestWriteHandlerInvalidateFabric(nlTestSuite * apSuite, void * apContext) +TEST_F(TestWriteInteraction, TestWriteHandlerInvalidateFabric) { - TestContext & ctx = *static_cast(apContext); - auto sessionHandle = ctx.GetSessionBobToAlice(); + auto sessionHandle = mpTestContext->GetSessionBobToAlice(); app::AttributePathParams attributePath(2, 3, 4); - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback writeCallback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); // Reserve all except the last 128 bytes, so that we make sure to chunk. - app::WriteClient writeClient(&ctx.GetExchangeManager(), &writeCallback, Optional::Missing(), + app::WriteClient writeClient(&mpTestContext->GetExchangeManager(), &writeCallback, Optional::Missing(), static_cast(kMaxSecureSduLengthBytes - 128) /* reserved buffer size */); ByteSpan list[5]; - err = writeClient.EncodeAttribute(attributePath, app::DataModel::List(list, 5)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(writeClient.EncodeAttribute(attributePath, app::DataModel::List(list, 5)), CHIP_NO_ERROR); - ctx.GetLoopback().mDroppedMessageCount = 0; - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 2; - err = writeClient.SendWriteRequest(sessionHandle); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 2; + EXPECT_EQ(writeClient.SendWriteRequest(sessionHandle), CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers() == 1); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 3); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + EXPECT_EQ(InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 1u); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 3u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); - ctx.GetFabricTable().Delete(ctx.GetAliceFabricIndex()); - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers() == 0); + mpTestContext->GetFabricTable().Delete(mpTestContext->GetAliceFabricIndex()); + EXPECT_EQ(InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 0u); engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateAliceFabric(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateAliceFabric(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } #endif -/** - * Helper macro we can use to pretend we got a reply from the server in cases - * when the reply was actually dropped due to us not wanting the client's state - * machine to advance. - * - * When this macro is used, the client has sent a message and is waiting for an - * ack+response, and the server has sent a response that got dropped and is - * waiting for an ack (and maybe a response). - * - * What this macro then needs to do is: - * - * 1. Pretend that the client got an ack (and clear out the corresponding ack - * state). - * 2. Pretend that the client got a message from the server, with the id of the - * message that was dropped, which requires an ack, so the client will send - * that ack in its next message. - * - * This is a macro so we get useful line numbers on assertion failures - */ -#define PretendWeGotReplyFromServer(aSuite, aContext, aClientExchange) \ - { \ - Messaging::ReliableMessageMgr * localRm = (aContext).GetExchangeManager().GetReliableMessageMgr(); \ - Messaging::ExchangeContext * localExchange = aClientExchange; \ - NL_TEST_ASSERT(aSuite, localRm->TestGetCountRetransTable() == 2); \ - \ - localRm->ClearRetransTable(localExchange); \ - NL_TEST_ASSERT(aSuite, localRm->TestGetCountRetransTable() == 1); \ - \ - localRm->EnumerateRetransTable([localExchange](auto * entry) { \ - localExchange->SetPendingPeerAckMessageCounter(entry->retainedBuf.GetMessageCounter()); \ - return Loop::Break; \ - }); \ - } - // Write Client sends a write request, receives an unexpected message type, sends a status response to that. -void TestWriteInteraction::TestWriteInvalidMessage1(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage1) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - AddAttributeDataIB(apSuite, apContext, writeClient); + AddAttributeDataIB(writeClient); - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 0 && callback.mOnErrorCalled == 0 && callback.mOnDoneCalled == 0); + EXPECT_EQ(callback.mOnSuccessCalled, 0); + EXPECT_EQ(callback.mOnErrorCalled, 0); + EXPECT_EQ(callback.mOnDoneCalled, 0); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = writeClient.SendWriteRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); ReportDataMessage::Builder response; response.Init(&writer); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::ReportData); @@ -769,70 +700,72 @@ void TestWriteInteraction::TestWriteInvalidMessage1(nlTestSuite * apSuite, void // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, writeClient.mExchangeCtx.Get()); - - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = writeClient.OnMessageReceived(writeClient.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_INVALID_MESSAGE_TYPE); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, callback.mError == CHIP_ERROR_INVALID_MESSAGE_TYPE); - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 0 && callback.mOnErrorCalled == 1 && callback.mOnDoneCalled == 1); + PretendWeGotReplyFromServer(*mpTestContext, writeClient.mExchangeCtx.Get()); + + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + EXPECT_EQ(writeClient.OnMessageReceived(writeClient.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), + CHIP_ERROR_INVALID_MESSAGE_TYPE); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(callback.mError, CHIP_ERROR_INVALID_MESSAGE_TYPE); + + EXPECT_EQ(callback.mOnSuccessCalled, 0); + EXPECT_EQ(callback.mOnErrorCalled, 1); + EXPECT_EQ(callback.mOnDoneCalled, 1); // TODO: Check that the server gets the right status. // Client sents status report with invalid action, server's exchange has been closed, so all it sends is an MRP Ack - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Write Client sends a write request, receives a malformed write response message, sends a Status Report. -void TestWriteInteraction::TestWriteInvalidMessage2(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage2) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - AddAttributeDataIB(apSuite, apContext, writeClient); + AddAttributeDataIB(writeClient); - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 0 && callback.mOnErrorCalled == 0 && callback.mOnDoneCalled == 0); + EXPECT_EQ(callback.mOnSuccessCalled, 0); + EXPECT_EQ(callback.mOnErrorCalled, 0); + EXPECT_EQ(callback.mOnDoneCalled, 0); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = writeClient.SendWriteRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); WriteResponseMessage::Builder response; response.Init(&writer); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::WriteResponse); @@ -840,69 +773,71 @@ void TestWriteInteraction::TestWriteInvalidMessage2(nlTestSuite * apSuite, void // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, writeClient.mExchangeCtx.Get()); - - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = writeClient.OnMessageReceived(writeClient.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_END_OF_TLV); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, callback.mError == CHIP_ERROR_END_OF_TLV); - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 0 && callback.mOnErrorCalled == 1 && callback.mOnDoneCalled == 1); + PretendWeGotReplyFromServer(*mpTestContext, writeClient.mExchangeCtx.Get()); + + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + EXPECT_EQ(writeClient.OnMessageReceived(writeClient.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), + CHIP_ERROR_END_OF_TLV); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(callback.mError, CHIP_ERROR_END_OF_TLV); + + EXPECT_EQ(callback.mOnSuccessCalled, 0); + EXPECT_EQ(callback.mOnErrorCalled, 1); + EXPECT_EQ(callback.mOnDoneCalled, 1); // Client sents status report with invalid action, server's exchange has been closed, so all it sends is an MRP Ack - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Write Client sends a write request, receives a malformed status response message. -void TestWriteInteraction::TestWriteInvalidMessage3(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage3) { - TestContext & ctx = *static_cast(apContext); - - CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - AddAttributeDataIB(apSuite, apContext, writeClient); + AddAttributeDataIB(writeClient); - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 0 && callback.mOnErrorCalled == 0 && callback.mOnDoneCalled == 0); + EXPECT_EQ(callback.mOnSuccessCalled, 0); + EXPECT_EQ(callback.mOnErrorCalled, 0); + EXPECT_EQ(callback.mOnDoneCalled, 0); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = writeClient.SendWriteRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); StatusResponseMessage::Builder response; response.Init(&writer); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::StatusResponse); @@ -910,71 +845,73 @@ void TestWriteInteraction::TestWriteInvalidMessage3(nlTestSuite * apSuite, void // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, writeClient.mExchangeCtx.Get()); - - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = writeClient.OnMessageReceived(writeClient.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_END_OF_TLV); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, callback.mError == CHIP_ERROR_END_OF_TLV); - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 0 && callback.mOnErrorCalled == 1 && callback.mOnDoneCalled == 1); + PretendWeGotReplyFromServer(*mpTestContext, writeClient.mExchangeCtx.Get()); + + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + EXPECT_EQ(writeClient.OnMessageReceived(writeClient.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), + CHIP_ERROR_END_OF_TLV); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(callback.mError, CHIP_ERROR_END_OF_TLV); + + EXPECT_EQ(callback.mOnSuccessCalled, 0); + EXPECT_EQ(callback.mOnErrorCalled, 1); + EXPECT_EQ(callback.mOnDoneCalled, 1); // TODO: Check that the server gets the right status // Client sents status report with invalid action, server's exchange has been closed, so all it sends is an MRP ack. - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } // Write Client sends a write request, receives a busy status response message. -void TestWriteInteraction::TestWriteInvalidMessage4(nlTestSuite * apSuite, void * apContext) +TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage4) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - AddAttributeDataIB(apSuite, apContext, writeClient); + AddAttributeDataIB(writeClient); - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 0 && callback.mOnErrorCalled == 0 && callback.mOnDoneCalled == 0); + EXPECT_EQ(callback.mOnSuccessCalled, 0); + EXPECT_EQ(callback.mOnErrorCalled, 0); + EXPECT_EQ(callback.mOnDoneCalled, 0); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 1; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = writeClient.SendWriteRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); - NL_TEST_ASSERT(apSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); System::PacketBufferTLVWriter writer; writer.Init(std::move(msgBuf)); StatusResponseMessage::Builder response; response.Init(&writer); response.Status(Protocols::InteractionModel::Status::Busy); - NL_TEST_ASSERT(apSuite, writer.Finalize(&msgBuf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::StatusResponse); @@ -982,74 +919,31 @@ void TestWriteInteraction::TestWriteInvalidMessage4(nlTestSuite * apSuite, void // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(apSuite, ctx, writeClient.mExchangeCtx.Get()); - - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; - err = writeClient.OnMessageReceived(writeClient.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)); - NL_TEST_ASSERT(apSuite, err == CHIP_IM_GLOBAL_STATUS(Busy)); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, callback.mError == CHIP_IM_GLOBAL_STATUS(Busy)); - NL_TEST_ASSERT(apSuite, callback.mOnSuccessCalled == 0 && callback.mOnErrorCalled == 1 && callback.mOnDoneCalled == 1); + PretendWeGotReplyFromServer(*mpTestContext, writeClient.mExchangeCtx.Get()); + + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + EXPECT_EQ(writeClient.OnMessageReceived(writeClient.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), + CHIP_IM_GLOBAL_STATUS(Busy)); + mpTestContext->DrainAndServiceIO(); + EXPECT_EQ(callback.mError, CHIP_IM_GLOBAL_STATUS(Busy)); + + EXPECT_EQ(callback.mOnSuccessCalled, 0); + EXPECT_EQ(callback.mOnErrorCalled, 1); + EXPECT_EQ(callback.mOnDoneCalled, 1); // TODO: Check that the server gets the right status.. // Client sents status report with invalid action, server's exchange has been closed, so it just sends an MRP ack. - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); engine->Shutdown(); - ctx.ExpireSessionAliceToBob(); - ctx.ExpireSessionBobToAlice(); - ctx.CreateSessionAliceToBob(); - ctx.CreateSessionBobToAlice(); + mpTestContext->ExpireSessionAliceToBob(); + mpTestContext->ExpireSessionBobToAlice(); + mpTestContext->CreateSessionAliceToBob(); + mpTestContext->CreateSessionBobToAlice(); } } // namespace app } // namespace chip - -namespace { - -/** - * Test Suite. It lists all the test functions. - */ - -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("CheckWriteClient", chip::app::TestWriteInteraction::TestWriteClient), - NL_TEST_DEF("CheckWriteClientGroup", chip::app::TestWriteInteraction::TestWriteClientGroup), - NL_TEST_DEF("CheckWriteHandler", chip::app::TestWriteInteraction::TestWriteHandler), - NL_TEST_DEF("CheckWriteRoundtrip", chip::app::TestWriteInteraction::TestWriteRoundtrip), - NL_TEST_DEF("TestWriteRoundtripWithClusterObjects", chip::app::TestWriteInteraction::TestWriteRoundtripWithClusterObjects), - NL_TEST_DEF("TestWriteRoundtripWithClusterObjectsVersionMatch", chip::app::TestWriteInteraction::TestWriteRoundtripWithClusterObjectsVersionMatch), - NL_TEST_DEF("TestWriteRoundtripWithClusterObjectsVersionMismatch", chip::app::TestWriteInteraction::TestWriteRoundtripWithClusterObjectsVersionMismatch), -#if CONFIG_BUILD_FOR_HOST_UNIT_TEST - NL_TEST_DEF("TestWriteHandlerReceiveInvalidMessage", chip::app::TestWriteInteraction::TestWriteHandlerReceiveInvalidMessage), - NL_TEST_DEF("TestWriteHandlerInvalidateFabric", chip::app::TestWriteInteraction::TestWriteHandlerInvalidateFabric), -#endif - NL_TEST_DEF("TestWriteInvalidMessage1", chip::app::TestWriteInteraction::TestWriteInvalidMessage1), - NL_TEST_DEF("TestWriteInvalidMessage2", chip::app::TestWriteInteraction::TestWriteInvalidMessage2), - NL_TEST_DEF("TestWriteInvalidMessage3", chip::app::TestWriteInteraction::TestWriteInvalidMessage3), - NL_TEST_DEF("TestWriteInvalidMessage4", chip::app::TestWriteInteraction::TestWriteInvalidMessage4), - NL_TEST_SENTINEL() -}; -// clang-format on - -nlTestSuite sSuite = { - "TestWriteInteraction", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; - -} // namespace - -int TestWriteInteraction() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestWriteInteraction) diff --git a/src/app/tests/test-interaction-model-api.h b/src/app/tests/test-interaction-model-api.h index 88e861b267b63b..a4f91add7f42f8 100644 --- a/src/app/tests/test-interaction-model-api.h +++ b/src/app/tests/test-interaction-model-api.h @@ -26,19 +26,55 @@ #include #include +/** + * Helper macro we can use to pretend we got a reply from the server in cases + * when the reply was actually dropped due to us not wanting the client's state + * machine to advance. + * + * When this macro is used, the client has sent a message and is waiting for an + * ack+response, and the server has sent a response that got dropped and is + * waiting for an ack (and maybe a response). + * + * What this macro then needs to do is: + * + * 1. Pretend that the client got an ack (and clear out the corresponding ack + * state). + * 2. Pretend that the client got a message from the server, with the id of the + * message that was dropped, which requires an ack, so the client will send + * that ack in its next message. + * + * a macro was chosen so that we get useful line numbers on assertion failures + * + * This macro is used by the code in TestWriteInteraction.cpp, TestReadInteraction.cpp + * and TestCommandInteraction.cpp + */ +#define PretendWeGotReplyFromServer(aContext, aClientExchange) \ + { \ + Messaging::ReliableMessageMgr * localRm = (aContext).GetExchangeManager().GetReliableMessageMgr(); \ + Messaging::ExchangeContext * localExchange = aClientExchange; \ + EXPECT_EQ(localRm->TestGetCountRetransTable(), 2); \ + \ + localRm->ClearRetransTable(localExchange); \ + EXPECT_EQ(localRm->TestGetCountRetransTable(), 1); \ + \ + localRm->EnumerateRetransTable([localExchange](auto * entry) { \ + localExchange->SetPendingPeerAckMessageCounter(entry->retainedBuf.GetMessageCounter()); \ + return Loop::Break; \ + }); \ + } + namespace chip { namespace Test { -constexpr chip::ClusterId kTestDeniedClusterId1 = 1000; -constexpr chip::ClusterId kTestDeniedClusterId2 = 3; - -constexpr chip::ClusterId kTestClusterId = 6; -constexpr uint8_t kTestFieldValue1 = 1; -constexpr chip::EndpointId kTestEndpointId = 1; -constexpr chip::DataVersion kTestDataVersion1 = 3; - +constexpr chip::ClusterId kTestDeniedClusterId1 = 1000; +constexpr chip::ClusterId kTestDeniedClusterId2 = 3; +constexpr chip::ClusterId kTestClusterId = 6; +constexpr uint8_t kTestFieldValue1 = 1; +constexpr chip::EndpointId kTestEndpointId = 1; +constexpr chip::DataVersion kTestDataVersion1 = 3; constexpr chip::DataVersion kRejectedDataVersion = 1; + extern uint8_t attributeDataTLV[CHIP_CONFIG_DEFAULT_UDP_MTU_SIZE]; extern size_t attributeDataTLVLen; diff --git a/src/test_driver/openiotsdk/unit-tests/CMakeLists.txt b/src/test_driver/openiotsdk/unit-tests/CMakeLists.txt index 10e55deb8ef06f..76247fb31c71e4 100644 --- a/src/test_driver/openiotsdk/unit-tests/CMakeLists.txt +++ b/src/test_driver/openiotsdk/unit-tests/CMakeLists.txt @@ -42,44 +42,13 @@ include(linker) add_subdirectory(${OPEN_IOT_SDK_EXAMPLE_COMMON}/app ./app_build) file(STRINGS test_components.txt TEST_NAMES_FROM_FILE) -# TODO [PW_MIGRATION] Remove the following variable once the migration to pw_unit_test is complete. -file(STRINGS test_components_nl.txt TEST_NAMES_FROM_FILE_NL) + target_compile_definitions(openiotsdk-startup PRIVATE IOT_SDK_APP_MAIN_STACK_SIZE=20480 ) -# TODO [PW_MIGRATION] Remove the following targets once the migration to pw_unit_test is complete. -foreach(TEST_NAME IN LISTS TEST_NAMES_FROM_FILE_NL) - set(APP_TARGET ${TEST_NAME}_ns) - add_executable(${APP_TARGET}) - target_include_directories(${APP_TARGET} - PRIVATE - main/include - ${CHIP_ROOT}/third_party/nlunit-test/repo/src - ) - - target_sources(${APP_TARGET} - PRIVATE - main/main_ns_nl.cpp - ) - - target_link_libraries(${APP_TARGET} - openiotsdk-startup - openiotsdk-app - ) - - # Link the *whole-archives* to keep the static test objects. - target_link_options(${APP_TARGET} - PUBLIC - -Wl,--whole-archive "${CMAKE_CURRENT_BINARY_DIR}/chip_build/lib/lib${TEST_NAME}.a" - -Wl,--no-whole-archive) - - set_target_link(${APP_TARGET}) - sdk_post_build(${APP_TARGET}) -endforeach() - foreach(TEST_NAME IN LISTS TEST_NAMES_FROM_FILE) set(APP_TARGET ${TEST_NAME}_ns) add_executable(${APP_TARGET}) diff --git a/src/test_driver/openiotsdk/unit-tests/main/main_ns_nl.cpp b/src/test_driver/openiotsdk/unit-tests/main/main_ns_nl.cpp deleted file mode 100644 index f7e511b8d183cf..00000000000000 --- a/src/test_driver/openiotsdk/unit-tests/main/main_ns_nl.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* - * - * Copyright (c) 2024 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. - */ - -#include -#include - -#include "openiotsdk_platform.h" -#include -#include -#include - -constexpr nl_test_output_logger_t NlTestLogger::nl_test_logger; - -using namespace ::chip; - -int main() -{ - if (openiotsdk_platform_init()) - { - ChipLogAutomation("ERROR: Open IoT SDK platform initialization failed"); - return EXIT_FAILURE; - } - - nlTestSetLogger(&NlTestLogger::nl_test_logger); - - ChipLogAutomation("Open IoT SDK unit-tests start"); - - if (openiotsdk_network_init(true)) - { - ChipLogAutomation("ERROR: Network initialization failed"); - return EXIT_FAILURE; - } - - ChipLogAutomation("Open IoT SDK unit-tests run..."); - int status = RunRegisteredUnitTests(); - ChipLogAutomation("Test status: %d", status); - ChipLogAutomation("Open IoT SDK unit-tests completed"); - - return EXIT_SUCCESS; -} diff --git a/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt b/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt deleted file mode 100644 index 6c038b398d914f..00000000000000 --- a/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt +++ /dev/null @@ -1 +0,0 @@ -AppTestsNL \ No newline at end of file