From ab4ce0a48e07f871f9516c9eb600e84bf67f6f12 Mon Sep 17 00:00:00 2001 From: AYA Date: Thu, 2 May 2024 17:22:27 +0200 Subject: [PATCH 01/22] TestReportingEnginer failure to link ember --- src/BUILD.gn | 1 + src/app/tests/BUILD.gn | 27 ++- src/app/tests/TestReportingEngine.cpp | 243 ++++++++++++++------------ 3 files changed, 157 insertions(+), 114 deletions(-) diff --git a/src/BUILD.gn b/src/BUILD.gn index 8fedfa15e43fd8..c526e0469bf061 100644 --- a/src/BUILD.gn +++ b/src/BUILD.gn @@ -96,6 +96,7 @@ if (chip_build_tests) { tests += [ # TODO(#10447): App test has HF on EFR32. "${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 49196f2fdaaf8f..b624883a4d07ff 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -15,6 +15,7 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") import("//build_overrides/nlunit_test.gni") +import("//build_overrides/pigweed.gni") import("${chip_root}/build/chip/chip_test_suite.gni") import("${chip_root}/src/app/icd/icd.gni") @@ -120,9 +121,32 @@ source_set("operational-state-test-srcs") { ] } -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libAppTests" + test_sources = [ "TestReportingEngine.cpp" ] + + cflags = [ "-Wconversion" ] + + public_deps = [ + ":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_test_suite_using_nltest("tests_nltest") { + output_name = "libAppTestsNL" + test_sources = [ "TestAclEvent.cpp", "TestAttributeAccessInterfaceCache.cpp", @@ -152,7 +176,6 @@ chip_test_suite_using_nltest("tests") { "TestPendingResponseTrackerImpl.cpp", "TestPowerSourceCluster.cpp", "TestReadInteraction.cpp", - "TestReportingEngine.cpp", "TestStatusIB.cpp", "TestStatusResponseMessage.cpp", "TestTestEventTriggerDelegate.cpp", diff --git a/src/app/tests/TestReportingEngine.cpp b/src/app/tests/TestReportingEngine.cpp index 618a2e892e789b..87b8f16423fa6b 100644 --- a/src/app/tests/TestReportingEngine.cpp +++ b/src/app/tests/TestReportingEngine.cpp @@ -22,6 +22,10 @@ * */ +#include + +#include + #include #include #include @@ -32,14 +36,9 @@ #include #include #include -#include -#include #include #include -#include -#include - using TestContext = chip::Test::AppContext; namespace chip { @@ -51,12 +50,56 @@ constexpr chip::AttributeId kTestFieldId2 = 2; namespace app { namespace reporting { -class TestReportingEngine +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() + { + ASSERT_EQ((LoopbackMessagingContext::SetUpTestSuite()), CHIP_NO_ERROR); + ASSERT_EQ((chip::DeviceLayer::PlatformMgr().InitChipStack()), CHIP_NO_ERROR); + } + + static void TearDownTestSuite() + { + chip::DeviceLayer::PlatformMgr().Shutdown(); + LoopbackMessagingContext::TearDownTestSuite(); + } + + void SetUp() + { + ASSERT_EQ((LoopbackMessagingContext::SetUp()), CHIP_NO_ERROR); + + ASSERT_EQ((app::InteractionModelEngine::GetInstance()->Init(&GetExchangeManager(), &GetFabricTable(), + app::reporting::GetDefaultReportScheduler())), + CHIP_NO_ERROR); + + Access::SetAccessControl(gPermissiveAccessControl); + ASSERT_EQ( + (Access::GetAccessControl().Init(chip::Access::Examples::GetPermissiveAccessControlDelegate(), + gDeviceTypeResolver)), CHIP_NO_ERROR); + } + + void TearDown() + { + Access::GetAccessControl().Finish(); + Access::ResetAccessControlToDefault(); + chip::app::InteractionModelEngine::GetInstance()->Shutdown(); + LoopbackMessagingContext::TearDown(); + } */ + + static void SetUpTestSuite() { ASSERT_EQ((ctx.SetUpTestSuite()), CHIP_NO_ERROR); } + static void TearDownTestSuite() { ctx.TearDownTestSuite(); } + void SetUp() { ASSERT_EQ((ctx.SetUp()), CHIP_NO_ERROR); } + void TearDown() { ctx.TearDown(); } + + static TestContext mAppContext; + static TestContext ctx; + // static chip::Test::LoopbackTransportManager mLoopbackTransportManager; + // chip::Test::MessagingContext mMessagingContext; + + static void TestBuildAndSendSingleReportData(); + static void TestMergeOverlappedAttributePath(); + static void TestMergeAttributePathWhenDirtySetPoolExhausted(); private: static bool InsertToDirtySet(const AttributePathParams & aPath); @@ -104,6 +147,11 @@ class TestReportingEngine } }; +// chip::Test::LoopbackTransportManager TestReportingEngine::mLoopbackTransportManager; +TestContext TestReportingEngine::ctx; + +TestContext TestReportingEngine::mAppContext; + class TestExchangeDelegate : public Messaging::ExchangeDelegate { CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * ec, const PayloadHeader & payloadHeader, @@ -126,10 +174,10 @@ class DummyDelegate : public ReadHandler::ManagementCallback } }; -void TestReportingEngine::TestBuildAndSendSingleReportData(nlTestSuite * apSuite, void * apContext) +void TestReportingEngine::TestBuildAndSendSingleReportData() { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + // TestContext & ctx = *static_cast(this); + CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBufferTLVWriter writer; System::PacketBufferHandle readRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); ReadRequestMessage::Builder readRequestBuilder; @@ -137,31 +185,31 @@ void TestReportingEngine::TestBuildAndSendSingleReportData(nlTestSuite * apSuite err = InteractionModelEngine::GetInstance()->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); TestExchangeDelegate delegate; Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(&delegate); writer.Init(std::move(readRequestbuf)); err = readRequestBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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); + EXPECT_EQ(readRequestBuilder.GetError(), CHIP_NO_ERROR); err = writer.Finalize(&readRequestbuf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); app::ReadHandler readHandler(dummy, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, app::reporting::GetDefaultReportScheduler()); readHandler.OnInitialRequest(std::move(readRequestbuf)); @@ -169,16 +217,16 @@ void TestReportingEngine::TestBuildAndSendSingleReportData(nlTestSuite * apSuite ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void TestReportingEngine::TestMergeOverlappedAttributePath(nlTestSuite * apSuite, void * apContext) +void 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); + // TestContext & ctx = *static_cast(this); + CHIP_ERROR err = CHIP_NO_ERROR; + err = InteractionModelEngine::GetInstance()->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, CHIP_NO_ERROR); AttributePathParams * clusterInfo = InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.CreateObject(); clusterInfo->mEndpointId = 1; @@ -190,8 +238,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 +246,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 +254,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,11 +270,9 @@ 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(); } @@ -244,13 +286,13 @@ bool TestReportingEngine::InsertToDirtySet(const AttributePathParams & aPath) return true; } -void TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted(nlTestSuite * apSuite, void * apContext) +void 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); + // TestContext & ctx = *static_cast(this); + CHIP_ERROR err = CHIP_NO_ERROR; + err = InteractionModelEngine::GetInstance()->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, CHIP_NO_ERROR); InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.ReleaseAll(); InteractionModelEngine::GetInstance()->GetReportingEngine().BumpDirtySetGeneration(); @@ -259,13 +301,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 +314,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 +327,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,51 +355,32 @@ 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(); } -} // namespace reporting -} // namespace app -} // namespace chip - -namespace { -// clang-format off -const nlTest sTests[] = +TEST_F(TestReportingEngine, TestBuildAndSendSingleReportData) { - 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 + TestReportingEngine::TestBuildAndSendSingleReportData(); +} -// clang-format off -nlTestSuite sSuite = +TEST_F(TestReportingEngine, TestMergeOverlappedAttributePath) { - "TestReportingEngine", - &sTests[0], - TestContext::nlTestSetUpTestSuite, - TestContext::nlTestTearDownTestSuite, - TestContext::nlTestSetUp, - TestContext::nlTestTearDown, -}; -// clang-format on - -} // namespace + TestReportingEngine::TestMergeOverlappedAttributePath(); +} -int TestReportingEngine() +TEST_F(TestReportingEngine, TestMergeAttributePathWhenDirtySetPoolExhausted) { - return chip::ExecuteTestsWithContext(&sSuite); + TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted(); } -CHIP_REGISTER_TEST_SUITE(TestReportingEngine) +} // namespace reporting +} // namespace app +} // namespace chip From 304f3e87b2b66d715429d5110bad134aab71ee6a Mon Sep 17 00:00:00 2001 From: AYA Date: Tue, 7 May 2024 14:45:45 +0200 Subject: [PATCH 02/22] making TestContext dynamically allocated --- src/app/tests/TestReportingEngine.cpp | 50 +++++++++++++++++---------- 1 file changed, 32 insertions(+), 18 deletions(-) diff --git a/src/app/tests/TestReportingEngine.cpp b/src/app/tests/TestReportingEngine.cpp index 87b8f16423fa6b..afd4d289a930c9 100644 --- a/src/app/tests/TestReportingEngine.cpp +++ b/src/app/tests/TestReportingEngine.cpp @@ -50,6 +50,9 @@ constexpr chip::AttributeId kTestFieldId2 = 2; namespace app { namespace reporting { + +std::unique_ptr pTestContext; + class TestReportingEngine : public ::testing::Test { public: @@ -87,15 +90,29 @@ class TestReportingEngine : public ::testing::Test LoopbackMessagingContext::TearDown(); } */ - static void SetUpTestSuite() { ASSERT_EQ((ctx.SetUpTestSuite()), CHIP_NO_ERROR); } - static void TearDownTestSuite() { ctx.TearDownTestSuite(); } - void SetUp() { ASSERT_EQ((ctx.SetUp()), CHIP_NO_ERROR); } - void TearDown() { ctx.TearDown(); } + static void SetUpTestSuite() + { + if (pTestContext == nullptr) + { + pTestContext = std::make_unique(); + ASSERT_NE(pTestContext, nullptr); + } + pTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + pTestContext->TearDownTestSuite(); + if (pTestContext != nullptr) + { + pTestContext.reset(); + } + } + void SetUp() { pTestContext->SetUp(); } + void TearDown() { pTestContext->TearDown(); } - static TestContext mAppContext; - static TestContext ctx; - // static chip::Test::LoopbackTransportManager mLoopbackTransportManager; - // chip::Test::MessagingContext mMessagingContext; + // static TestContext ctx; + // static chip::Test::LoopbackTransportManager mLoopbackTransportManager; + // chip::Test::MessagingContext mMessagingContext; static void TestBuildAndSendSingleReportData(); static void TestMergeOverlappedAttributePath(); @@ -148,9 +165,6 @@ class TestReportingEngine : public ::testing::Test }; // chip::Test::LoopbackTransportManager TestReportingEngine::mLoopbackTransportManager; -TestContext TestReportingEngine::ctx; - -TestContext TestReportingEngine::mAppContext; class TestExchangeDelegate : public Messaging::ExchangeDelegate { @@ -183,11 +197,11 @@ void TestReportingEngine::TestBuildAndSendSingleReportData() ReadRequestMessage::Builder readRequestBuilder; DummyDelegate dummy; - err = InteractionModelEngine::GetInstance()->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), + err = InteractionModelEngine::GetInstance()->Init(&pTestContext->GetExchangeManager(), &pTestContext->GetFabricTable(), app::reporting::GetDefaultReportScheduler()); EXPECT_EQ(err, CHIP_NO_ERROR); TestExchangeDelegate delegate; - Messaging::ExchangeContext * exchangeCtx = ctx.NewExchangeToAlice(&delegate); + Messaging::ExchangeContext * exchangeCtx = pTestContext->NewExchangeToAlice(&delegate); writer.Init(std::move(readRequestbuf)); err = readRequestBuilder.Init(&writer); @@ -215,7 +229,7 @@ void TestReportingEngine::TestBuildAndSendSingleReportData() readHandler.OnInitialRequest(std::move(readRequestbuf)); err = InteractionModelEngine::GetInstance()->GetReportingEngine().BuildAndSendSingleReportData(&readHandler); - ctx.DrainAndServiceIO(); + pTestContext->DrainAndServiceIO(); EXPECT_EQ(err, CHIP_NO_ERROR); } @@ -224,8 +238,8 @@ void TestReportingEngine::TestMergeOverlappedAttributePath() { // TestContext & ctx = *static_cast(this); CHIP_ERROR err = CHIP_NO_ERROR; - err = InteractionModelEngine::GetInstance()->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), - app::reporting::GetDefaultReportScheduler()); + err = InteractionModelEngine::GetInstance()->Init(&pTestContext->GetExchangeManager(), &pTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); EXPECT_EQ(err, CHIP_NO_ERROR); AttributePathParams * clusterInfo = InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.CreateObject(); @@ -290,8 +304,8 @@ void TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted() { // TestContext & ctx = *static_cast(this); CHIP_ERROR err = CHIP_NO_ERROR; - err = InteractionModelEngine::GetInstance()->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), - app::reporting::GetDefaultReportScheduler()); + err = InteractionModelEngine::GetInstance()->Init(&pTestContext->GetExchangeManager(), &pTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); EXPECT_EQ(err, CHIP_NO_ERROR); InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.ReleaseAll(); From f3c23e5ac18ed064f2366e8e273f6b270b383cfe Mon Sep 17 00:00:00 2001 From: AYA Date: Wed, 8 May 2024 13:03:10 +0200 Subject: [PATCH 03/22] Adding *TestAccess Classes to allow access to private Members of tested functions --- src/app/ReadHandler.h | 11 +- src/app/reporting/Engine.h | 5 + src/app/tests/BUILD.gn | 4 + src/app/tests/EngineTestAccess.h | 67 ++++++++ src/app/tests/ReadHandlerTestAccess.h | 51 ++++++ src/app/tests/TestReportingEngine.cpp | 235 +++++++++++--------------- 6 files changed, 231 insertions(+), 142 deletions(-) create mode 100644 src/app/tests/EngineTestAccess.h create mode 100644 src/app/tests/ReadHandlerTestAccess.h diff --git a/src/app/ReadHandler.h b/src/app/ReadHandler.h index a30f1f8974ad25..db6b6cfe983bb6 100644 --- a/src/app/ReadHandler.h +++ b/src/app/ReadHandler.h @@ -56,6 +56,12 @@ inline constexpr uint16_t kSubscriptionMaxIntervalPublisherLimit = 3600; // seconds (60 minutes) namespace chip { + +// Forward declaration of ReadHandlerTestAccess class to allow it to be friend with the ReadHandler. +// This is not for general API use. It is only to be used for (Unit) Tests to expose private Methods/Members. +namespace Test { +class ReadHandlerTestAccess; +} namespace app { // @@ -124,14 +130,14 @@ class ReadHandler : public Messaging::ExchangeDelegate /* * Called after a subscription has been fully established. */ - virtual void OnSubscriptionEstablished(ReadHandler & aReadHandler){}; + virtual void OnSubscriptionEstablished(ReadHandler & aReadHandler) {}; /* * Called right before a subscription is about to get terminated. This is only called on subscriptions that were terminated * after they had been fully established (and therefore had called OnSubscriptionEstablished). * OnSubscriptionEstablishment(). */ - virtual void OnSubscriptionTerminated(ReadHandler & aReadHandler){}; + virtual void OnSubscriptionTerminated(ReadHandler & aReadHandler) {}; }; /* @@ -426,6 +432,7 @@ class ReadHandler : public Messaging::ExchangeDelegate friend class TestReadInteraction; friend class chip::app::reporting::TestReportingEngine; friend class chip::app::reporting::TestReportScheduler; + friend class chip::Test::ReadHandlerTestAccess; // // The engine needs to be able to Abort/Close a ReadHandler instance upon completion of work for a given read/subscribe diff --git a/src/app/reporting/Engine.h b/src/app/reporting/Engine.h index 0bf7a9f83de1ae..56a73eedd118ca 100644 --- a/src/app/reporting/Engine.h +++ b/src/app/reporting/Engine.h @@ -38,6 +38,10 @@ #include namespace chip { +namespace Test { +class EngineTestAccess; + +} namespace app { class InteractionModelEngine; @@ -148,6 +152,7 @@ class Engine friend class TestReportingEngine; friend class ::chip::app::TestReadInteraction; + friend class ::chip::Test::EngineTestAccess; bool IsRunScheduled() const { return mRunScheduled; } diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index b624883a4d07ff..d61660fc61680a 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -126,6 +126,10 @@ chip_test_suite("tests") { test_sources = [ "TestReportingEngine.cpp" ] + sources = [ + "EngineTestAccess.h", + "ReadHandlerTestAccess.h", + ] cflags = [ "-Wconversion" ] public_deps = [ diff --git a/src/app/tests/EngineTestAccess.h b/src/app/tests/EngineTestAccess.h new file mode 100644 index 00000000000000..18d6851e87aea3 --- /dev/null +++ b/src/app/tests/EngineTestAccess.h @@ -0,0 +1,67 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +using namespace chip::app::reporting; + +namespace chip { +namespace Test { + +/** + * @brief Class acts as an accessor to private methods of the Engine class without needing to give friend access to + * each individual test. + * This is not a Global API and should only be used for (Unit) Testing. + */ +class EngineTestAccess +{ +public: + EngineTestAccess(Engine * aEngine) : pEngine(aEngine) {} + + CHIP_ERROR BuildAndSendSingleReportData(chip::app::ReadHandler * apReadHandler) + { + return pEngine->BuildAndSendSingleReportData(apReadHandler); + } + + Engine * GetEngine() { return pEngine; } + + ObjectPool & + GetGlobalDirtySet() + { + return pEngine->mGlobalDirtySet; + } + + bool MergeOverlappedAttributePath(const chip::app::AttributePathParams & aAttributePath) + { + return pEngine->MergeOverlappedAttributePath(aAttributePath); + } + + inline void BumpDirtySetGeneration() { pEngine->BumpDirtySetGeneration(); } + + CHIP_ERROR InsertPathIntoDirtySet(const chip::app::AttributePathParams & aAttributePath) + { + return pEngine->InsertPathIntoDirtySet(aAttributePath); + } + +private: + Engine * pEngine = nullptr; +}; + +} // namespace Test +} // namespace chip diff --git a/src/app/tests/ReadHandlerTestAccess.h b/src/app/tests/ReadHandlerTestAccess.h new file mode 100644 index 00000000000000..b76d722639b4d0 --- /dev/null +++ b/src/app/tests/ReadHandlerTestAccess.h @@ -0,0 +1,51 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +using namespace chip::app; + +namespace chip { +namespace Test { + +/** + * @brief Class acts as an accessor to private methods of the ReadHandler class without needing to give friend access to + * each individual test. + * This is not a Global API and should only be used for (Unit) Testing. + */ +class ReadHandlerTestAccess +{ +public: + ReadHandlerTestAccess(ReadHandler * aReadHandler) : pReadHandler(aReadHandler) {} + + void OnInitialRequest(System::PacketBufferHandle && aPayload) + { + if (pReadHandler != nullptr) + { + pReadHandler->OnInitialRequest(std::move(aPayload)); + } + } + ReadHandler * GetReadHandler() { return pReadHandler; } + +private: + ReadHandler * pReadHandler = nullptr; +}; + +} // namespace Test +} // namespace chip diff --git a/src/app/tests/TestReportingEngine.cpp b/src/app/tests/TestReportingEngine.cpp index afd4d289a930c9..18eecde2a0bf8f 100644 --- a/src/app/tests/TestReportingEngine.cpp +++ b/src/app/tests/TestReportingEngine.cpp @@ -26,6 +26,9 @@ #include +#include +#include + #include #include #include @@ -56,40 +59,6 @@ std::unique_ptr pTestContext; class TestReportingEngine : public ::testing::Test { public: - /* static void SetUpTestSuite() - { - ASSERT_EQ((LoopbackMessagingContext::SetUpTestSuite()), CHIP_NO_ERROR); - ASSERT_EQ((chip::DeviceLayer::PlatformMgr().InitChipStack()), CHIP_NO_ERROR); - } - - static void TearDownTestSuite() - { - chip::DeviceLayer::PlatformMgr().Shutdown(); - LoopbackMessagingContext::TearDownTestSuite(); - } - - void SetUp() - { - ASSERT_EQ((LoopbackMessagingContext::SetUp()), CHIP_NO_ERROR); - - ASSERT_EQ((app::InteractionModelEngine::GetInstance()->Init(&GetExchangeManager(), &GetFabricTable(), - app::reporting::GetDefaultReportScheduler())), - CHIP_NO_ERROR); - - Access::SetAccessControl(gPermissiveAccessControl); - ASSERT_EQ( - (Access::GetAccessControl().Init(chip::Access::Examples::GetPermissiveAccessControlDelegate(), - gDeviceTypeResolver)), CHIP_NO_ERROR); - } - - void TearDown() - { - Access::GetAccessControl().Finish(); - Access::ResetAccessControlToDefault(); - chip::app::InteractionModelEngine::GetInstance()->Shutdown(); - LoopbackMessagingContext::TearDown(); - } */ - static void SetUpTestSuite() { if (pTestContext == nullptr) @@ -110,62 +79,18 @@ class TestReportingEngine : public ::testing::Test void SetUp() { pTestContext->SetUp(); } void TearDown() { pTestContext->TearDown(); } - // static TestContext ctx; - // static chip::Test::LoopbackTransportManager mLoopbackTransportManager; - // chip::Test::MessagingContext mMessagingContext; - - static void TestBuildAndSendSingleReportData(); - static void TestMergeOverlappedAttributePath(); - static void TestMergeAttributePathWhenDirtySetPoolExhausted(); - -private: + template + static bool VerifyDirtySetContent(const Args &... args); static bool InsertToDirtySet(const AttributePathParams & aPath); +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; - } }; -// chip::Test::LoopbackTransportManager TestReportingEngine::mLoopbackTransportManager; - class TestExchangeDelegate : public Messaging::ExchangeDelegate { CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * ec, const PayloadHeader & payloadHeader, @@ -188,9 +113,53 @@ class DummyDelegate : public ReadHandler::ManagementCallback } }; -void TestReportingEngine::TestBuildAndSendSingleReportData() +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(TestReportingEngine, TestBuildAndSendSingleReportData) { - // TestContext & ctx = *static_cast(this); CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBufferTLVWriter writer; System::PacketBufferHandle readRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); @@ -226,33 +195,38 @@ void TestReportingEngine::TestBuildAndSendSingleReportData() EXPECT_EQ(err, 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); + chip::Test::ReadHandlerTestAccess privatereadHandler(&readHandler); + privatereadHandler.OnInitialRequest(std::move(readRequestbuf)); + + err = chip::Test::EngineTestAccess(&(InteractionModelEngine::GetInstance()->GetReportingEngine())) + .BuildAndSendSingleReportData(privatereadHandler.GetReadHandler()); pTestContext->DrainAndServiceIO(); EXPECT_EQ(err, CHIP_NO_ERROR); } -void TestReportingEngine::TestMergeOverlappedAttributePath() +TEST_F(TestReportingEngine, TestMergeOverlappedAttributePath) { - // TestContext & ctx = *static_cast(this); CHIP_ERROR err = CHIP_NO_ERROR; err = InteractionModelEngine::GetInstance()->Init(&pTestContext->GetExchangeManager(), &pTestContext->GetFabricTable(), app::reporting::GetDefaultReportScheduler()); EXPECT_EQ(err, CHIP_NO_ERROR); - AttributePathParams * clusterInfo = InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.CreateObject(); - clusterInfo->mEndpointId = 1; - clusterInfo->mClusterId = 1; - clusterInfo->mAttributeId = 1; + AttributePathParams * clusterInfo = chip::Test::EngineTestAccess(&(InteractionModelEngine::GetInstance()->GetReportingEngine())) + .GetGlobalDirtySet() + .CreateObject(); + clusterInfo->mEndpointId = 1; + clusterInfo->mClusterId = 1; + clusterInfo->mAttributeId = 1; { AttributePathParams testClusterInfo; testClusterInfo.mEndpointId = 1; testClusterInfo.mClusterId = 1; testClusterInfo.mAttributeId = 3; - EXPECT_FALSE(InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); + EXPECT_FALSE(chip::Test::EngineTestAccess(&(InteractionModelEngine::GetInstance()->GetReportingEngine())) + .MergeOverlappedAttributePath(testClusterInfo)); } { AttributePathParams testClusterInfo; @@ -260,7 +234,8 @@ void TestReportingEngine::TestMergeOverlappedAttributePath() testClusterInfo.mClusterId = 1; testClusterInfo.mAttributeId = 1; testClusterInfo.mListIndex = 2; - EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); + EXPECT_TRUE(chip::Test::EngineTestAccess(&(InteractionModelEngine::GetInstance()->GetReportingEngine())) + .MergeOverlappedAttributePath(testClusterInfo)); } { @@ -268,14 +243,16 @@ void TestReportingEngine::TestMergeOverlappedAttributePath() testClusterInfo.mEndpointId = 1; testClusterInfo.mClusterId = 1; testClusterInfo.mAttributeId = kInvalidAttributeId; - EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); + EXPECT_TRUE(chip::Test::EngineTestAccess(&(InteractionModelEngine::GetInstance()->GetReportingEngine())) + .MergeOverlappedAttributePath(testClusterInfo)); } { AttributePathParams testClusterInfo; testClusterInfo.mClusterId = kInvalidClusterId; testClusterInfo.mAttributeId = kInvalidAttributeId; - EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); + EXPECT_TRUE(chip::Test::EngineTestAccess(&(InteractionModelEngine::GetInstance()->GetReportingEngine())) + .MergeOverlappedAttributePath(testClusterInfo)); EXPECT_TRUE(clusterInfo->mClusterId == kInvalidClusterId && clusterInfo->mAttributeId == kInvalidAttributeId); } @@ -284,32 +261,23 @@ void TestReportingEngine::TestMergeOverlappedAttributePath() testClusterInfo.mEndpointId = kInvalidEndpointId; testClusterInfo.mClusterId = kInvalidClusterId; testClusterInfo.mAttributeId = kInvalidAttributeId; - EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().MergeOverlappedAttributePath(testClusterInfo)); + EXPECT_TRUE(chip::Test::EngineTestAccess(&(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() +TEST_F(TestReportingEngine, TestMergeAttributePathWhenDirtySetPoolExhausted) { - // TestContext & ctx = *static_cast(this); CHIP_ERROR err = CHIP_NO_ERROR; err = InteractionModelEngine::GetInstance()->Init(&pTestContext->GetExchangeManager(), &pTestContext->GetFabricTable(), app::reporting::GetDefaultReportScheduler()); EXPECT_EQ(err, CHIP_NO_ERROR); - InteractionModelEngine::GetInstance()->GetReportingEngine().mGlobalDirtySet.ReleaseAll(); - InteractionModelEngine::GetInstance()->GetReportingEngine().BumpDirtySetGeneration(); + chip::Test::EngineTestAccess(&(InteractionModelEngine::GetInstance()->GetReportingEngine())).GetGlobalDirtySet().ReleaseAll(); + chip::Test::EngineTestAccess(&(InteractionModelEngine::GetInstance()->GetReportingEngine())).BumpDirtySetGeneration(); // Case 1: All dirty paths including the new one are under the same cluster. // -> Expected behavior: The dirty set is replaced by a wildcard attribute path under the same cluster. @@ -317,12 +285,13 @@ void TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted() { EXPECT_TRUE(InsertToDirtySet(AttributePathParams(kTestEndpointId, kTestClusterId, i))); } - EXPECT_EQ(CHIP_NO_ERROR, - InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( - AttributePathParams(kTestEndpointId, kTestClusterId, CHIP_IM_SERVER_MAX_NUM_DIRTY_SET + 1))); + EXPECT_EQ( + CHIP_NO_ERROR, + chip::Test::EngineTestAccess(&(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(); + chip::Test::EngineTestAccess(&(InteractionModelEngine::GetInstance()->GetReportingEngine())).GetGlobalDirtySet().ReleaseAll(); // Case 2: All dirty paths including the new one are under the same endpoint. // -> Expected behavior: The dirty set is replaced by a wildcard cluster path under the same endpoint. @@ -330,12 +299,13 @@ void TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted() { EXPECT_TRUE(InsertToDirtySet(AttributePathParams(kTestEndpointId, i, 1))); } - EXPECT_EQ(CHIP_NO_ERROR, - InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( - AttributePathParams(kTestEndpointId, ClusterId(CHIP_IM_SERVER_MAX_NUM_DIRTY_SET + 1), 1))); + EXPECT_EQ( + CHIP_NO_ERROR, + chip::Test::EngineTestAccess(&(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(); + chip::Test::EngineTestAccess(&(InteractionModelEngine::GetInstance()->GetReportingEngine())).GetGlobalDirtySet().ReleaseAll(); // Case 3: All dirty paths including the new one are under the different endpoints. // -> Expected behavior: The dirty set is replaced by a wildcard endpoint. @@ -344,11 +314,11 @@ void TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted() EXPECT_TRUE(InsertToDirtySet(AttributePathParams(EndpointId(i), i, i))); } EXPECT_EQ(CHIP_NO_ERROR, - InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( - AttributePathParams(EndpointId(CHIP_IM_SERVER_MAX_NUM_DIRTY_SET + 1), 1, 1))); + chip::Test::EngineTestAccess(&(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(); + chip::Test::EngineTestAccess(&(InteractionModelEngine::GetInstance()->GetReportingEngine())).GetGlobalDirtySet().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 @@ -358,12 +328,12 @@ void TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted() EXPECT_TRUE(InsertToDirtySet(AttributePathParams(kTestEndpointId, kTestClusterId, i))); } EXPECT_EQ(CHIP_NO_ERROR, - InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( - AttributePathParams(kTestEndpointId + 1, kTestClusterId + 1, 1))); + chip::Test::EngineTestAccess(&(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(); + chip::Test::EngineTestAccess(&(InteractionModelEngine::GetInstance()->GetReportingEngine())).GetGlobalDirtySet().ReleaseAll(); // Case 5: All existing dirty paths are under the same endpoint, the new path comes from another endpoint. // -> Expected behavior: The existing paths are merged into one single wildcard cluster path. New path is inserted as-is. @@ -372,29 +342,14 @@ void TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted() EXPECT_TRUE(InsertToDirtySet(AttributePathParams(kTestEndpointId, i, 1))); } EXPECT_EQ(CHIP_NO_ERROR, - InteractionModelEngine::GetInstance()->GetReportingEngine().InsertPathIntoDirtySet( - AttributePathParams(kTestEndpointId + 1, kTestClusterId + 1, 1))); + chip::Test::EngineTestAccess(&(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(); } -TEST_F(TestReportingEngine, TestBuildAndSendSingleReportData) -{ - TestReportingEngine::TestBuildAndSendSingleReportData(); -} - -TEST_F(TestReportingEngine, TestMergeOverlappedAttributePath) -{ - TestReportingEngine::TestMergeOverlappedAttributePath(); -} - -TEST_F(TestReportingEngine, TestMergeAttributePathWhenDirtySetPoolExhausted) -{ - TestReportingEngine::TestMergeAttributePathWhenDirtySetPoolExhausted(); -} - } // namespace reporting } // namespace app } // namespace chip From 9a4fd058bbad01992b44d01045fbdc7c226b2156 Mon Sep 17 00:00:00 2001 From: AYA Date: Wed, 8 May 2024 15:44:01 +0200 Subject: [PATCH 04/22] namespace fix --- src/app/tests/EngineTestAccess.h | 12 ++++++------ src/app/tests/ReadHandlerTestAccess.h | 9 ++++----- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/src/app/tests/EngineTestAccess.h b/src/app/tests/EngineTestAccess.h index 18d6851e87aea3..8823ba3f980e73 100644 --- a/src/app/tests/EngineTestAccess.h +++ b/src/app/tests/EngineTestAccess.h @@ -19,8 +19,6 @@ #include -using namespace chip::app::reporting; - namespace chip { namespace Test { @@ -31,17 +29,19 @@ namespace Test { */ class EngineTestAccess { + public: - EngineTestAccess(Engine * aEngine) : pEngine(aEngine) {} + EngineTestAccess(chip::app::reporting::Engine * aEngine) : pEngine(aEngine) {} CHIP_ERROR BuildAndSendSingleReportData(chip::app::ReadHandler * apReadHandler) { return pEngine->BuildAndSendSingleReportData(apReadHandler); } - Engine * GetEngine() { return pEngine; } + chip::app::reporting::Engine * GetEngine() { return pEngine; } - ObjectPool & + ObjectPool & GetGlobalDirtySet() { return pEngine->mGlobalDirtySet; @@ -60,7 +60,7 @@ class EngineTestAccess } private: - Engine * pEngine = nullptr; + chip::app::reporting::Engine * pEngine = nullptr; }; } // namespace Test diff --git a/src/app/tests/ReadHandlerTestAccess.h b/src/app/tests/ReadHandlerTestAccess.h index b76d722639b4d0..886bec70dc9ff9 100644 --- a/src/app/tests/ReadHandlerTestAccess.h +++ b/src/app/tests/ReadHandlerTestAccess.h @@ -19,8 +19,6 @@ #include -using namespace chip::app; - namespace chip { namespace Test { @@ -31,8 +29,9 @@ namespace Test { */ class ReadHandlerTestAccess { + public: - ReadHandlerTestAccess(ReadHandler * aReadHandler) : pReadHandler(aReadHandler) {} + ReadHandlerTestAccess(chip::app::ReadHandler * aReadHandler) : pReadHandler(aReadHandler) {} void OnInitialRequest(System::PacketBufferHandle && aPayload) { @@ -41,10 +40,10 @@ class ReadHandlerTestAccess pReadHandler->OnInitialRequest(std::move(aPayload)); } } - ReadHandler * GetReadHandler() { return pReadHandler; } + chip::app::ReadHandler * GetReadHandler() { return pReadHandler; } private: - ReadHandler * pReadHandler = nullptr; + chip::app::ReadHandler * pReadHandler = nullptr; }; } // namespace Test From c1c8084965c9ffe547d911fce92827143a562de7 Mon Sep 17 00:00:00 2001 From: AYA Date: Tue, 14 May 2024 10:42:39 +0200 Subject: [PATCH 05/22] Migrating App Tests - not linking --- src/BUILD.gn | 1 + src/app/CommandHandler.h | 4 + src/app/CommandSender.h | 5 + src/app/tests/BUILD.gn | 54 +- src/app/tests/CommandHandlerTestAccess.h | 57 + src/app/tests/CommandSenderTestAccess.h | 62 + src/app/tests/TestAclAttribute.cpp | 138 +- src/app/tests/TestBuilderParser.cpp | 80 +- src/app/tests/TestCommandInteraction.cpp | 1519 ++++++++--------- src/app/tests/TestMessageDef.cpp | 1278 +++++++------- src/app/tests/TestNullable.cpp | 195 +-- src/app/tests/TestStatusIB.cpp | 125 +- src/app/tests/TestStatusResponseMessage.cpp | 90 +- src/app/tests/TestTimedHandler.cpp | 207 ++- src/messaging/ReliableMessageContext.h | 4 + .../tests/ReliableMessageContextTestAccess.h | 48 + 16 files changed, 1868 insertions(+), 1999 deletions(-) create mode 100644 src/app/tests/CommandHandlerTestAccess.h create mode 100644 src/app/tests/CommandSenderTestAccess.h create mode 100644 src/messaging/tests/ReliableMessageContextTestAccess.h diff --git a/src/BUILD.gn b/src/BUILD.gn index d1dfcc7856135e..b24036c1a3783a 100644 --- a/src/BUILD.gn +++ b/src/BUILD.gn @@ -96,6 +96,7 @@ if (chip_build_tests) { tests += [ # TODO(#10447): App test has HF on EFR32. "${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/CommandHandler.h b/src/app/CommandHandler.h index cce19879a6c8a9..716226515ad9cc 100644 --- a/src/app/CommandHandler.h +++ b/src/app/CommandHandler.h @@ -55,6 +55,9 @@ #include namespace chip { +namespace Test { +class CommandHandlerTestAccess; +} namespace app { class CommandHandler @@ -445,6 +448,7 @@ class CommandHandler private: friend class TestCommandInteraction; friend class CommandHandler::Handle; + friend class chip::Test::CommandHandlerTestAccess; enum class State : uint8_t { diff --git a/src/app/CommandSender.h b/src/app/CommandSender.h index 25603b3a1f3787..a42043cddf9fbf 100644 --- a/src/app/CommandSender.h +++ b/src/app/CommandSender.h @@ -51,6 +51,10 @@ #define COMMON_STATUS_SUCCESS 0 namespace chip { +namespace Test { +class CommandSenderTestAccess; + +} namespace app { class CommandSender final : public Messaging::ExchangeDelegate @@ -491,6 +495,7 @@ class CommandSender final : public Messaging::ExchangeDelegate private: friend class TestCommandInteraction; + friend class chip::Test::CommandSenderTestAccess; enum class State : uint8_t { diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index 49196f2fdaaf8f..9319f39732f2cc 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -15,6 +15,7 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") import("//build_overrides/nlunit_test.gni") +import("//build_overrides/pigweed.gni") import("${chip_root}/build/chip/chip_test_suite.gni") import("${chip_root}/src/app/icd/icd.gni") @@ -120,9 +121,44 @@ source_set("operational-state-test-srcs") { ] } -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libAppTests" + sources = [ "CommandSenderTestAccess.h" ] + test_sources = [ + "TestBuilderParser.cpp", + "TestCommandInteraction.cpp", + "TestMessageDef.cpp", + "TestNullable.cpp", + "TestStatusIB.cpp", + "TestStatusResponseMessage.cpp", + "TestTimedHandler.cpp", + ] + + test_sources += [ "TestAclAttribute.cpp" ] + cflags = [ "-Wconversion" ] + + public_deps = [ + ":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", + ] +} + +chip_test_suite_using_nltest("tests_nltest") { + output_name = "libAppTestsNL" + test_sources = [ "TestAclEvent.cpp", "TestAttributeAccessInterfaceCache.cpp", @@ -132,9 +168,7 @@ chip_test_suite_using_nltest("tests") { "TestAttributeValueEncoder.cpp", "TestBasicCommandPathRegistry.cpp", "TestBindingTable.cpp", - "TestBuilderParser.cpp", "TestClusterInfo.cpp", - "TestCommandInteraction.cpp", "TestCommandPathParams.cpp", "TestConcreteAttributePath.cpp", "TestDataModelSerialization.cpp", @@ -144,8 +178,6 @@ chip_test_suite_using_nltest("tests") { "TestEventPathParams.cpp", "TestFabricScopedEventLogging.cpp", "TestInteractionModelEngine.cpp", - "TestMessageDef.cpp", - "TestNullable.cpp", "TestNumericAttributeTraits.cpp", "TestOperationalStateClusterObjects.cpp", "TestPendingNotificationMap.cpp", @@ -153,11 +185,8 @@ chip_test_suite_using_nltest("tests") { "TestPowerSourceCluster.cpp", "TestReadInteraction.cpp", "TestReportingEngine.cpp", - "TestStatusIB.cpp", - "TestStatusResponseMessage.cpp", "TestTestEventTriggerDelegate.cpp", "TestTimeSyncDataProvider.cpp", - "TestTimedHandler.cpp", "TestWriteInteraction.cpp", ] @@ -165,8 +194,6 @@ chip_test_suite_using_nltest("tests") { test_sources += [ "TestFailSafeContext.cpp" ] } - test_sources += [ "TestAclAttribute.cpp" ] - # DefaultICDClientStorage assumes that raw AES key is used by the application if (chip_crypto != "psa") { test_sources += [ "TestDefaultICDClientStorage.cpp" ] @@ -243,3 +270,10 @@ chip_test_suite_using_nltest("tests") { test_sources += [ "TestSimpleSubscriptionResumptionStorage.cpp" ] } } + +group("test_migration") { + deps = [ + ":tests", + ":tests_nltest", + ] +} diff --git a/src/app/tests/CommandHandlerTestAccess.h b/src/app/tests/CommandHandlerTestAccess.h new file mode 100644 index 00000000000000..e800e5266d0605 --- /dev/null +++ b/src/app/tests/CommandHandlerTestAccess.h @@ -0,0 +1,57 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +namespace chip { +namespace Test { + +/** + * @brief Class acts as an accessor to private methods of the CommandHandler class without needing to give friend access to + * each individual test. + * This is not a Global API and should only be used for (Unit) Testing. + */ +class CommandHandlerTestAccess +{ + +public: + CommandHandlerTestAccess(app::CommandHandler * aCommandHandler) : pCommandHandler(aCommandHandler) {} + + bool TestOnlyIsInIdleState() { return pCommandHandler->TestOnlyIsInIdleState(); } + + Protocols::InteractionModel::Status ProcessInvokeRequest(System::PacketBufferHandle && payload, bool isTimedInvoke) + { + return pCommandHandler->ProcessInvokeRequest(std::move(payload), isTimedInvoke); + } + + void SetReserveSpaceForMoreChunkMessages(bool aReserveSpaceForMoreChunkMessages) + { + pCommandHandler->mReserveSpaceForMoreChunkMessages = aReserveSpaceForMoreChunkMessages; + } + + app::InvokeResponseMessage::Builder & GetInvokeResponseBuilder() { return pCommandHandler->mInvokeResponseBuilder; } + + app::CommandHandlerExchangeInterface * GetmpResponder() { return pCommandHandler->mpResponder; } + +private: + app::CommandHandler * pCommandHandler = nullptr; +}; + +} // namespace Test +} // namespace chip diff --git a/src/app/tests/CommandSenderTestAccess.h b/src/app/tests/CommandSenderTestAccess.h new file mode 100644 index 00000000000000..b07837ce1447ca --- /dev/null +++ b/src/app/tests/CommandSenderTestAccess.h @@ -0,0 +1,62 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +namespace chip { +namespace Test { + +/** + * @brief Class acts as an accessor to private methods of the CommandSender class without needing to give friend access to + * each individual test. + * This is not a Global API and should only be used for (Unit) Testing. + */ +class CommandSenderTestAccess +{ + +public: + CommandSenderTestAccess(app::CommandSender * aCommandSender) : pCommandSender(aCommandSender) {} + + CHIP_ERROR ProcessInvokeResponse(System::PacketBufferHandle && payload, bool & moreChunkedMessages) + { + return pCommandSender->ProcessInvokeResponse(std::move(payload), moreChunkedMessages); + } + + void FlushNoCommandResponse() { pCommandSender->FlushNoCommandResponse(); } + + void SetFinishedCommandCount(uint16_t aFinishedCommandCount) { pCommandSender->mFinishedCommandCount = aFinishedCommandCount; } + + Messaging::ExchangeHolder GetExchangeCtx() { return pCommandSender->mExchangeCtx; } + + CHIP_ERROR OnMessageReceived(const PayloadHeader & aPayloadHeader, System::PacketBufferHandle && aPayload) + { + return pCommandSender->OnMessageReceived(pCommandSender->mExchangeCtx.Get(), aPayloadHeader, std::move(aPayload)); + } + + CHIP_ERROR Finalize(System::PacketBufferHandle & commandPacket) { return pCommandSender->Finalize(commandPacket); } + + void MoveToState(const app::CommandSender::State aTargetState) {} + void MoveToStateAddedCommand() { pCommandSender->MoveToState(app::CommandSender::State::AddedCommand); } + +private: + app::CommandSender * pCommandSender = nullptr; +}; + +} // namespace Test +} // namespace chip diff --git a/src/app/tests/TestAclAttribute.cpp b/src/app/tests/TestAclAttribute.cpp index c1bfd8acf68a73..4d0c27099377df 100644 --- a/src/app/tests/TestAclAttribute.cpp +++ b/src/app/tests/TestAclAttribute.cpp @@ -16,6 +16,8 @@ * limitations under the License. */ +#include + #include #include #include @@ -33,11 +35,8 @@ #include #include #include -#include -#include #include #include -#include #include #include @@ -77,18 +76,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: @@ -140,29 +127,65 @@ Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventP return Protocols::InteractionModel::Status::Success; } -class TestAclAttribute +class TestAclAttribute : public ::testing::Test { public: - static void TestACLDeniedAttribute(nlTestSuite * apSuite, void * apContext); + static void SetUpTestSuite() + { + + pTestContext = new chip::Test::AppContext; + + pTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + pTestContext->TearDownTestSuite(); + if (pTestContext != nullptr) + { + delete pTestContext; + } + } + + void SetUp() override + { + + if (pTestContext != nullptr) + { + pTestContext->SetUp(); + + Access::GetAccessControl().Finish(); + Access::GetAccessControl().Init(GetTestAccessControlDelegate(), gDeviceTypeResolver); + } + } + void TearDown() override + { + if (pTestContext != nullptr) + { + pTestContext->TearDown(); + } + } + static chip::Test::AppContext * pTestContext; }; +chip::Test::AppContext * TestAclAttribute::pTestContext = 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; + CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + Messaging::ReliableMessageMgr * rm = pTestContext->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); + err = engine->Init(&pTestContext->GetExchangeManager(), &pTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, CHIP_NO_ERROR); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &pTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; @@ -174,22 +197,22 @@ void TestAclAttribute::TestACLDeniedAttribute(nlTestSuite * apSuite, void * apCo attributePathParams[1].mClusterId = kTestDeniedClusterId1; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(InvalidAction)); - NL_TEST_ASSERT(apSuite, !delegate.mGotReport); + pTestContext->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(), &pTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; @@ -200,22 +223,22 @@ void TestAclAttribute::TestACLDeniedAttribute(nlTestSuite * apSuite, void * apCo attributePathParams[1].mClusterId = kTestDeniedClusterId2; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(InvalidAction)); - NL_TEST_ASSERT(apSuite, !delegate.mGotReport); + pTestContext->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(), &pTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; @@ -227,49 +250,24 @@ void TestAclAttribute::TestACLDeniedAttribute(nlTestSuite * apSuite, void * apCo attributePathParams[1].mClusterId = kTestClusterId; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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); + pTestContext->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(pTestContext->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], - TestAccessContext::nlTestSetUpTestSuite, - TestAccessContext::nlTestTearDownTestSuite, - TestAccessContext::nlTestSetUp, - TestAccessContext::nlTestTearDown, -}; - -} // namespace - -int TestAclAttribute() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestAclAttribute) diff --git a/src/app/tests/TestBuilderParser.cpp b/src/app/tests/TestBuilderParser.cpp index 314353e8b70029..8f0e1a2f2cf58d 100644 --- a/src/app/tests/TestBuilderParser.cpp +++ b/src/app/tests/TestBuilderParser.cpp @@ -16,6 +16,8 @@ * limitations under the License. */ +#include + #include #include #include @@ -25,23 +27,27 @@ #include #include #include -#include #include -#include - namespace { using namespace chip::app; -void ListTest(nlTestSuite * apSuite, void * apContext) +class TestBuilderParser : public ::testing::Test +{ +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestBuilderParser, TestList) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); ListBuilder listBuilder; - NL_TEST_ASSERT(apSuite, listBuilder.Init(&writer) == CHIP_NO_ERROR); + EXPECT_EQ(listBuilder.Init(&writer), CHIP_NO_ERROR); listBuilder.EndOfContainer(); chip::System::PacketBufferHandle buf; @@ -50,18 +56,18 @@ void ListTest(nlTestSuite * apSuite, void * apContext) ListParser listParser; reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, listParser.Init(reader) == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(listParser.Init(reader), CHIP_NO_ERROR); } -void StructTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestBuilderParser, TestStruct) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); StructBuilder structBuilder; - NL_TEST_ASSERT(apSuite, structBuilder.Init(&writer) == CHIP_NO_ERROR); + EXPECT_EQ(structBuilder.Init(&writer), CHIP_NO_ERROR); structBuilder.EndOfContainer(); chip::System::PacketBufferHandle buf; @@ -71,17 +77,17 @@ void StructTest(nlTestSuite * apSuite, void * apContext) reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, structParser.Init(reader) == CHIP_NO_ERROR); + EXPECT_EQ(structParser.Init(reader), CHIP_NO_ERROR); } -void ArrayTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestBuilderParser, TestArray) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); ArrayBuilder arrayBuilder; - NL_TEST_ASSERT(apSuite, arrayBuilder.Init(&writer) == CHIP_NO_ERROR); + EXPECT_EQ(arrayBuilder.Init(&writer), CHIP_NO_ERROR); arrayBuilder.EndOfContainer(); chip::System::PacketBufferHandle buf; @@ -91,55 +97,7 @@ void ArrayTest(nlTestSuite * apSuite, void * apContext) reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, arrayParser.Init(reader) == CHIP_NO_ERROR); + EXPECT_EQ(arrayParser.Init(reader), CHIP_NO_ERROR); } -// clang-format off -const nlTest sTests[] = - { - NL_TEST_DEF("ListTest", ListTest), - NL_TEST_DEF("StructTest", StructTest), - NL_TEST_DEF("ArrayTest", ArrayTest), - NL_TEST_SENTINEL() - }; -// clang-format on } // namespace - -/** - * Set up the test suite. - */ -static int TestSetup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -static int TestTeardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -int TestBuilderParser() -{ - // clang-format off - nlTestSuite theSuite = - { - "TestBuilderParser", - &sTests[0], - TestSetup, - TestTeardown, - }; - // clang-format on - - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestBuilderParser) diff --git a/src/app/tests/TestCommandInteraction.cpp b/src/app/tests/TestCommandInteraction.cpp index 87296580fa695f..4cd0b26a1d50cc 100644 --- a/src/app/tests/TestCommandInteraction.cpp +++ b/src/app/tests/TestCommandInteraction.cpp @@ -24,6 +24,12 @@ #include +#include + +#include +#include +#include + #include #include #include @@ -34,8 +40,6 @@ #include #include #include -#include -#include #include #include #include @@ -46,22 +50,18 @@ #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 @@ -75,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; @@ -93,6 +90,12 @@ namespace app { CommandHandler::Handle asyncCommandHandle; +enum class ForcedSizeBufferLengthHint +{ + kSizeBetween0and255, + kSizeGreaterThan255, +}; + struct ForcedSizeBuffer { chip::Platform::ScopedMemoryBufferWithSize mBuffer; @@ -119,10 +122,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) @@ -165,25 +191,25 @@ void DispatchSingleClusterCommand(const ConcreteCommandPath & aRequestCommandPat TLV::TLVType outerContainerType; CHIP_ERROR err = aReader.EnterContainer(outerContainerType); - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_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(err, CHIP_NO_ERROR); + EXPECT_TRUE(val); } err = aReader.ExitContainer(outerContainerType); - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); if (asyncCommand) { @@ -319,66 +345,44 @@ class MockCommandHandlerCallback : public CommandHandler::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 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); + static void SetUpTestSuite() + { + pTestContext = new TestContext; + pTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + pTestContext->TearDownTestSuite(); + if (pTestContext != nullptr) + { + delete pTestContext; + } + } - static void TestCommandSenderAbruptDestruction(nlTestSuite * apSuite, void * apContext); + void SetUp() override + { + if (pTestContext != nullptr) + { + pTestContext->SetUp(); + } + } + void TearDown() override + { + if (pTestContext != nullptr) + { + pTestContext->TearDown(); + } + } + static TestContext * pTestContext; static size_t GetNumActiveCommandResponderObjects() { return chip::app::InteractionModelEngine::GetInstance()->mCommandResponderObjs.Allocated(); } -private: /** * With the introduction of batch invoke commands, CommandHandler keeps track of incoming * ConcreteCommandPath and the associated CommandRefs. These are normally populated @@ -390,8 +394,7 @@ class TestCommandInteraction { public: CommandHandlerWithUnrespondedCommand(CommandHandler::Callback * apCallback, const ConcreteCommandPath & aRequestCommandPath, - const Optional & aRef) : - CommandHandler(apCallback) + const Optional & aRef) : CommandHandler(apCallback) { GetCommandPathRegistry().Add(aRequestCommandPath, aRef.std_optional()); SetExchangeInterface(&mMockCommandResponder); @@ -401,28 +404,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, CommandHandler * apCommandHandler, - const ConcreteCommandPath & aRequestCommandPath, uint32_t aSizeToLeaveInBuffer); - static void ValidateCommandHandlerEncodeInvokeResponseMessage(nlTestSuite * apSuite, void * apContext, bool aNeedStatusCode); + static void FillCurrentInvokeResponseBuffer(CommandHandler * apCommandHandler, const ConcreteCommandPath & aRequestCommandPath, + uint32_t aSizeToLeaveInBuffer); + static void ValidateCommandHandlerEncodeInvokeResponseMessage(bool aNeedStatusCode); }; +TestContext * TestCommandInteraction::pTestContext = nullptr; class TestExchangeDelegate : public Messaging::ExchangeDelegate { @@ -440,9 +440,8 @@ 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; @@ -451,20 +450,20 @@ void TestCommandInteraction::GenerateInvokeRequest(nlTestSuite * apSuite, void * writer.Init(std::move(aPayload)); err = invokeRequestMessageBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); invokeRequestMessageBuilder.SuppressResponse(true).TimedRequest(aIsTimedRequest); InvokeRequests::Builder & invokeRequests = invokeRequestMessageBuilder.CreateInvokeRequests(); - NL_TEST_ASSERT(apSuite, invokeRequestMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_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) { @@ -472,30 +471,30 @@ void TestCommandInteraction::GenerateInvokeRequest(nlTestSuite * apSuite, void * 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(err, CHIP_NO_ERROR); err = pWriter->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = pWriter->EndContainer(dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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); + EXPECT_EQ(invokeRequestMessageBuilder.GetError(), CHIP_NO_ERROR); err = writer.Finalize(&aPayload); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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) { @@ -505,23 +504,23 @@ void TestCommandInteraction::GenerateInvokeResponse(nlTestSuite * apSuite, void writer.Init(std::move(aPayload)); err = invokeResponseMessageBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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) { @@ -529,73 +528,71 @@ void TestCommandInteraction::GenerateInvokeResponse(nlTestSuite * apSuite, void 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(err, CHIP_NO_ERROR); err = pWriter->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = pWriter->EndContainer(dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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(err, 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(err, 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(err, CHIP_NO_ERROR); err = apCommandSender->FinishCommand(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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(err, 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(err, 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) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -611,89 +608,105 @@ void TestCommandInteraction::AddInvokeResponseData(nlTestSuite * apSuite, void * const CommandHandler::InvokeResponseParameters prepareParams(requestCommandPath); ConcreteCommandPath responseCommandPath = { kTestEndpointId, kTestClusterId, aResponseCommandId }; err = apCommandHandler->PrepareInvokeResponseCommand(responseCommandPath, prepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); chip::TLV::TLVWriter * writer = apCommandHandler->GetCommandDataIBTLVWriter(); err = writer->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = apCommandHandler->FinishCommand(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } } -uint32_t TestCommandInteraction::GetAddResponseDataOverheadSizeForPath(nlTestSuite * apSuite, - const ConcreteCommandPath & aRequestCommandPath, +uint32_t TestCommandInteraction::GetAddResponseDataOverheadSizeForPath(const ConcreteCommandPath & aRequestCommandPath, ForcedSizeBufferLengthHint aBufferSizeHint) { BasicCommandPathRegistry<4> basicCommandPathRegistry; MockCommandResponder mockCommandResponder; CommandHandler::TestOnlyOverrides testOnlyOverrides{ &basicCommandPathRegistry, &mockCommandResponder }; CommandHandler commandHandler(testOnlyOverrides, &mockCommandHandlerDelegate); - commandHandler.mReserveSpaceForMoreChunkMessages = true; - ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; - ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; + chip::Test::CommandHandlerTestAccess(&commandHandler).SetReserveSpaceForMoreChunkMessages(true); + 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = commandHandler.AllocateBuffer(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - uint32_t remainingSizeBefore = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); + EXPECT_EQ(err, CHIP_NO_ERROR); + + uint32_t remainingSizeBefore = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().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); - uint32_t remainingSizeAfter = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - uint32_t delta = remainingSizeBefore - remainingSizeAfter - sizeOfForcedSizeBuffer; + EXPECT_EQ(err, CHIP_NO_ERROR); + uint32_t remainingSizeAfter = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + uint32_t delta = remainingSizeBefore - remainingSizeAfter - sizeOfForcedSizeBuffer; return delta; } -void TestCommandInteraction::FillCurrentInvokeResponseBuffer(nlTestSuite * apSuite, CommandHandler * apCommandHandler, +void TestCommandInteraction::FillCurrentInvokeResponseBuffer(CommandHandler * 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(err, 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); + EXPECT_GE(sizeToFill, 256u); err = apCommandHandler->AddResponseData(aRequestCommandPath, ForcedSizeBuffer(sizeToFill)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void TestCommandInteraction::TestCommandSenderWithWrongState(nlTestSuite * apSuite, void * apContext) +void TestCommandInteraction::ValidateCommandHandlerEncodeInvokeResponseMessage(bool aNeedStatusCode) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + chip::app::ConcreteCommandPath requestCommandPath(kTestEndpointId, kTestClusterId, kTestCommandIdWithData); + CommandHandlerWithUnrespondedCommand commandHandler(&mockCommandHandlerDelegate, requestCommandPath, + /* aRef = */ NullOptional); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + { + // This simulates how cluster would call CommandHandler APIs synchronously. There would + // be handle already acquired on the callers behalf. + CommandHandler::Handle handle(&commandHandler); + + AddInvokeResponseData(&commandHandler, aNeedStatusCode); + } + EXPECT_FALSE(commandHandler.mMockCommandResponder.mChunks.IsNull()); +} - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_ERROR_INCORRECT_STATE); +TEST_F(TestCommandInteraction, TestCommandSenderWithWrongState) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); + EXPECT_EQ(err, CHIP_NO_ERROR); + + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); } -void TestCommandInteraction::TestCommandHandlerWithWrongState(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerWithWrongState) { CHIP_ERROR err = CHIP_NO_ERROR; ConcreteCommandPath requestCommandPath = { kTestEndpointId, kTestClusterId, kTestCommandIdNoData }; @@ -709,34 +722,34 @@ void TestCommandInteraction::TestCommandHandlerWithWrongState(nlTestSuite * apSu const CommandHandler::InvokeResponseParameters prepareParams(requestCommandPath); err = commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } - NL_TEST_ASSERT(apSuite, commandHandler.mMockCommandResponder.mChunks.IsNull()); + EXPECT_TRUE(commandHandler.mMockCommandResponder.mChunks.IsNull()); } -void TestCommandInteraction::TestCommandSenderWithSendCommand(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandSenderWithSendCommand) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->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); + AddInvokeRequestData(&commandSender); + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + pTestContext->DrainAndServiceIO(); - GenerateInvokeResponse(apSuite, apContext, buf, kTestCommandIdWithData); + GenerateInvokeResponse(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); + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(moreChunkedMessages); } -void TestCommandInteraction::TestCommandHandlerWithSendEmptyCommand(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerWithSendEmptyCommand) { CHIP_ERROR err = CHIP_NO_ERROR; ConcreteCommandPath requestCommandPath = { kTestEndpointId, kTestClusterId, kTestCommandIdNoData }; @@ -752,147 +765,98 @@ void TestCommandInteraction::TestCommandHandlerWithSendEmptyCommand(nlTestSuite const CommandHandler::InvokeResponseParameters prepareParams(requestCommandPath); err = commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = commandHandler.FinishCommand(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } - NL_TEST_ASSERT(apSuite, !commandHandler.mMockCommandResponder.mChunks.IsNull()); + EXPECT_FALSE(commandHandler.mMockCommandResponder.mChunks.IsNull()); } -void TestCommandInteraction::TestCommandSenderWithProcessReceivedMsg(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandSenderWithProcessReceivedMsg) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - GenerateInvokeResponse(apSuite, apContext, buf, kTestCommandIdWithData); + GenerateInvokeResponse(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); + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(moreChunkedMessages); } -void TestCommandInteraction::TestCommandSenderExtendableApiWithProcessReceivedMsg(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandSenderExtendableApiWithProcessReceivedMsg) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager(), - &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &pTestContext->GetExchangeManager(), &pendingResponseTracker); uint16_t mockCommandRef = 1; pendingResponseTracker.Add(mockCommandRef); - commandSender.mFinishedCommandCount = 1; + chip::Test::CommandSenderTestAccess(&commandSender).SetFinishedCommandCount(1); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - GenerateInvokeResponse(apSuite, apContext, buf, kTestCommandIdWithData); + GenerateInvokeResponse(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); + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(moreChunkedMessages); - commandSender.FlushNoCommandResponse(); + chip::Test::CommandSenderTestAccess(&commandSender).FlushNoCommandResponse(); - NL_TEST_ASSERT(apSuite, - mockCommandSenderExtendedDelegate.onResponseCalledTimes == 1 && - mockCommandSenderExtendedDelegate.onFinalCalledTimes == 0 && - mockCommandSenderExtendedDelegate.onNoResponseCalledTimes == 0 && - mockCommandSenderExtendedDelegate.onErrorCalledTimes == 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onResponseCalledTimes, 1); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onFinalCalledTimes, 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onNoResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onErrorCalledTimes, 0); } -void TestCommandInteraction::TestCommandSenderExtendableApiWithProcessReceivedMsgContainingInvalidCommandRef(nlTestSuite * apSuite, - void * apContext) +TEST_F(TestCommandInteraction, TestCommandSenderExtendableApiWithProcessReceivedMsgContainingInvalidCommandRef) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager(), - &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &pTestContext->GetExchangeManager(), &pendingResponseTracker); uint16_t mockCommandRef = 1; pendingResponseTracker.Add(mockCommandRef); - commandSender.mFinishedCommandCount = 1; + chip::Test::CommandSenderTestAccess(&commandSender).SetFinishedCommandCount(1); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); uint16_t invalidResponseCommandRef = 2; - GenerateInvokeResponse(apSuite, apContext, buf, kTestCommandIdWithData, kTestClusterId, kTestEndpointId, + GenerateInvokeResponse(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); + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); + EXPECT_EQ(err, CHIP_ERROR_KEY_NOT_FOUND); + EXPECT_FALSE(moreChunkedMessages); - commandSender.FlushNoCommandResponse(); + chip::Test::CommandSenderTestAccess(&commandSender).FlushNoCommandResponse(); - NL_TEST_ASSERT(apSuite, - mockCommandSenderExtendedDelegate.onResponseCalledTimes == 0 && - mockCommandSenderExtendedDelegate.onFinalCalledTimes == 0 && - mockCommandSenderExtendedDelegate.onNoResponseCalledTimes == 1 && - mockCommandSenderExtendedDelegate.onErrorCalledTimes == 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onFinalCalledTimes, 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onNoResponseCalledTimes, 1); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onErrorCalledTimes, 0); } -void TestCommandInteraction::ValidateCommandHandlerEncodeInvokeResponseMessage(nlTestSuite * apSuite, void * apContext, - bool aNeedStatusCode) -{ - chip::app::ConcreteCommandPath requestCommandPath(kTestEndpointId, kTestClusterId, kTestCommandIdWithData); - 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); - - AddInvokeResponseData(apSuite, apContext, &commandHandler, aNeedStatusCode); - } - NL_TEST_ASSERT(apSuite, !commandHandler.mMockCommandResponder.mChunks.IsNull()); -} - -void TestCommandInteraction::TestCommandHandlerEncodeSimpleCommandData(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerEncodeSimpleCommandData) { // Send response which has simple command data and command path - ValidateCommandHandlerEncodeInvokeResponseMessage(apSuite, apContext, false /*aNeedStatusCode=false*/); + ValidateCommandHandlerEncodeInvokeResponseMessage(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) +TEST_F(TestCommandInteraction, TestCommandHandlerCommandDataEncoding) { auto path = MakeTestCommandPath(); auto requestCommandPath = ConcreteCommandPath(path.mEndpointId, path.mClusterId, path.mCommandId); @@ -905,10 +869,10 @@ void TestCommandInteraction::TestCommandHandlerCommandDataEncoding(nlTestSuite * commandHandler.AddResponse(requestCommandPath, Fields()); } - NL_TEST_ASSERT(apSuite, !commandHandler.mMockCommandResponder.mChunks.IsNull()); + EXPECT_FALSE(commandHandler.mMockCommandResponder.mChunks.IsNull()); } -void TestCommandInteraction::TestCommandHandlerCommandEncodeFailure(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerCommandEncodeFailure) { auto path = MakeTestCommandPath(); auto requestCommandPath = ConcreteCommandPath(path.mEndpointId, path.mClusterId, path.mCommandId); @@ -921,7 +885,7 @@ void TestCommandInteraction::TestCommandHandlerCommandEncodeFailure(nlTestSuite commandHandler.AddResponse(requestCommandPath, BadFields()); } - NL_TEST_ASSERT(apSuite, !commandHandler.mMockCommandResponder.mChunks.IsNull()); + EXPECT_FALSE(commandHandler.mMockCommandResponder.mChunks.IsNull()); } /** @@ -943,333 +907,328 @@ void TestCommandInteraction::TestCommandHandlerCommandEncodeFailure(nlTestSuite * * This is a macro so we get useful line numbers on assertion failures */ -#define PretendWeGotReplyFromServer(aSuite, aContext, aClientExchange) \ +#define PretendWeGotReplyFromServer(aContext, aClientExchange) \ { \ - Messaging::ReliableMessageMgr * localRm = (aContext).GetExchangeManager().GetReliableMessageMgr(); \ + Messaging::ReliableMessageMgr * localRm = aContext->GetExchangeManager().GetReliableMessageMgr(); \ Messaging::ExchangeContext * localExchange = aClientExchange; \ - NL_TEST_ASSERT(aSuite, localRm->TestGetCountRetransTable() == 2); \ + EXPECT_EQ(localRm->TestGetCountRetransTable(), 2); \ \ localRm->ClearRetransTable(localExchange); \ - NL_TEST_ASSERT(aSuite, localRm->TestGetCountRetransTable() == 1); \ + EXPECT_EQ(localRm->TestGetCountRetransTable(), 1); \ \ localRm->EnumerateRetransTable([localExchange](auto * entry) { \ - localExchange->SetPendingPeerAckMessageCounter(entry->retainedBuf.GetMessageCounter()); \ + chip::Test::ReliableMessageContextTestAccess(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(TestCommandInteraction, TestCommandInvalidMessage1) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->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(); + pTestContext->GetLoopback().mSentMessageCount = 0; + pTestContext->GetLoopback().mNumMessagesToDrop = 1; + pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_NO_ERROR); + pTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + EXPECT_EQ(pTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(pTestContext->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()); + 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(*pTestContext); 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(pTestContext, chip::Test::CommandSenderTestAccess(&commandSender).GetExchangeCtx().Get()); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + pTestContext->GetLoopback().mSentMessageCount = 0; + pTestContext->GetLoopback().mNumMessagesToDrop = 0; + pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + pTestContext->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); + err = chip::Test::CommandSenderTestAccess(&commandSender).OnMessageReceived(payloadHeader, std::move(msgBuf)); + EXPECT_EQ(err, 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(); + pTestContext->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(pTestContext->GetLoopback().mSentMessageCount, 2u); + CheckForInvalidAction(messageLog); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + pTestContext->ExpireSessionAliceToBob(); + pTestContext->ExpireSessionBobToAlice(); + pTestContext->CreateSessionAliceToBob(); + pTestContext->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(TestCommandInteraction, TestCommandInvalidMessage2) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->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(); + pTestContext->GetLoopback().mSentMessageCount = 0; + pTestContext->GetLoopback().mNumMessagesToDrop = 1; + pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_NO_ERROR); + pTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + EXPECT_EQ(pTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(pTestContext->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()); + 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); - Test::MessageCapturer messageLog(ctx); + chip::Test::MessageCapturer messageLog(*pTestContext); 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(pTestContext, chip::Test::CommandSenderTestAccess(&commandSender).GetExchangeCtx().Get()); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + pTestContext->GetLoopback().mSentMessageCount = 0; + pTestContext->GetLoopback().mNumMessagesToDrop = 0; + pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + pTestContext->GetLoopback().mDroppedMessageCount = 0; - 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); + err = chip::Test::CommandSenderTestAccess(&commandSender).OnMessageReceived(payloadHeader, std::move(msgBuf)); + EXPECT_EQ(err, 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); - ctx.DrainAndServiceIO(); + pTestContext->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(pTestContext->GetLoopback().mSentMessageCount, 2u); + CheckForInvalidAction(messageLog); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + pTestContext->ExpireSessionAliceToBob(); + pTestContext->ExpireSessionBobToAlice(); + pTestContext->CreateSessionAliceToBob(); + pTestContext->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(TestCommandInteraction, TestCommandInvalidMessage3) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->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(); + pTestContext->GetLoopback().mSentMessageCount = 0; + pTestContext->GetLoopback().mNumMessagesToDrop = 1; + pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_NO_ERROR); + pTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + EXPECT_EQ(pTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(pTestContext->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()); + EXPECT_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(*pTestContext); 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(pTestContext, chip::Test::CommandSenderTestAccess(&commandSender).GetExchangeCtx().Get()); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + pTestContext->GetLoopback().mSentMessageCount = 0; + pTestContext->GetLoopback().mNumMessagesToDrop = 0; + pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + pTestContext->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); + err = chip::Test::CommandSenderTestAccess(&commandSender).OnMessageReceived(payloadHeader, std::move(msgBuf)); + EXPECT_EQ(err, 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(); + pTestContext->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(pTestContext->GetLoopback().mSentMessageCount, 2u); + CheckForInvalidAction(messageLog); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + pTestContext->ExpireSessionAliceToBob(); + pTestContext->ExpireSessionBobToAlice(); + pTestContext->CreateSessionAliceToBob(); + pTestContext->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(TestCommandInteraction, TestCommandInvalidMessage4) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->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(); + pTestContext->GetLoopback().mSentMessageCount = 0; + pTestContext->GetLoopback().mNumMessagesToDrop = 1; + pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_NO_ERROR); + pTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 2); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); + EXPECT_EQ(pTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(pTestContext->GetLoopback().mDroppedMessageCount, 1u); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 0 && - mockCommandSenderDelegate.onErrorCalledTimes == 0); - - 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()); + 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); - Test::MessageCapturer messageLog(ctx); + chip::Test::MessageCapturer messageLog(*pTestContext); 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(pTestContext, chip::Test::CommandSenderTestAccess(&commandSender).GetExchangeCtx().Get()); - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + pTestContext->GetLoopback().mSentMessageCount = 0; + pTestContext->GetLoopback().mNumMessagesToDrop = 0; + pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + pTestContext->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); + err = chip::Test::CommandSenderTestAccess(&commandSender).OnMessageReceived(payloadHeader, std::move(msgBuf)); + EXPECT_EQ(err, 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(); + pTestContext->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(pTestContext->GetLoopback().mSentMessageCount, 2u); + CheckForInvalidAction(messageLog); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + pTestContext->ExpireSessionAliceToBob(); + pTestContext->ExpireSessionBobToAlice(); + pTestContext->CreateSessionAliceToBob(); + pTestContext->CreateSessionBobToAlice(); } // 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; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->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); + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_NO_ERROR); + + pTestContext->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(pTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestCommandInteraction::TestCommandHandlerCommandEncodeExternalFailure(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerCommandEncodeExternalFailure) { CHIP_ERROR err = CHIP_NO_ERROR; auto path = MakeTestCommandPath(); @@ -1282,19 +1241,19 @@ void TestCommandInteraction::TestCommandHandlerCommandEncodeExternalFailure(nlTe CommandHandler::Handle handle(&commandHandler); err = commandHandler.AddResponseData(requestCommandPath, BadFields()); - NL_TEST_ASSERT(apSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, 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(TestCommandInteraction, TestCommandHandlerWithoutResponderCallingAddStatus) { chip::app::ConcreteCommandPath requestCommandPath(kTestEndpointId, kTestClusterId, kTestCommandIdWithData); CommandHandler commandHandler(&mockCommandHandlerDelegate); @@ -1303,25 +1262,24 @@ 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(chip::Test::CommandHandlerTestAccess(&commandHandler).TestOnlyIsInIdleState()); } -void TestCommandInteraction::TestCommandHandlerWithoutResponderCallingAddResponse(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerWithoutResponderCallingAddResponse) { chip::app::ConcreteCommandPath requestCommandPath(kTestEndpointId, kTestClusterId, kTestCommandIdWithData); CommandHandler 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(err, 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(chip::Test::CommandHandlerTestAccess(&commandHandler).TestOnlyIsInIdleState()); } -void TestCommandInteraction::TestCommandHandlerWithoutResponderCallingDirectPrepareFinishCommandApis(nlTestSuite * apSuite, - void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerWithoutResponderCallingDirectPrepareFinishCommandApis) { chip::app::ConcreteCommandPath requestCommandPath(kTestEndpointId, kTestClusterId, kTestCommandIdWithData); CommandHandler commandHandler(&mockCommandHandlerDelegate); @@ -1333,22 +1291,22 @@ void TestCommandInteraction::TestCommandHandlerWithoutResponderCallingDirectPrep const CommandHandler::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(err, 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(err, CHIP_ERROR_INCORRECT_STATE); - NL_TEST_ASSERT(apSuite, commandHandler.TestOnlyIsInIdleState()); + EXPECT_TRUE(chip::Test::CommandHandlerTestAccess(&commandHandler).TestOnlyIsInIdleState()); } -void TestCommandInteraction::TestCommandHandlerWithOnInvokeReceivedNotExistCommand(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerWithOnInvokeReceivedNotExistCommand) { 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 */); CommandHandler commandHandler(&mockCommandHandlerDelegate); chip::isCommandDispatched = false; @@ -1356,13 +1314,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, TestCommandHandlerWithOnInvokeReceivedEmptyDataMsg) { bool allBooleans[] = { true, false }; for (auto messageIsTimed : allBooleans) @@ -1374,78 +1332,73 @@ 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; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); - - AddInvokeRequestData(apSuite, apContext, &commandSender, kTestNonExistCommandId); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); - ctx.DrainAndServiceIO(); + AddInvokeRequestData(&commandSender, kTestNonExistCommandId); + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 1 && - mockCommandSenderDelegate.onErrorCalledTimes == 1); + pTestContext->DrainAndServiceIO(); - 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(pTestContext->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, TestCommandSenderExtendableCallbackUnsupportedCommand) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderExtendedDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderExtendedDelegate, &pTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender, kTestNonExistCommandId); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + AddInvokeRequestData(&commandSender, kTestNonExistCommandId); + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + pTestContext->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(pTestContext->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; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); app::CommandSender::PrepareCommandParameters prepareCommandParams; app::CommandSender::FinishCommandParameters finishCommandParams; prepareCommandParams.SetStartDataStruct(true).SetCommandRef(0); @@ -1454,78 +1407,75 @@ 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(err, 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(err, 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = commandSender.FinishCommand(finishCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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(err, CHIP_ERROR_INCORRECT_STATE); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(pTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestCommandInteraction::TestCommandSenderExtendableCallbackBuildingBatchDuplicateCommandRefFails(nlTestSuite * apSuite, - void * apContext) +TEST_F(TestCommandInteraction, TestCommandSenderExtendableCallbackBuildingBatchDuplicateCommandRefFails) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager(), - &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &pTestContext->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(err, 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(err, 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = commandSender.FinishCommand(finishCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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(err, CHIP_ERROR_INVALID_ARGUMENT); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(pTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } -void TestCommandInteraction::TestCommandSenderExtendableCallbackBuildingBatchCommandSuccess(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandSenderExtendableCallbackBuildingBatchCommandSuccess) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &ctx.GetExchangeManager(), - &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &pTestContext->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(err, 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. @@ -1535,140 +1485,133 @@ void TestCommandInteraction::TestCommandSenderExtendableCallbackBuildingBatchCom finishCommandParams.SetEndDataStruct(true).SetCommandRef(firstCommandRef); auto commandPathParams = MakeTestCommandPath(); err = commandSender.PrepareCommand(commandPathParams, prepareCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = commandSender.FinishCommand(finishCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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(err, CHIP_NO_ERROR); writer = commandSender.GetCommandDataIBTLVWriter(); err = writer->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = commandSender.FinishCommand(finishCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); - NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); + EXPECT_EQ(pTestContext->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; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); + + AddInvokeRequestData(&commandSender); + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); - AddInvokeRequestData(apSuite, apContext, &commandSender); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(commandSender.GetInvokeResponseMessageCount(), 0u); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, commandSender.GetInvokeResponseMessageCount() == 0); + pTestContext->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(pTestContext->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; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender); + AddInvokeRequestData(&commandSender); asyncCommand = true; - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + pTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 0 && - mockCommandSenderDelegate.onErrorCalledTimes == 0); - - 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(pTestContext->GetExchangeManager().GetNumActiveExchanges(), 2u); // Decrease CommandHandler refcount and send response asyncCommandHandle = nullptr; - ctx.DrainAndServiceIO(); + pTestContext->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(pTestContext->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; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender, kTestCommandIdCommandSpecificResponse); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); + AddInvokeRequestData(&commandSender, kTestCommandIdCommandSpecificResponse); + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + pTestContext->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(pTestContext->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; + 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, &pTestContext->GetExchangeManager()); - ctx.DrainAndServiceIO(); + AddInvokeRequestData(&commandSender, kTestNonExistCommandId); + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + pTestContext->DrainAndServiceIO(); - ctx.DrainAndServiceIO(); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 0 && mockCommandSenderDelegate.onFinalCalledTimes == 1 && - mockCommandSenderDelegate.onErrorCalledTimes == 1); + pTestContext->DrainAndServiceIO(); - 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(pTestContext->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; + CHIP_ERROR err = CHIP_NO_ERROR; // // Don't send back a response, just keep the CommandHandler @@ -1679,47 +1622,46 @@ void TestCommandInteraction::TestCommandSenderAbruptDestruction(nlTestSuite * ap mockCommandSenderDelegate.ResetCounter(); { - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender, kTestCommandIdCommandSpecificResponse); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); + AddInvokeRequestData(&commandSender, kTestCommandIdCommandSpecificResponse); + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + pTestContext->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(pTestContext->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(pTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); - NL_TEST_ASSERT(apSuite, GetNumActiveCommandResponderObjects() == 0); + EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); } -void TestCommandInteraction::TestCommandHandlerRejectMultipleIdenticalCommands(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerRejectMultipleIdenticalCommands) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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, + &pTestContext->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); @@ -1729,49 +1671,45 @@ 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()); + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + pTestContext->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(pTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } #if CONFIG_BUILD_FOR_HOST_UNIT_TEST -void TestCommandInteraction::TestCommandHandlerRejectsMultipleCommandsWithIdenticalCommandRef(nlTestSuite * apSuite, - void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerRejectsMultipleCommandsWithIdenticalCommandRef) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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, + &pTestContext->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; { @@ -1787,16 +1725,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)); } } @@ -1807,36 +1744,35 @@ 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); + err = chip::Test::CommandSenderTestAccess(&commandSender).Finalize(commandDatabuf); + EXPECT_EQ(err, CHIP_NO_ERROR); mockCommandHandlerDelegate.ResetCounter(); commandDispatchedCount = 0; - InteractionModel::Status status = commandHandler.ProcessInvokeRequest(std::move(commandDatabuf), false); - NL_TEST_ASSERT(apSuite, status == InteractionModel::Status::InvalidAction); + InteractionModel::Status status = + chip::Test::CommandHandlerTestAccess(&commandHandler).ProcessInvokeRequest(std::move(commandDatabuf), false); + 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(TestCommandInteraction, TestCommandHandlerRejectMultipleCommandsWhenHandlerOnlySupportsOne) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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, + &pTestContext->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; { @@ -1850,20 +1786,19 @@ 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); + err = chip::Test::CommandSenderTestAccess(&commandSender).Finalize(commandDatabuf); + EXPECT_EQ(err, CHIP_NO_ERROR); mockCommandHandlerDelegate.ResetCounter(); sendResponse = true; @@ -1872,27 +1807,26 @@ void TestCommandInteraction::TestCommandHandlerRejectMultipleCommandsWhenHandler CommandHandler 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(TestCommandInteraction, TestCommandHandlerAcceptMultipleCommands) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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, + &pTestContext->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; { @@ -1906,16 +1840,15 @@ 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); + // changing the state of commandSender to State::AddedCommand + chip::Test::CommandSenderTestAccess(&commandSender).MoveToStateAddedCommand(); } BasicCommandPathRegistry<4> basicCommandPathRegistry; @@ -1925,104 +1858,107 @@ 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); + err = chip::Test::CommandSenderTestAccess(&commandSender).Finalize(commandDatabuf); + EXPECT_EQ(err, 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); + InteractionModel::Status status = + chip::Test::CommandHandlerTestAccess(&commandHandler).ProcessInvokeRequest(std::move(commandDatabuf), false); + 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(TestCommandInteraction, TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsStatusResponse) { BasicCommandPathRegistry<4> basicCommandPathRegistry; MockCommandResponder mockCommandResponder; CommandHandler::TestOnlyOverrides testOnlyOverrides{ &basicCommandPathRegistry, &mockCommandResponder }; CommandHandler commandHandler(testOnlyOverrides, &mockCommandHandlerDelegate); - commandHandler.mReserveSpaceForMoreChunkMessages = true; - ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; - ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; + chip::Test::CommandHandlerTestAccess(&commandHandler).SetReserveSpaceForMoreChunkMessages(true); + 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t sizeToLeave = 0; - FillCurrentInvokeResponseBuffer(apSuite, &commandHandler, requestCommandPath1, sizeToLeave); - uint32_t remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize == sizeToLeave); + FillCurrentInvokeResponseBuffer(&commandHandler, requestCommandPath1, sizeToLeave); + uint32_t remainingSize = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + 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); + remainingSize = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + EXPECT_GT(remainingSize, sizeToLeave); } - -void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponsePrimative( - nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponsePrimative) { BasicCommandPathRegistry<4> basicCommandPathRegistry; MockCommandResponder mockCommandResponder; CommandHandler::TestOnlyOverrides testOnlyOverrides{ &basicCommandPathRegistry, &mockCommandResponder }; CommandHandler commandHandler(testOnlyOverrides, &mockCommandHandlerDelegate); - commandHandler.mReserveSpaceForMoreChunkMessages = true; - ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; - ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; + chip::Test::CommandHandlerTestAccess(&commandHandler).SetReserveSpaceForMoreChunkMessages(true); + 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t sizeToLeave = 0; - FillCurrentInvokeResponseBuffer(apSuite, &commandHandler, requestCommandPath1, sizeToLeave); - uint32_t remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize == sizeToLeave); + FillCurrentInvokeResponseBuffer(&commandHandler, requestCommandPath1, sizeToLeave); + uint32_t remainingSize = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + 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); + remainingSize = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + EXPECT_GT(remainingSize, sizeToLeave); } -void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponse(nlTestSuite * apSuite, - void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponse) { BasicCommandPathRegistry<4> basicCommandPathRegistry; MockCommandResponder mockCommandResponder; CommandHandler::TestOnlyOverrides testOnlyOverrides{ &basicCommandPathRegistry, &mockCommandResponder }; CommandHandler commandHandler(testOnlyOverrides, &mockCommandHandlerDelegate); - commandHandler.mReserveSpaceForMoreChunkMessages = true; - ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; - ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; + chip::Test::CommandHandlerTestAccess(&commandHandler).SetReserveSpaceForMoreChunkMessages(true); + 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t sizeToLeave = 0; - FillCurrentInvokeResponseBuffer(apSuite, &commandHandler, requestCommandPath1, sizeToLeave); - uint32_t remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize == sizeToLeave); + FillCurrentInvokeResponseBuffer(&commandHandler, requestCommandPath1, sizeToLeave); + uint32_t remainingSize = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + EXPECT_EQ(remainingSize, sizeToLeave); uint32_t sizeToFill = 50; err = commandHandler.AddResponseData(requestCommandPath2, ForcedSizeBuffer(sizeToFill)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize > sizeToLeave); + remainingSize = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + EXPECT_GT(remainingSize, sizeToLeave); } #if CONFIG_BUILD_FOR_HOST_UNIT_TEST @@ -2030,29 +1966,32 @@ 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(TestCommandInteraction, TestCommandHandlerReleaseWithExchangeClosed) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); - AddInvokeRequestData(apSuite, apContext, &commandSender); + AddInvokeRequestData(&commandSender); asyncCommandHandle = nullptr; asyncCommand = true; - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + pTestContext->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. - asyncCommandHandle.Get()->mpResponder->GetExchangeContext()->GetSessionHolder().Release(); - asyncCommandHandle.Get()->mpResponder->GetExchangeContext()->OnSessionReleased(); + chip::Test::CommandHandlerTestAccess(asyncCommandHandle.Get()) + .GetmpResponder() + ->GetExchangeContext() + ->GetSessionHolder() + .Release(); + chip::Test::CommandHandlerTestAccess(asyncCommandHandle.Get()).GetmpResponder()->GetExchangeContext()->OnSessionReleased(); asyncCommandHandle = nullptr; } @@ -2060,79 +1999,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], - TestContext::nlTestSetUpTestSuite, - TestContext::nlTestTearDownTestSuite, - TestContext::nlTestSetUp, - TestContext::nlTestTearDown, -}; -// clang-format on - -} // namespace - -int TestCommandInteraction() -{ - chip::gSuite = &sSuite; - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestCommandInteraction) diff --git a/src/app/tests/TestMessageDef.cpp b/src/app/tests/TestMessageDef.cpp index 10417fa2025522..148913da022ae1 100644 --- a/src/app/tests/TestMessageDef.cpp +++ b/src/app/tests/TestMessageDef.cpp @@ -22,6 +22,8 @@ * */ +#include + #include #include #include @@ -38,16 +40,20 @@ #include #include #include -#include #include #include -#include - namespace { using namespace chip::app; +class TestMessageDef : public ::testing::Test +{ +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + void ENFORCE_FORMAT(1, 2) TLVPrettyPrinter(const char * aFormat, ...) { va_list args; @@ -75,7 +81,7 @@ CHIP_ERROR DebugPrettyPrint(const chip::System::PacketBufferHandle & aMsgBuf) return err; } -void BuildStatusIB(nlTestSuite * apSuite, StatusIB::Builder & aStatusIBBuilder) +void BuildStatusIB(StatusIB::Builder & aStatusIBBuilder) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -83,10 +89,10 @@ void BuildStatusIB(nlTestSuite * apSuite, StatusIB::Builder & aStatusIBBuilder) statusIB.mStatus = chip::Protocols::InteractionModel::Status::InvalidSubscription; aStatusIBBuilder.EncodeStatusIB(statusIB); err = aStatusIBBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void ParseStatusIB(nlTestSuite * apSuite, StatusIB::Parser & aStatusIBParser) +void ParseStatusIB(StatusIB::Parser & aStatusIBParser) { CHIP_ERROR err = CHIP_NO_ERROR; StatusIB::Parser StatusIBParser; @@ -96,20 +102,20 @@ void ParseStatusIB(nlTestSuite * apSuite, StatusIB::Parser & aStatusIBParser) aStatusIBParser.PrettyPrint(); #endif err = aStatusIBParser.DecodeStatusIB(statusIB); - NL_TEST_ASSERT(apSuite, - err == CHIP_NO_ERROR && statusIB.mStatus == chip::Protocols::InteractionModel::Status::InvalidSubscription && - !statusIB.mClusterStatus.HasValue()); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(statusIB.mStatus, chip::Protocols::InteractionModel::Status::InvalidSubscription); + EXPECT_FALSE(statusIB.mClusterStatus.HasValue()); } -void BuildClusterPathIB(nlTestSuite * apSuite, ClusterPathIB::Builder & aClusterPathBuilder) +void BuildClusterPathIB(ClusterPathIB::Builder & aClusterPathBuilder) { CHIP_ERROR err = CHIP_NO_ERROR; aClusterPathBuilder.Node(1).Endpoint(2).Cluster(3).EndOfClusterPathIB(); err = aClusterPathBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void ParseClusterPathIB(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseClusterPathIB(chip::TLV::TLVReader & aReader) { ClusterPathIB::Parser clusterPathParser; CHIP_ERROR err = CHIP_NO_ERROR; @@ -118,31 +124,34 @@ void ParseClusterPathIB(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) chip::ClusterId cluster = 0; err = clusterPathParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT clusterPathParser.PrettyPrint(); #endif err = clusterPathParser.GetNode(&node); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && node == 1); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(node, 1u); err = clusterPathParser.GetEndpoint(&endpoint); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && endpoint == 2); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(endpoint, 2u); err = clusterPathParser.GetCluster(&cluster); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && cluster == 3); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(cluster, 3u); } -void BuildDataVersionFilterIB(nlTestSuite * apSuite, DataVersionFilterIB::Builder & aDataVersionFilterIBBuilder) +void BuildDataVersionFilterIB(DataVersionFilterIB::Builder & aDataVersionFilterIBBuilder) { ClusterPathIB::Builder & clusterPathBuilder = aDataVersionFilterIBBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, clusterPathBuilder.GetError() == CHIP_NO_ERROR); - BuildClusterPathIB(apSuite, clusterPathBuilder); + EXPECT_EQ(clusterPathBuilder.GetError(), CHIP_NO_ERROR); + BuildClusterPathIB(clusterPathBuilder); aDataVersionFilterIBBuilder.DataVersion(2).EndOfDataVersionFilterIB(); - NL_TEST_ASSERT(apSuite, aDataVersionFilterIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aDataVersionFilterIBBuilder.GetError(), CHIP_NO_ERROR); } -void ParseDataVersionFilterIB(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseDataVersionFilterIB(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; DataVersionFilterIB::Parser dataVersionFilterIBParser; @@ -150,46 +159,47 @@ void ParseDataVersionFilterIB(nlTestSuite * apSuite, chip::TLV::TLVReader & aRea chip::DataVersion dataVersion = 2; err = dataVersionFilterIBParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT dataVersionFilterIBParser.PrettyPrint(); #endif err = dataVersionFilterIBParser.GetPath(&clusterPath); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = dataVersionFilterIBParser.GetDataVersion(&dataVersion); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && dataVersion == 2); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(dataVersion, 2u); } -void BuildDataVersionFilterIBs(nlTestSuite * apSuite, DataVersionFilterIBs::Builder & aDataVersionFilterIBsBuilder) +void BuildDataVersionFilterIBs(DataVersionFilterIBs::Builder & aDataVersionFilterIBsBuilder) { DataVersionFilterIB::Builder & dataVersionFilterIBBuilder = aDataVersionFilterIBsBuilder.CreateDataVersionFilter(); - NL_TEST_ASSERT(apSuite, aDataVersionFilterIBsBuilder.GetError() == CHIP_NO_ERROR); - BuildDataVersionFilterIB(apSuite, dataVersionFilterIBBuilder); + EXPECT_EQ(aDataVersionFilterIBsBuilder.GetError(), CHIP_NO_ERROR); + BuildDataVersionFilterIB(dataVersionFilterIBBuilder); aDataVersionFilterIBsBuilder.EndOfDataVersionFilterIBs(); - NL_TEST_ASSERT(apSuite, aDataVersionFilterIBsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aDataVersionFilterIBsBuilder.GetError(), CHIP_NO_ERROR); } -void ParseDataVersionFilterIBs(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseDataVersionFilterIBs(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; DataVersionFilterIBs::Parser dataVersionFilterIBsParser; err = dataVersionFilterIBsParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT dataVersionFilterIBsParser.PrettyPrint(); #endif } -void BuildEventFilterIB(nlTestSuite * apSuite, EventFilterIB::Builder & aEventFilterIBBuilder) +void BuildEventFilterIB(EventFilterIB::Builder & aEventFilterIBBuilder) { aEventFilterIBBuilder.Node(1).EventMin(2).EndOfEventFilterIB(); - NL_TEST_ASSERT(apSuite, aEventFilterIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aEventFilterIBBuilder.GetError(), CHIP_NO_ERROR); } -void ParseEventFilterIB(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseEventFilterIB(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; EventFilterIB::Parser eventFilterIBParser; @@ -197,39 +207,41 @@ void ParseEventFilterIB(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) uint64_t eventMin = 2; err = eventFilterIBParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT eventFilterIBParser.PrettyPrint(); #endif err = eventFilterIBParser.GetNode(&node); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && node == 1); + EXPECT_EQ(err, CHIP_NO_ERROR); + + EXPECT_EQ(node, 1u); err = eventFilterIBParser.GetEventMin(&eventMin); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && eventMin == 2); + EXPECT_EQ(eventMin, 2u); } -void BuildEventFilters(nlTestSuite * apSuite, EventFilterIBs::Builder & aEventFiltersBuilder) +void BuildEventFilters(EventFilterIBs::Builder & aEventFiltersBuilder) { EventFilterIB::Builder & eventFilterBuilder = aEventFiltersBuilder.CreateEventFilter(); - NL_TEST_ASSERT(apSuite, aEventFiltersBuilder.GetError() == CHIP_NO_ERROR); - BuildEventFilterIB(apSuite, eventFilterBuilder); + EXPECT_EQ(aEventFiltersBuilder.GetError(), CHIP_NO_ERROR); + BuildEventFilterIB(eventFilterBuilder); aEventFiltersBuilder.EndOfEventFilters(); - NL_TEST_ASSERT(apSuite, aEventFiltersBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aEventFiltersBuilder.GetError(), CHIP_NO_ERROR); } -void ParseEventFilters(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseEventFilters(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; EventFilterIBs::Parser eventFiltersParser; err = eventFiltersParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT eventFiltersParser.PrettyPrint(); #endif } -void BuildAttributePathIB(nlTestSuite * apSuite, AttributePathIB::Builder & aAttributePathBuilder) +void BuildAttributePathIB(AttributePathIB::Builder & aAttributePathBuilder) { CHIP_ERROR err = CHIP_NO_ERROR; err = aAttributePathBuilder.EnableTagCompression(false) @@ -239,10 +251,10 @@ void BuildAttributePathIB(nlTestSuite * apSuite, AttributePathIB::Builder & aAtt .Attribute(4) .ListIndex(5) .EndOfAttributePathIB(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void ParseAttributePathIB(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseAttributePathIB(chip::TLV::TLVReader & aReader) { AttributePathIB::Parser attributePathParser; CHIP_ERROR err = CHIP_NO_ERROR; @@ -254,63 +266,69 @@ void ParseAttributePathIB(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) chip::ListIndex listIndex = 5; err = attributePathParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT attributePathParser.PrettyPrint(); #endif err = attributePathParser.GetEnableTagCompression(&enableTagCompression); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && enableTagCompression == false); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(enableTagCompression); err = attributePathParser.GetNode(&node); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && node == 1); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(node, 1u); err = attributePathParser.GetEndpoint(&endpoint); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && endpoint == 2); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(endpoint, 2u); err = attributePathParser.GetCluster(&cluster); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && cluster == 3); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(cluster, 3u); err = attributePathParser.GetAttribute(&attribute); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && attribute == 4); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(attribute, 4u); err = attributePathParser.GetListIndex(&listIndex); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && listIndex == 5); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(listIndex, 5u); } -void BuildAttributePathList(nlTestSuite * apSuite, AttributePathIBs::Builder & aAttributePathListBuilder) +void BuildAttributePathList(AttributePathIBs::Builder & aAttributePathListBuilder) { AttributePathIB::Builder & attributePathBuilder = aAttributePathListBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributePathIB(apSuite, attributePathBuilder); + EXPECT_EQ(attributePathBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributePathIB(attributePathBuilder); aAttributePathListBuilder.EndOfAttributePathIBs(); - NL_TEST_ASSERT(apSuite, aAttributePathListBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aAttributePathListBuilder.GetError(), CHIP_NO_ERROR); } -void ParseAttributePathList(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseAttributePathList(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; AttributePathIBs::Parser attributePathListParser; AttributePathIB::Parser attributePathParser; err = attributePathListParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT attributePathListParser.PrettyPrint(); #endif } -void BuildEventPath(nlTestSuite * apSuite, EventPathIB::Builder & aEventPathBuilder) +void BuildEventPath(EventPathIB::Builder & aEventPathBuilder) { CHIP_ERROR err = CHIP_NO_ERROR; aEventPathBuilder.Node(1).Endpoint(2).Cluster(3).Event(4).IsUrgent(true).EndOfEventPathIB(); err = aEventPathBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void ParseEventPath(nlTestSuite * apSuite, EventPathIB::Parser & aEventPathParser) +void ParseEventPath(EventPathIB::Parser & aEventPathParser) { CHIP_ERROR err = CHIP_NO_ERROR; chip::NodeId node = 1; @@ -323,50 +341,55 @@ void ParseEventPath(nlTestSuite * apSuite, EventPathIB::Parser & aEventPathParse aEventPathParser.PrettyPrint(); #endif err = aEventPathParser.GetNode(&node); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && node == 1); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(node, 1u); err = aEventPathParser.GetEndpoint(&endpoint); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && endpoint == 2); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(endpoint, 2u); err = aEventPathParser.GetCluster(&cluster); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && cluster == 3); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(cluster, 3u); err = aEventPathParser.GetEvent(&event); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && event == 4); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(event, 4u); err = aEventPathParser.GetIsUrgent(&isUrgent); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && isUrgent == true); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(isUrgent); } -void BuildEventPaths(nlTestSuite * apSuite, EventPathIBs::Builder & aEventPathsBuilder) +void BuildEventPaths(EventPathIBs::Builder & aEventPathsBuilder) { EventPathIB::Builder & eventPathBuilder = aEventPathsBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, eventPathBuilder.GetError() == CHIP_NO_ERROR); - BuildEventPath(apSuite, eventPathBuilder); + EXPECT_EQ(eventPathBuilder.GetError(), CHIP_NO_ERROR); + BuildEventPath(eventPathBuilder); aEventPathsBuilder.EndOfEventPaths(); - NL_TEST_ASSERT(apSuite, aEventPathsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aEventPathsBuilder.GetError(), CHIP_NO_ERROR); } -void ParseEventPaths(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseEventPaths(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; EventPathIBs::Parser eventPathListParser; err = eventPathListParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT eventPathListParser.PrettyPrint(); #endif } -void BuildCommandPath(nlTestSuite * apSuite, CommandPathIB::Builder & aCommandPathBuilder) +void BuildCommandPath(CommandPathIB::Builder & aCommandPathBuilder) { aCommandPathBuilder.EndpointId(1).ClusterId(3).CommandId(4).EndOfCommandPathIB(); - NL_TEST_ASSERT(apSuite, aCommandPathBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aCommandPathBuilder.GetError(), CHIP_NO_ERROR); } -void ParseCommandPath(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseCommandPath(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; CommandPathIB::Parser commandPathParser; @@ -375,52 +398,55 @@ void ParseCommandPath(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) chip::CommandId commandId = 0; err = commandPathParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT commandPathParser.PrettyPrint(); #endif err = commandPathParser.GetEndpointId(&endpointId); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && endpointId == 1); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(endpointId, 1u); err = commandPathParser.GetClusterId(&clusterId); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && clusterId == 3); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(clusterId, 3u); err = commandPathParser.GetCommandId(&commandId); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && commandId == 4); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(commandId, 4u); } -void BuildEventDataIB(nlTestSuite * apSuite, EventDataIB::Builder & aEventDataIBBuilder) +void BuildEventDataIB(EventDataIB::Builder & aEventDataIBBuilder) { CHIP_ERROR err = CHIP_NO_ERROR; EventPathIB::Builder & eventPathBuilder = aEventDataIBBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, eventPathBuilder.GetError() == CHIP_NO_ERROR); - BuildEventPath(apSuite, eventPathBuilder); + EXPECT_EQ(eventPathBuilder.GetError(), CHIP_NO_ERROR); + BuildEventPath(eventPathBuilder); aEventDataIBBuilder.EventNumber(2).Priority(3).EpochTimestamp(4).SystemTimestamp(5).DeltaEpochTimestamp(6).DeltaSystemTimestamp( 7); err = aEventDataIBBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Construct test event data { chip::TLV::TLVWriter * pWriter = aEventDataIBBuilder.GetWriter(); chip::TLV::TLVType dummyType = chip::TLV::kTLVType_NotSpecified; err = pWriter->StartContainer(chip::TLV::ContextTag(chip::to_underlying(EventDataIB::Tag::kData)), chip::TLV::kTLVType_Structure, dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = pWriter->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = pWriter->EndContainer(dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } aEventDataIBBuilder.EndOfEventDataIB(); } -void ParseEventDataIB(nlTestSuite * apSuite, EventDataIB::Parser & aEventDataIBParser) +void ParseEventDataIB(EventDataIB::Parser & aEventDataIBParser) { CHIP_ERROR err = CHIP_NO_ERROR; uint8_t priorityLevel = 0; @@ -437,20 +463,31 @@ void ParseEventDataIB(nlTestSuite * apSuite, EventDataIB::Parser & aEventDataIBP { EventPathIB::Parser eventPath; err = aEventDataIBParser.GetPath(&eventPath); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = aEventDataIBParser.GetEventNumber(&number); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && number == 2); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(number, 2u); + err = aEventDataIBParser.GetPriority(&priorityLevel); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && priorityLevel == 3); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(priorityLevel, 3u); + err = aEventDataIBParser.GetEpochTimestamp(&EpochTimestamp); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && EpochTimestamp == 4); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(EpochTimestamp, 4u); + err = aEventDataIBParser.GetSystemTimestamp(&systemTimestamp); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && systemTimestamp == 5); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(systemTimestamp, 5u); + err = aEventDataIBParser.GetDeltaEpochTimestamp(&deltaUTCTimestamp); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && deltaUTCTimestamp == 6); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(deltaUTCTimestamp, 6u); + err = aEventDataIBParser.GetDeltaSystemTimestamp(&deltaSystemTimestamp); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && deltaSystemTimestamp == 7); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(deltaSystemTimestamp, 7u); { chip::TLV::TLVReader reader; @@ -458,35 +495,36 @@ void ParseEventDataIB(nlTestSuite * apSuite, EventDataIB::Parser & aEventDataIBP chip::TLV::TLVType container; aEventDataIBParser.GetData(&reader); err = reader.EnterContainer(container); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.Get(val); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && val); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(val); err = reader.ExitContainer(container); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } } } -void BuildEventStatusIB(nlTestSuite * apSuite, EventStatusIB::Builder & aEventStatusIBBuilder) +void BuildEventStatusIB(EventStatusIB::Builder & aEventStatusIBBuilder) { EventPathIB::Builder & eventPathBuilder = aEventStatusIBBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, aEventStatusIBBuilder.GetError() == CHIP_NO_ERROR); - BuildEventPath(apSuite, eventPathBuilder); + EXPECT_EQ(aEventStatusIBBuilder.GetError(), CHIP_NO_ERROR); + BuildEventPath(eventPathBuilder); StatusIB::Builder & statusIBBuilder = aEventStatusIBBuilder.CreateErrorStatus(); - NL_TEST_ASSERT(apSuite, statusIBBuilder.GetError() == CHIP_NO_ERROR); - BuildStatusIB(apSuite, statusIBBuilder); + EXPECT_EQ(statusIBBuilder.GetError(), CHIP_NO_ERROR); + BuildStatusIB(statusIBBuilder); aEventStatusIBBuilder.EndOfEventStatusIB(); - NL_TEST_ASSERT(apSuite, aEventStatusIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aEventStatusIBBuilder.GetError(), CHIP_NO_ERROR); } -void ParseEventStatusIB(nlTestSuite * apSuite, EventStatusIB::Parser & aEventStatusIBParser) +void ParseEventStatusIB(EventStatusIB::Parser & aEventStatusIBParser) { CHIP_ERROR err = CHIP_NO_ERROR; EventPathIB::Parser eventPathParser; @@ -495,23 +533,23 @@ void ParseEventStatusIB(nlTestSuite * apSuite, EventStatusIB::Parser & aEventSta aEventStatusIBParser.PrettyPrint(); #endif err = aEventStatusIBParser.GetPath(&eventPathParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = aEventStatusIBParser.GetErrorStatus(&statusParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void BuildEventReportIB(nlTestSuite * apSuite, EventReportIB::Builder & aEventReportIBBuilder) +void BuildEventReportIB(EventReportIB::Builder & aEventReportIBBuilder) { EventDataIB::Builder & eventDataIBBuilder = aEventReportIBBuilder.CreateEventData(); - NL_TEST_ASSERT(apSuite, aEventReportIBBuilder.GetError() == CHIP_NO_ERROR); - BuildEventDataIB(apSuite, eventDataIBBuilder); + EXPECT_EQ(aEventReportIBBuilder.GetError(), CHIP_NO_ERROR); + BuildEventDataIB(eventDataIBBuilder); aEventReportIBBuilder.EndOfEventReportIB(); - NL_TEST_ASSERT(apSuite, aEventReportIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aEventReportIBBuilder.GetError(), CHIP_NO_ERROR); } -void ParseEventReportIB(nlTestSuite * apSuite, EventReportIB::Parser & aEventReportIBParser) +void ParseEventReportIB(EventReportIB::Parser & aEventReportIBParser) { CHIP_ERROR err = CHIP_NO_ERROR; EventStatusIB::Parser eventStatusParser; @@ -522,45 +560,45 @@ void ParseEventReportIB(nlTestSuite * apSuite, EventReportIB::Parser & aEventRep #endif err = aEventReportIBParser.GetEventData(&eventDataParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void BuildEventReports(nlTestSuite * apSuite, EventReportIBs::Builder & aEventReportsBuilder) +void BuildEventReports(EventReportIBs::Builder & aEventReportsBuilder) { EventReportIB::Builder & eventReportIBBuilder = aEventReportsBuilder.CreateEventReport(); - NL_TEST_ASSERT(apSuite, aEventReportsBuilder.GetError() == CHIP_NO_ERROR); - BuildEventReportIB(apSuite, eventReportIBBuilder); + EXPECT_EQ(aEventReportsBuilder.GetError(), CHIP_NO_ERROR); + BuildEventReportIB(eventReportIBBuilder); aEventReportsBuilder.EndOfEventReports(); - NL_TEST_ASSERT(apSuite, aEventReportsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aEventReportsBuilder.GetError(), CHIP_NO_ERROR); } -void ParseEventReports(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseEventReports(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; EventReportIBs::Parser eventReportsParser; err = eventReportsParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT eventReportsParser.PrettyPrint(); #endif } -void BuildAttributeStatusIB(nlTestSuite * apSuite, AttributeStatusIB::Builder & aAttributeStatusIBBuilder) +void BuildAttributeStatusIB(AttributeStatusIB::Builder & aAttributeStatusIBBuilder) { AttributePathIB::Builder & attributePathBuilder = aAttributeStatusIBBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, attributePathBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributePathIB(apSuite, attributePathBuilder); + EXPECT_EQ(attributePathBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributePathIB(attributePathBuilder); StatusIB::Builder & statusIBBuilder = aAttributeStatusIBBuilder.CreateErrorStatus(); - NL_TEST_ASSERT(apSuite, statusIBBuilder.GetError() == CHIP_NO_ERROR); - BuildStatusIB(apSuite, statusIBBuilder); + EXPECT_EQ(statusIBBuilder.GetError(), CHIP_NO_ERROR); + BuildStatusIB(statusIBBuilder); aAttributeStatusIBBuilder.EndOfAttributeStatusIB(); - NL_TEST_ASSERT(apSuite, aAttributeStatusIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aAttributeStatusIBBuilder.GetError(), CHIP_NO_ERROR); } -void ParseAttributeStatusIB(nlTestSuite * apSuite, AttributeStatusIB::Parser & aAttributeStatusIBParser) +void ParseAttributeStatusIB(AttributeStatusIB::Parser & aAttributeStatusIBParser) { CHIP_ERROR err = CHIP_NO_ERROR; AttributePathIB::Parser attributePathParser; @@ -570,43 +608,43 @@ void ParseAttributeStatusIB(nlTestSuite * apSuite, AttributeStatusIB::Parser & a aAttributeStatusIBParser.PrettyPrint(); #endif err = aAttributeStatusIBParser.GetPath(&attributePathParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = aAttributeStatusIBParser.GetErrorStatus(&StatusIBParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void BuildAttributeStatuses(nlTestSuite * apSuite, AttributeStatusIBs::Builder & aAttributeStatusesBuilder) +void BuildAttributeStatuses(AttributeStatusIBs::Builder & aAttributeStatusesBuilder) { AttributeStatusIB::Builder & aAttributeStatusIBBuilder = aAttributeStatusesBuilder.CreateAttributeStatus(); - NL_TEST_ASSERT(apSuite, aAttributeStatusesBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributeStatusIB(apSuite, aAttributeStatusIBBuilder); + EXPECT_EQ(aAttributeStatusesBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributeStatusIB(aAttributeStatusIBBuilder); aAttributeStatusesBuilder.EndOfAttributeStatuses(); - NL_TEST_ASSERT(apSuite, aAttributeStatusesBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aAttributeStatusesBuilder.GetError(), CHIP_NO_ERROR); } -void ParseAttributeStatuses(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseAttributeStatuses(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; AttributeStatusIBs::Parser attributeStatusParser; err = attributeStatusParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT attributeStatusParser.PrettyPrint(); #endif } -void BuildAttributeDataIB(nlTestSuite * apSuite, AttributeDataIB::Builder & aAttributeDataIBBuilder) +void BuildAttributeDataIB(AttributeDataIB::Builder & aAttributeDataIBBuilder) { CHIP_ERROR err = CHIP_NO_ERROR; aAttributeDataIBBuilder.DataVersion(2); AttributePathIB::Builder & attributePathBuilder = aAttributeDataIBBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, aAttributeDataIBBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributePathIB(apSuite, attributePathBuilder); + EXPECT_EQ(aAttributeDataIBBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributePathIB(attributePathBuilder); // Construct attribute data { @@ -614,22 +652,22 @@ void BuildAttributeDataIB(nlTestSuite * apSuite, AttributeDataIB::Builder & aAtt chip::TLV::TLVType dummyType = chip::TLV::kTLVType_NotSpecified; err = pWriter->StartContainer(chip::TLV::ContextTag(chip::to_underlying(AttributeDataIB::Tag::kData)), chip::TLV::kTLVType_Structure, dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = pWriter->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = pWriter->EndContainer(dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } err = aAttributeDataIBBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); aAttributeDataIBBuilder.EndOfAttributeDataIB(); - NL_TEST_ASSERT(apSuite, aAttributeDataIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aAttributeDataIBBuilder.GetError(), CHIP_NO_ERROR); } -void ParseAttributeDataIB(nlTestSuite * apSuite, AttributeDataIB::Parser & aAttributeDataIBParser) +void ParseAttributeDataIB(AttributeDataIB::Parser & aAttributeDataIBParser) { CHIP_ERROR err = CHIP_NO_ERROR; AttributePathIB::Parser attributePathParser; @@ -638,10 +676,11 @@ void ParseAttributeDataIB(nlTestSuite * apSuite, AttributeDataIB::Parser & aAttr aAttributeDataIBParser.PrettyPrint(); #endif err = aAttributeDataIBParser.GetPath(&attributePathParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = aAttributeDataIBParser.GetDataVersion(&version); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && version == 2); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(version, 2u); { chip::TLV::TLVReader reader; @@ -649,52 +688,53 @@ void ParseAttributeDataIB(nlTestSuite * apSuite, AttributeDataIB::Parser & aAttr chip::TLV::TLVType container; aAttributeDataIBParser.GetData(&reader); err = reader.EnterContainer(container); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.Get(val); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && val); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(val); err = reader.ExitContainer(container); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } } -void BuildAttributeDataIBs(nlTestSuite * apSuite, AttributeDataIBs::Builder & aAttributeDataIBsBuilder) +void BuildAttributeDataIBs(AttributeDataIBs::Builder & aAttributeDataIBsBuilder) { AttributeDataIB::Builder & attributeDataIBBuilder = aAttributeDataIBsBuilder.CreateAttributeDataIBBuilder(); - NL_TEST_ASSERT(apSuite, aAttributeDataIBsBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributeDataIB(apSuite, attributeDataIBBuilder); + EXPECT_EQ(aAttributeDataIBsBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributeDataIB(attributeDataIBBuilder); aAttributeDataIBsBuilder.EndOfAttributeDataIBs(); - NL_TEST_ASSERT(apSuite, aAttributeDataIBsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aAttributeDataIBsBuilder.GetError(), CHIP_NO_ERROR); } -void ParseAttributeDataIBs(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseAttributeDataIBs(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; AttributeDataIBs::Parser AttributeDataIBsParser; err = AttributeDataIBsParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT AttributeDataIBsParser.PrettyPrint(); #endif } -void BuildAttributeReportIB(nlTestSuite * apSuite, AttributeReportIB::Builder & aAttributeReportIBBuilder) +void BuildAttributeReportIB(AttributeReportIB::Builder & aAttributeReportIBBuilder) { AttributeDataIB::Builder & attributeDataIBBuilder = aAttributeReportIBBuilder.CreateAttributeData(); - NL_TEST_ASSERT(apSuite, aAttributeReportIBBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributeDataIB(apSuite, attributeDataIBBuilder); + EXPECT_EQ(aAttributeReportIBBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributeDataIB(attributeDataIBBuilder); aAttributeReportIBBuilder.EndOfAttributeReportIB(); - NL_TEST_ASSERT(apSuite, aAttributeReportIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aAttributeReportIBBuilder.GetError(), CHIP_NO_ERROR); } -void ParseAttributeReportIB(nlTestSuite * apSuite, AttributeReportIB::Parser & aAttributeReportIBParser) +void ParseAttributeReportIB(AttributeReportIB::Parser & aAttributeReportIBParser) { CHIP_ERROR err = CHIP_NO_ERROR; AttributeStatusIB::Parser attributeStatusParser; @@ -704,38 +744,38 @@ void ParseAttributeReportIB(nlTestSuite * apSuite, AttributeReportIB::Parser & a aAttributeReportIBParser.PrettyPrint(); #endif err = aAttributeReportIBParser.GetAttributeData(&attributeDataParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void BuildAttributeReportIBs(nlTestSuite * apSuite, AttributeReportIBs::Builder & aAttributeReportIBsBuilder) +void BuildAttributeReportIBs(AttributeReportIBs::Builder & aAttributeReportIBsBuilder) { AttributeReportIB::Builder & attributeReportIBBuilder = aAttributeReportIBsBuilder.CreateAttributeReport(); - NL_TEST_ASSERT(apSuite, aAttributeReportIBsBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributeReportIB(apSuite, attributeReportIBBuilder); + EXPECT_EQ(aAttributeReportIBsBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributeReportIB(attributeReportIBBuilder); aAttributeReportIBsBuilder.EndOfAttributeReportIBs(); - NL_TEST_ASSERT(apSuite, aAttributeReportIBsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aAttributeReportIBsBuilder.GetError(), CHIP_NO_ERROR); } -void ParseAttributeReportIBs(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseAttributeReportIBs(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; AttributeReportIBs::Parser attributeReportIBsParser; err = attributeReportIBsParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT attributeReportIBsParser.PrettyPrint(); #endif } -void BuildCommandDataIB(nlTestSuite * apSuite, CommandDataIB::Builder & aCommandDataIBBuilder) +void BuildCommandDataIB(CommandDataIB::Builder & aCommandDataIBBuilder) { CHIP_ERROR err = CHIP_NO_ERROR; CommandPathIB::Builder & commandPathBuilder = aCommandDataIBBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, aCommandDataIBBuilder.GetError() == CHIP_NO_ERROR); - BuildCommandPath(apSuite, commandPathBuilder); + EXPECT_EQ(aCommandDataIBBuilder.GetError(), CHIP_NO_ERROR); + BuildCommandPath(commandPathBuilder); // Construct command data { @@ -743,20 +783,20 @@ void BuildCommandDataIB(nlTestSuite * apSuite, CommandDataIB::Builder & aCommand 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(err, CHIP_NO_ERROR); err = pWriter->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = pWriter->EndContainer(dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } aCommandDataIBBuilder.EndOfCommandDataIB(); - NL_TEST_ASSERT(apSuite, aCommandDataIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aCommandDataIBBuilder.GetError(), CHIP_NO_ERROR); } -void ParseCommandDataIB(nlTestSuite * apSuite, CommandDataIB::Parser & aCommandDataIBParser) +void ParseCommandDataIB(CommandDataIB::Parser & aCommandDataIBParser) { CHIP_ERROR err = CHIP_NO_ERROR; CommandPathIB::Parser commandPathParser; @@ -764,7 +804,7 @@ void ParseCommandDataIB(nlTestSuite * apSuite, CommandDataIB::Parser & aCommandD aCommandDataIBParser.PrettyPrint(); #endif err = aCommandDataIBParser.GetPath(&commandPathParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); { chip::TLV::TLVReader reader; @@ -772,34 +812,35 @@ void ParseCommandDataIB(nlTestSuite * apSuite, CommandDataIB::Parser & aCommandD chip::TLV::TLVType container; aCommandDataIBParser.GetFields(&reader); err = reader.EnterContainer(container); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reader.Get(val); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && val); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(val); err = reader.ExitContainer(container); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } } -void BuildCommandStatusIB(nlTestSuite * apSuite, CommandStatusIB::Builder & aCommandStatusIBBuilder) +void BuildCommandStatusIB(CommandStatusIB::Builder & aCommandStatusIBBuilder) { CommandPathIB::Builder & commandPathBuilder = aCommandStatusIBBuilder.CreatePath(); - NL_TEST_ASSERT(apSuite, aCommandStatusIBBuilder.GetError() == CHIP_NO_ERROR); - BuildCommandPath(apSuite, commandPathBuilder); + EXPECT_EQ(aCommandStatusIBBuilder.GetError(), CHIP_NO_ERROR); + BuildCommandPath(commandPathBuilder); StatusIB::Builder & statusIBBuilder = aCommandStatusIBBuilder.CreateErrorStatus(); - NL_TEST_ASSERT(apSuite, statusIBBuilder.GetError() == CHIP_NO_ERROR); - BuildStatusIB(apSuite, statusIBBuilder); + EXPECT_EQ(statusIBBuilder.GetError(), CHIP_NO_ERROR); + BuildStatusIB(statusIBBuilder); aCommandStatusIBBuilder.EndOfCommandStatusIB(); - NL_TEST_ASSERT(apSuite, aCommandStatusIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aCommandStatusIBBuilder.GetError(), CHIP_NO_ERROR); } -void ParseCommandStatusIB(nlTestSuite * apSuite, CommandStatusIB::Parser & aCommandStatusIBParser) +void ParseCommandStatusIB(CommandStatusIB::Parser & aCommandStatusIBParser) { CHIP_ERROR err = CHIP_NO_ERROR; CommandPathIB::Parser commandPathParser; @@ -808,37 +849,37 @@ void ParseCommandStatusIB(nlTestSuite * apSuite, CommandStatusIB::Parser & aComm aCommandStatusIBParser.PrettyPrint(); #endif err = aCommandStatusIBParser.GetPath(&commandPathParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = aCommandStatusIBParser.GetErrorStatus(&statusParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void BuildWrongInvokeResponseIB(nlTestSuite * apSuite, InvokeResponseIB::Builder & aInvokeResponseIBBuilder) +void BuildWrongInvokeResponseIB(InvokeResponseIB::Builder & aInvokeResponseIBBuilder) { aInvokeResponseIBBuilder.CreateCommand(); - NL_TEST_ASSERT(apSuite, aInvokeResponseIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aInvokeResponseIBBuilder.GetError(), CHIP_NO_ERROR); } -void BuildInvokeResponseIBWithCommandDataIB(nlTestSuite * apSuite, InvokeResponseIB::Builder & aInvokeResponseIBBuilder) +void BuildInvokeResponseIBWithCommandDataIB(InvokeResponseIB::Builder & aInvokeResponseIBBuilder) { CommandDataIB::Builder & commandDataBuilder = aInvokeResponseIBBuilder.CreateCommand(); - NL_TEST_ASSERT(apSuite, aInvokeResponseIBBuilder.GetError() == CHIP_NO_ERROR); - BuildCommandDataIB(apSuite, commandDataBuilder); + EXPECT_EQ(aInvokeResponseIBBuilder.GetError(), CHIP_NO_ERROR); + BuildCommandDataIB(commandDataBuilder); aInvokeResponseIBBuilder.EndOfInvokeResponseIB(); - NL_TEST_ASSERT(apSuite, aInvokeResponseIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aInvokeResponseIBBuilder.GetError(), CHIP_NO_ERROR); } -void BuildInvokeResponseIBWithCommandStatusIB(nlTestSuite * apSuite, InvokeResponseIB::Builder & aInvokeResponseIBBuilder) +void BuildInvokeResponseIBWithCommandStatusIB(InvokeResponseIB::Builder & aInvokeResponseIBBuilder) { CommandStatusIB::Builder & commandStatusBuilder = aInvokeResponseIBBuilder.CreateStatus(); - NL_TEST_ASSERT(apSuite, aInvokeResponseIBBuilder.GetError() == CHIP_NO_ERROR); - BuildCommandStatusIB(apSuite, commandStatusBuilder); + EXPECT_EQ(aInvokeResponseIBBuilder.GetError(), CHIP_NO_ERROR); + BuildCommandStatusIB(commandStatusBuilder); aInvokeResponseIBBuilder.EndOfInvokeResponseIB(); - NL_TEST_ASSERT(apSuite, aInvokeResponseIBBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aInvokeResponseIBBuilder.GetError(), CHIP_NO_ERROR); } -void ParseInvokeResponseIBWithCommandDataIB(nlTestSuite * apSuite, InvokeResponseIB::Parser & aInvokeResponseIBParser) +void ParseInvokeResponseIBWithCommandDataIB(InvokeResponseIB::Parser & aInvokeResponseIBParser) { CHIP_ERROR err = CHIP_NO_ERROR; CommandDataIB::Parser commandDataParser; @@ -847,10 +888,10 @@ void ParseInvokeResponseIBWithCommandDataIB(nlTestSuite * apSuite, InvokeRespons aInvokeResponseIBParser.PrettyPrint(); #endif err = aInvokeResponseIBParser.GetCommand(&commandDataParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void ParseInvokeResponseIBWithCommandStatusIB(nlTestSuite * apSuite, InvokeResponseIB::Parser & aInvokeResponseIBParser) +void ParseInvokeResponseIBWithCommandStatusIB(InvokeResponseIB::Parser & aInvokeResponseIBParser) { CHIP_ERROR err = CHIP_NO_ERROR; CommandDataIB::Parser commandDataParser; @@ -859,90 +900,90 @@ void ParseInvokeResponseIBWithCommandStatusIB(nlTestSuite * apSuite, InvokeRespo aInvokeResponseIBParser.PrettyPrint(); #endif err = aInvokeResponseIBParser.GetStatus(&statusIBParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } -void BuildInvokeRequests(nlTestSuite * apSuite, InvokeRequests::Builder & aInvokeRequestsBuilder) +void BuildInvokeRequests(InvokeRequests::Builder & aInvokeRequestsBuilder) { CommandDataIB::Builder & aCommandDataIBBuilder = aInvokeRequestsBuilder.CreateCommandData(); - NL_TEST_ASSERT(apSuite, aInvokeRequestsBuilder.GetError() == CHIP_NO_ERROR); - BuildCommandDataIB(apSuite, aCommandDataIBBuilder); + EXPECT_EQ(aInvokeRequestsBuilder.GetError(), CHIP_NO_ERROR); + BuildCommandDataIB(aCommandDataIBBuilder); aInvokeRequestsBuilder.EndOfInvokeRequests(); - NL_TEST_ASSERT(apSuite, aInvokeRequestsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aInvokeRequestsBuilder.GetError(), CHIP_NO_ERROR); } -void ParseInvokeRequests(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseInvokeRequests(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; InvokeRequests::Parser invokeRequestsParser; err = invokeRequestsParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT invokeRequestsParser.PrettyPrint(); #endif } -void BuildInvokeResponses(nlTestSuite * apSuite, InvokeResponseIBs::Builder & aInvokeResponsesBuilder) +void BuildInvokeResponses(InvokeResponseIBs::Builder & aInvokeResponsesBuilder) { InvokeResponseIB::Builder & invokeResponseIBBuilder = aInvokeResponsesBuilder.CreateInvokeResponse(); - NL_TEST_ASSERT(apSuite, aInvokeResponsesBuilder.GetError() == CHIP_NO_ERROR); - BuildInvokeResponseIBWithCommandDataIB(apSuite, invokeResponseIBBuilder); + EXPECT_EQ(aInvokeResponsesBuilder.GetError(), CHIP_NO_ERROR); + BuildInvokeResponseIBWithCommandDataIB(invokeResponseIBBuilder); aInvokeResponsesBuilder.EndOfInvokeResponses(); - NL_TEST_ASSERT(apSuite, aInvokeResponsesBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(aInvokeResponsesBuilder.GetError(), CHIP_NO_ERROR); } -void ParseInvokeResponses(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseInvokeResponses(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; InvokeResponseIBs::Parser invokeResponsesParser; err = invokeResponsesParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT invokeResponsesParser.PrettyPrint(); #endif } -void BuildInvokeRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVWriter & aWriter) +void BuildInvokeRequestMessage(chip::TLV::TLVWriter & aWriter) { CHIP_ERROR err = CHIP_NO_ERROR; InvokeRequestMessage::Builder invokeRequestMessageBuilder; err = invokeRequestMessageBuilder.Init(&aWriter); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); invokeRequestMessageBuilder.SuppressResponse(true); invokeRequestMessageBuilder.TimedRequest(true); InvokeRequests::Builder & invokeRequestsBuilder = invokeRequestMessageBuilder.CreateInvokeRequests(); - NL_TEST_ASSERT(apSuite, invokeRequestsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(invokeRequestsBuilder.GetError(), CHIP_NO_ERROR); - BuildInvokeRequests(apSuite, invokeRequestsBuilder); + BuildInvokeRequests(invokeRequestsBuilder); invokeRequestMessageBuilder.EndOfInvokeRequestMessage(); - NL_TEST_ASSERT(apSuite, invokeRequestMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(invokeRequestMessageBuilder.GetError(), CHIP_NO_ERROR); } -void ParseInvokeRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseInvokeRequestMessage(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; InvokeRequestMessage::Parser invokeRequestMessageParser; err = invokeRequestMessageParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); bool suppressResponse = false; bool timedRequest = false; invokeRequestMessageParser.GetSuppressResponse(&suppressResponse); invokeRequestMessageParser.GetTimedRequest(&timedRequest); - NL_TEST_ASSERT(apSuite, suppressResponse == true); - NL_TEST_ASSERT(apSuite, timedRequest == true); + EXPECT_TRUE(suppressResponse); + EXPECT_TRUE(timedRequest); #if CHIP_CONFIG_IM_PRETTY_PRINT invokeRequestMessageParser.PrettyPrint(); #endif - NL_TEST_ASSERT(apSuite, invokeRequestMessageParser.ExitContainer() == CHIP_NO_ERROR); + EXPECT_EQ(invokeRequestMessageParser.ExitContainer(), CHIP_NO_ERROR); } -void BuildInvokeResponseMessage(nlTestSuite * apSuite, chip::TLV::TLVWriter & aWriter) +void BuildInvokeResponseMessage(chip::TLV::TLVWriter & aWriter) { CHIP_ERROR err = CHIP_NO_ERROR; InvokeResponseMessage::Builder invokeResponseMessageBuilder; @@ -950,67 +991,67 @@ void BuildInvokeResponseMessage(nlTestSuite * apSuite, chip::TLV::TLVWriter & aW invokeResponseMessageBuilder.SuppressResponse(true); InvokeResponseIBs::Builder & invokeResponsesBuilder = invokeResponseMessageBuilder.CreateInvokeResponses(); - NL_TEST_ASSERT(apSuite, invokeResponseMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(invokeResponseMessageBuilder.GetError(), CHIP_NO_ERROR); - BuildInvokeResponses(apSuite, invokeResponsesBuilder); + BuildInvokeResponses(invokeResponsesBuilder); invokeResponseMessageBuilder.MoreChunkedMessages(true); - NL_TEST_ASSERT(apSuite, invokeResponseMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(invokeResponseMessageBuilder.GetError(), CHIP_NO_ERROR); invokeResponseMessageBuilder.EndOfInvokeResponseMessage(); - NL_TEST_ASSERT(apSuite, invokeResponseMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(invokeResponseMessageBuilder.GetError(), CHIP_NO_ERROR); } -void ParseInvokeResponseMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseInvokeResponseMessage(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; InvokeResponseMessage::Parser invokeResponseMessageParser; err = invokeResponseMessageParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); bool suppressResponse = false; err = invokeResponseMessageParser.GetSuppressResponse(&suppressResponse); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, suppressResponse == true); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(suppressResponse); bool moreChunkedMessages = true; err = invokeResponseMessageParser.GetMoreChunkedMessages(&suppressResponse); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, moreChunkedMessages == true); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(moreChunkedMessages); #if CHIP_CONFIG_IM_PRETTY_PRINT invokeResponseMessageParser.PrettyPrint(); #endif - NL_TEST_ASSERT(apSuite, invokeResponseMessageParser.ExitContainer() == CHIP_NO_ERROR); + EXPECT_EQ(invokeResponseMessageParser.ExitContainer(), CHIP_NO_ERROR); } -void BuildReportDataMessage(nlTestSuite * apSuite, chip::TLV::TLVWriter & aWriter) +void BuildReportDataMessage(chip::TLV::TLVWriter & aWriter) { CHIP_ERROR err = CHIP_NO_ERROR; ReportDataMessage::Builder reportDataMessageBuilder; err = reportDataMessageBuilder.Init(&aWriter); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reportDataMessageBuilder.SubscriptionId(2); - NL_TEST_ASSERT(apSuite, reportDataMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(reportDataMessageBuilder.GetError(), CHIP_NO_ERROR); AttributeReportIBs::Builder & attributeReportIBs = reportDataMessageBuilder.CreateAttributeReportIBs(); - NL_TEST_ASSERT(apSuite, reportDataMessageBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributeReportIBs(apSuite, attributeReportIBs); + EXPECT_EQ(reportDataMessageBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributeReportIBs(attributeReportIBs); EventReportIBs::Builder & eventReportIBs = reportDataMessageBuilder.CreateEventReports(); - NL_TEST_ASSERT(apSuite, reportDataMessageBuilder.GetError() == CHIP_NO_ERROR); - BuildEventReports(apSuite, eventReportIBs); + EXPECT_EQ(reportDataMessageBuilder.GetError(), CHIP_NO_ERROR); + BuildEventReports(eventReportIBs); reportDataMessageBuilder.MoreChunkedMessages(true).SuppressResponse(true); - 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); } -void ParseReportDataMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseReportDataMessage(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; ReportDataMessage::Parser reportDataParser; @@ -1026,55 +1067,58 @@ void ParseReportDataMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aReade reportDataParser.PrettyPrint(); #endif err = reportDataParser.GetSuppressResponse(&suppressResponse); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && suppressResponse); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(suppressResponse); err = reportDataParser.GetSubscriptionId(&subscriptionId); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && subscriptionId == 2); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(subscriptionId, 2u); err = reportDataParser.GetAttributeReportIBs(&attributeReportIBsParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reportDataParser.GetEventReports(&eventReportsParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = reportDataParser.GetMoreChunkedMessages(&moreChunkedMessages); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && moreChunkedMessages); - NL_TEST_ASSERT(apSuite, reportDataParser.ExitContainer() == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(moreChunkedMessages); + EXPECT_EQ(reportDataParser.ExitContainer(), CHIP_NO_ERROR); } -void BuildReadRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVWriter & aWriter) +void BuildReadRequestMessage(chip::TLV::TLVWriter & aWriter) { CHIP_ERROR err = CHIP_NO_ERROR; ReadRequestMessage::Builder readRequestBuilder; err = readRequestBuilder.Init(&aWriter); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); AttributePathIBs::Builder & attributePathIBs = readRequestBuilder.CreateAttributeRequests(); - NL_TEST_ASSERT(apSuite, readRequestBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributePathList(apSuite, attributePathIBs); + EXPECT_EQ(readRequestBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributePathList(attributePathIBs); EventPathIBs::Builder & eventPathList = readRequestBuilder.CreateEventRequests(); - NL_TEST_ASSERT(apSuite, readRequestBuilder.GetError() == CHIP_NO_ERROR); - BuildEventPaths(apSuite, eventPathList); + EXPECT_EQ(readRequestBuilder.GetError(), CHIP_NO_ERROR); + BuildEventPaths(eventPathList); EventFilterIBs::Builder & eventFilters = readRequestBuilder.CreateEventFilters(); - NL_TEST_ASSERT(apSuite, readRequestBuilder.GetError() == CHIP_NO_ERROR); - BuildEventFilters(apSuite, eventFilters); + EXPECT_EQ(readRequestBuilder.GetError(), CHIP_NO_ERROR); + BuildEventFilters(eventFilters); readRequestBuilder.IsFabricFiltered(true); - NL_TEST_ASSERT(apSuite, readRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(readRequestBuilder.GetError(), CHIP_NO_ERROR); DataVersionFilterIBs::Builder & dataVersionFilters = readRequestBuilder.CreateDataVersionFilters(); - NL_TEST_ASSERT(apSuite, readRequestBuilder.GetError() == CHIP_NO_ERROR); - BuildDataVersionFilterIBs(apSuite, dataVersionFilters); + EXPECT_EQ(readRequestBuilder.GetError(), CHIP_NO_ERROR); + BuildDataVersionFilterIBs(dataVersionFilters); readRequestBuilder.EndOfReadRequestMessage(); - NL_TEST_ASSERT(apSuite, readRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(readRequestBuilder.GetError(), CHIP_NO_ERROR); } -void ParseReadRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseReadRequestMessage(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -1086,53 +1130,54 @@ void ParseReadRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aRead bool isFabricFiltered = false; err = readRequestParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT readRequestParser.PrettyPrint(); #endif err = readRequestParser.GetAttributeRequests(&attributePathListParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = readRequestParser.GetDataVersionFilters(&dataVersionFilterIBsParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = readRequestParser.GetEventRequests(&eventPathListParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = readRequestParser.GetEventFilters(&eventFiltersParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = readRequestParser.GetIsFabricFiltered(&isFabricFiltered); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && isFabricFiltered); - NL_TEST_ASSERT(apSuite, readRequestParser.ExitContainer() == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(isFabricFiltered); + EXPECT_EQ(readRequestParser.ExitContainer(), CHIP_NO_ERROR); } -void BuildWriteRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVWriter & aWriter) +void BuildWriteRequestMessage(chip::TLV::TLVWriter & aWriter) { CHIP_ERROR err = CHIP_NO_ERROR; WriteRequestMessage::Builder writeRequestBuilder; err = writeRequestBuilder.Init(&aWriter); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); writeRequestBuilder.SuppressResponse(true); - NL_TEST_ASSERT(apSuite, writeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(writeRequestBuilder.GetError(), CHIP_NO_ERROR); writeRequestBuilder.TimedRequest(true); - NL_TEST_ASSERT(apSuite, writeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(writeRequestBuilder.GetError(), CHIP_NO_ERROR); AttributeDataIBs::Builder & attributeDataIBs = writeRequestBuilder.CreateWriteRequests(); - NL_TEST_ASSERT(apSuite, writeRequestBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributeDataIBs(apSuite, attributeDataIBs); + EXPECT_EQ(writeRequestBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributeDataIBs(attributeDataIBs); writeRequestBuilder.MoreChunkedMessages(true); - NL_TEST_ASSERT(apSuite, writeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(writeRequestBuilder.GetError(), CHIP_NO_ERROR); writeRequestBuilder.EndOfWriteRequestMessage(); - NL_TEST_ASSERT(apSuite, writeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(writeRequestBuilder.GetError(), CHIP_NO_ERROR); } -void ParseWriteRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseWriteRequestMessage(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -1143,97 +1188,100 @@ void ParseWriteRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aRea bool moreChunkedMessages = false; err = writeRequestParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT writeRequestParser.PrettyPrint(); #endif err = writeRequestParser.GetSuppressResponse(&suppressResponse); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && suppressResponse); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(suppressResponse); err = writeRequestParser.GetTimedRequest(&timeRequest); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && timeRequest); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(timeRequest); err = writeRequestParser.GetWriteRequests(&writeRequests); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = writeRequestParser.GetMoreChunkedMessages(&moreChunkedMessages); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR && moreChunkedMessages); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(moreChunkedMessages); } -void BuildWriteResponseMessage(nlTestSuite * apSuite, chip::TLV::TLVWriter & aWriter) +void BuildWriteResponseMessage(chip::TLV::TLVWriter & aWriter) { CHIP_ERROR err = CHIP_NO_ERROR; WriteResponseMessage::Builder writeResponseBuilder; err = writeResponseBuilder.Init(&aWriter); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); AttributeStatusIBs::Builder & attributeStatuses = writeResponseBuilder.CreateWriteResponses(); - NL_TEST_ASSERT(apSuite, writeResponseBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributeStatuses(apSuite, attributeStatuses); + EXPECT_EQ(writeResponseBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributeStatuses(attributeStatuses); writeResponseBuilder.EndOfWriteResponseMessage(); - NL_TEST_ASSERT(apSuite, writeResponseBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(writeResponseBuilder.GetError(), CHIP_NO_ERROR); } -void ParseWriteResponseMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseWriteResponseMessage(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; WriteResponseMessage::Parser writeResponseParser; AttributeStatusIBs::Parser attributeStatusesParser; err = writeResponseParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT writeResponseParser.PrettyPrint(); #endif err = writeResponseParser.GetWriteResponses(&attributeStatusesParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, writeResponseParser.ExitContainer() == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(writeResponseParser.ExitContainer(), CHIP_NO_ERROR); } -void BuildSubscribeRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVWriter & aWriter) +void BuildSubscribeRequestMessage(chip::TLV::TLVWriter & aWriter) { CHIP_ERROR err = CHIP_NO_ERROR; SubscribeRequestMessage::Builder subscribeRequestBuilder; err = subscribeRequestBuilder.Init(&aWriter); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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 & attributePathIBs = subscribeRequestBuilder.CreateAttributeRequests(); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributePathList(apSuite, attributePathIBs); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributePathList(attributePathIBs); EventPathIBs::Builder & eventPathList = subscribeRequestBuilder.CreateEventRequests(); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); - BuildEventPaths(apSuite, eventPathList); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); + BuildEventPaths(eventPathList); EventFilterIBs::Builder & eventFilters = subscribeRequestBuilder.CreateEventFilters(); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); - BuildEventFilters(apSuite, eventFilters); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); + BuildEventFilters(eventFilters); subscribeRequestBuilder.IsFabricFiltered(true); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); DataVersionFilterIBs::Builder & dataVersionFilters = subscribeRequestBuilder.CreateDataVersionFilters(); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); - BuildDataVersionFilterIBs(apSuite, dataVersionFilters); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); + BuildDataVersionFilterIBs(dataVersionFilters); subscribeRequestBuilder.EndOfSubscribeRequestMessage(); - NL_TEST_ASSERT(apSuite, subscribeRequestBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeRequestBuilder.GetError(), CHIP_NO_ERROR); } -void ParseSubscribeRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseSubscribeRequestMessage(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -1248,55 +1296,57 @@ void ParseSubscribeRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & bool isFabricFiltered = false; err = subscribeRequestParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT subscribeRequestParser.PrettyPrint(); #endif err = subscribeRequestParser.GetAttributeRequests(&attributePathListParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = subscribeRequestParser.GetDataVersionFilters(&dataVersionFilterIBsParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = subscribeRequestParser.GetEventRequests(&eventPathListParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = subscribeRequestParser.GetEventFilters(&eventFiltersParser); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = subscribeRequestParser.GetMinIntervalFloorSeconds(&minIntervalFloorSeconds); - NL_TEST_ASSERT(apSuite, minIntervalFloorSeconds == 2 && err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(minIntervalFloorSeconds, 2u); err = subscribeRequestParser.GetMaxIntervalCeilingSeconds(&maxIntervalCeilingSeconds); - NL_TEST_ASSERT(apSuite, maxIntervalCeilingSeconds == 3 && err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(maxIntervalCeilingSeconds, 3u); err = subscribeRequestParser.GetKeepSubscriptions(&keepExistingSubscription); - NL_TEST_ASSERT(apSuite, keepExistingSubscription && err == CHIP_NO_ERROR); + EXPECT_TRUE(keepExistingSubscription); err = subscribeRequestParser.GetIsFabricFiltered(&isFabricFiltered); - NL_TEST_ASSERT(apSuite, isFabricFiltered && err == CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, subscribeRequestParser.ExitContainer() == CHIP_NO_ERROR); + EXPECT_TRUE(isFabricFiltered); + EXPECT_EQ(subscribeRequestParser.ExitContainer(), CHIP_NO_ERROR); } -void BuildSubscribeResponseMessage(nlTestSuite * apSuite, chip::TLV::TLVWriter & aWriter) +void BuildSubscribeResponseMessage(chip::TLV::TLVWriter & aWriter) { CHIP_ERROR err = CHIP_NO_ERROR; SubscribeResponseMessage::Builder subscribeResponseBuilder; err = subscribeResponseBuilder.Init(&aWriter); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); subscribeResponseBuilder.SubscriptionId(1); - NL_TEST_ASSERT(apSuite, subscribeResponseBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeResponseBuilder.GetError(), CHIP_NO_ERROR); subscribeResponseBuilder.MaxInterval(2); - NL_TEST_ASSERT(apSuite, subscribeResponseBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeResponseBuilder.GetError(), CHIP_NO_ERROR); subscribeResponseBuilder.EndOfSubscribeResponseMessage(); - NL_TEST_ASSERT(apSuite, subscribeResponseBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeResponseBuilder.GetError(), CHIP_NO_ERROR); } -void ParseSubscribeResponseMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseSubscribeResponseMessage(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -1304,32 +1354,34 @@ void ParseSubscribeResponseMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & chip::SubscriptionId subscriptionId = 0; uint16_t maxInterval = 0; err = subscribeResponseParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT subscribeResponseParser.PrettyPrint(); #endif err = subscribeResponseParser.GetSubscriptionId(&subscriptionId); - NL_TEST_ASSERT(apSuite, subscriptionId == 1 && err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(subscriptionId, 1u); err = subscribeResponseParser.GetMaxInterval(&maxInterval); - NL_TEST_ASSERT(apSuite, maxInterval == 2 && err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(maxInterval, 2u); - NL_TEST_ASSERT(apSuite, subscribeResponseParser.ExitContainer() == CHIP_NO_ERROR); + EXPECT_EQ(subscribeResponseParser.ExitContainer(), CHIP_NO_ERROR); } -void BuildTimedRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVWriter & aWriter) +void BuildTimedRequestMessage(chip::TLV::TLVWriter & aWriter) { CHIP_ERROR err = CHIP_NO_ERROR; TimedRequestMessage::Builder TimedRequestMessageBuilder; err = TimedRequestMessageBuilder.Init(&aWriter); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); TimedRequestMessageBuilder.TimeoutMs(1); - NL_TEST_ASSERT(apSuite, TimedRequestMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(TimedRequestMessageBuilder.GetError(), CHIP_NO_ERROR); } -void ParseTimedRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader) +void ParseTimedRequestMessage(chip::TLV::TLVReader & aReader) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -1337,17 +1389,19 @@ void ParseTimedRequestMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aRea uint16_t timeout = 0; err = timedRequestMessageParser.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT timedRequestMessageParser.PrettyPrint(); #endif err = timedRequestMessageParser.GetTimeoutMs(&timeout); - NL_TEST_ASSERT(apSuite, timeout == 1 && err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, timedRequestMessageParser.ExitContainer() == CHIP_NO_ERROR); + EXPECT_EQ(timeout, 1u); + + EXPECT_EQ(timedRequestMessageParser.ExitContainer(), CHIP_NO_ERROR); } -void DataVersionFilterIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestDataVersionFilterIB) { CHIP_ERROR err = CHIP_NO_ERROR; DataVersionFilterIB::Builder dataVersionFilterIBBuilder; @@ -1355,20 +1409,20 @@ void DataVersionFilterIBTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); dataVersionFilterIBBuilder.Init(&writer); - BuildDataVersionFilterIB(apSuite, dataVersionFilterIBBuilder); + BuildDataVersionFilterIB(dataVersionFilterIBBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseDataVersionFilterIB(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseDataVersionFilterIB(reader); } -void DataVersionFilterIBsTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestDataVersionFilterIBs) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -1377,22 +1431,22 @@ void DataVersionFilterIBsTest(nlTestSuite * apSuite, void * apContext) writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); err = dataVersionFilterIBsBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - BuildDataVersionFilterIBs(apSuite, dataVersionFilterIBsBuilder); + BuildDataVersionFilterIBs(dataVersionFilterIBsBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseDataVersionFilterIBs(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseDataVersionFilterIBs(reader); } -void EventFilterTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestEventFilter) { CHIP_ERROR err = CHIP_NO_ERROR; EventFilterIB::Builder eventFilterBuilder; @@ -1400,20 +1454,20 @@ void EventFilterTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); eventFilterBuilder.Init(&writer); - BuildEventFilterIB(apSuite, eventFilterBuilder); + BuildEventFilterIB(eventFilterBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseEventFilterIB(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseEventFilterIB(reader); } -void EventFiltersTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestEventFilters) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -1423,22 +1477,22 @@ void EventFiltersTest(nlTestSuite * apSuite, void * apContext) writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); err = eventFiltersBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - BuildEventFilters(apSuite, eventFiltersBuilder); + BuildEventFilters(eventFiltersBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseEventFilters(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseEventFilters(reader); } -void ClusterPathIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestClusterPathIB) { CHIP_ERROR err = CHIP_NO_ERROR; ClusterPathIB::Builder clusterPathBuilder; @@ -1446,21 +1500,21 @@ void ClusterPathIBTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); clusterPathBuilder.Init(&writer); - BuildClusterPathIB(apSuite, clusterPathBuilder); + BuildClusterPathIB(clusterPathBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ParseClusterPathIB(apSuite, reader); + ParseClusterPathIB(reader); } -void AttributePathTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestAttributePath) { CHIP_ERROR err = CHIP_NO_ERROR; AttributePathIB::Builder attributePathBuilder; @@ -1468,21 +1522,21 @@ void AttributePathTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); attributePathBuilder.Init(&writer); - BuildAttributePathIB(apSuite, attributePathBuilder); + BuildAttributePathIB(attributePathBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ParseAttributePathIB(apSuite, reader); + ParseAttributePathIB(reader); } -void AttributePathListTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestAttributePathList) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -1492,22 +1546,22 @@ void AttributePathListTest(nlTestSuite * apSuite, void * apContext) writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); err = attributePathListBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - BuildAttributePathList(apSuite, attributePathListBuilder); + BuildAttributePathList(attributePathListBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseAttributePathList(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseAttributePathList(reader); } -void EventPathTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestEventPath) { CHIP_ERROR err = CHIP_NO_ERROR; EventPathIB::Parser eventPathParser; @@ -1516,22 +1570,22 @@ void EventPathTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); eventPathBuilder.Init(&writer); - BuildEventPath(apSuite, eventPathBuilder); + BuildEventPath(eventPathBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); eventPathParser.Init(reader); - ParseEventPath(apSuite, eventPathParser); + ParseEventPath(eventPathParser); } -void EventPathsTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestEventPaths) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -1541,22 +1595,22 @@ void EventPathsTest(nlTestSuite * apSuite, void * apContext) writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); err = eventPathListBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - BuildEventPaths(apSuite, eventPathListBuilder); + BuildEventPaths(eventPathListBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseEventPaths(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseEventPaths(reader); } -void CommandPathIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestCommandPathIB) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -1564,24 +1618,24 @@ void CommandPathIBTest(nlTestSuite * apSuite, void * apContext) CommandPathIB::Builder commandPathBuilder; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); err = commandPathBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - BuildCommandPath(apSuite, commandPathBuilder); + BuildCommandPath(commandPathBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ParseCommandPath(apSuite, reader); + ParseCommandPath(reader); } -void EventDataIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestEventDataIB) { CHIP_ERROR err = CHIP_NO_ERROR; EventDataIB::Builder eventDataIBBuilder; @@ -1590,22 +1644,22 @@ void EventDataIBTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); eventDataIBBuilder.Init(&writer); - BuildEventDataIB(apSuite, eventDataIBBuilder); + BuildEventDataIB(eventDataIBBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); eventDataIBParser.Init(reader); - ParseEventDataIB(apSuite, eventDataIBParser); + ParseEventDataIB(eventDataIBParser); } -void EventReportIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestEventReportIB) { CHIP_ERROR err = CHIP_NO_ERROR; EventReportIB::Builder eventReportIBBuilder; @@ -1614,22 +1668,22 @@ void EventReportIBTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); eventReportIBBuilder.Init(&writer); - BuildEventReportIB(apSuite, eventReportIBBuilder); + BuildEventReportIB(eventReportIBBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); eventReportIBParser.Init(reader); - ParseEventReportIB(apSuite, eventReportIBParser); + ParseEventReportIB(eventReportIBParser); } -void EventReportsTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestEventReports) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -1637,20 +1691,20 @@ void EventReportsTest(nlTestSuite * apSuite, void * apContext) EventReportIBs::Builder eventReportsBuilder; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); eventReportsBuilder.Init(&writer); - BuildEventReports(apSuite, eventReportsBuilder); + BuildEventReports(eventReportsBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseEventReports(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseEventReports(reader); } -void EmptyEventReportsTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestEmptyEventReports) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -1659,20 +1713,20 @@ void EmptyEventReportsTest(nlTestSuite * apSuite, void * apContext) writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); eventReportsBuilder.Init(&writer); eventReportsBuilder.EndOfEventReports(); - NL_TEST_ASSERT(apSuite, eventReportsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(eventReportsBuilder.GetError(), CHIP_NO_ERROR); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseEventReports(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseEventReports(reader); } -void AttributeReportIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestAttributeReportIB) { CHIP_ERROR err = CHIP_NO_ERROR; AttributeReportIB::Builder attributeReportIBBuilder; @@ -1681,22 +1735,22 @@ void AttributeReportIBTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); attributeReportIBBuilder.Init(&writer); - BuildAttributeReportIB(apSuite, attributeReportIBBuilder); + BuildAttributeReportIB(attributeReportIBBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); attributeReportIBParser.Init(reader); - ParseAttributeReportIB(apSuite, attributeReportIBParser); + ParseAttributeReportIB(attributeReportIBParser); } -void AttributeReportIBsTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestAttributeReportIBs) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -1704,20 +1758,20 @@ void AttributeReportIBsTest(nlTestSuite * apSuite, void * apContext) AttributeReportIBs::Builder attributeReportIBsBuilder; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); attributeReportIBsBuilder.Init(&writer); - BuildAttributeReportIBs(apSuite, attributeReportIBsBuilder); + BuildAttributeReportIBs(attributeReportIBsBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseAttributeReportIBs(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseAttributeReportIBs(reader); } -void EmptyAttributeReportIBsTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestEmptyAttributeReportIBs) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -1726,20 +1780,20 @@ void EmptyAttributeReportIBsTest(nlTestSuite * apSuite, void * apContext) writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); attributeReportIBsBuilder.Init(&writer); attributeReportIBsBuilder.EndOfAttributeReportIBs(); - NL_TEST_ASSERT(apSuite, attributeReportIBsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeReportIBsBuilder.GetError(), CHIP_NO_ERROR); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseAttributeReportIBs(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseAttributeReportIBs(reader); } -void StatusIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestStatusIB) { CHIP_ERROR err = CHIP_NO_ERROR; StatusIB::Builder statusIBBuilder; @@ -1748,22 +1802,22 @@ void StatusIBTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); statusIBBuilder.Init(&writer); - BuildStatusIB(apSuite, statusIBBuilder); + BuildStatusIB(statusIBBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); StatusIBParser.Init(reader); - ParseStatusIB(apSuite, StatusIBParser); + ParseStatusIB(StatusIBParser); } -void EventStatusIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestEventStatusIB) { CHIP_ERROR err = CHIP_NO_ERROR; EventStatusIB::Builder eventStatusIBBuilder; @@ -1772,22 +1826,22 @@ void EventStatusIBTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); eventStatusIBBuilder.Init(&writer); - BuildEventStatusIB(apSuite, eventStatusIBBuilder); + BuildEventStatusIB(eventStatusIBBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); eventStatusIBParser.Init(reader); - ParseEventStatusIB(apSuite, eventStatusIBParser); + ParseEventStatusIB(eventStatusIBParser); } -void AttributeStatusIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestAttributeStatusIB) { CHIP_ERROR err = CHIP_NO_ERROR; AttributeStatusIB::Builder attributeStatusIBBuilder; @@ -1796,22 +1850,22 @@ void AttributeStatusIBTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); attributeStatusIBBuilder.Init(&writer); - BuildAttributeStatusIB(apSuite, attributeStatusIBBuilder); + BuildAttributeStatusIB(attributeStatusIBBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); attributeStatusIBParser.Init(reader); - ParseAttributeStatusIB(apSuite, attributeStatusIBParser); + ParseAttributeStatusIB(attributeStatusIBParser); } -void AttributeStatusesTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestAttributeStatuses) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -1819,21 +1873,21 @@ void AttributeStatusesTest(nlTestSuite * apSuite, void * apContext) writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); AttributeStatusIBs::Builder attributeStatusesBuilder; err = attributeStatusesBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - BuildAttributeStatuses(apSuite, attributeStatusesBuilder); + EXPECT_EQ(err, CHIP_NO_ERROR); + BuildAttributeStatuses(attributeStatusesBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseAttributeStatuses(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseAttributeStatuses(reader); } -void AttributeDataIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestAttributeDataIB) { CHIP_ERROR err = CHIP_NO_ERROR; AttributeDataIB::Builder AttributeDataIBBuilder; @@ -1842,22 +1896,22 @@ void AttributeDataIBTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); AttributeDataIBBuilder.Init(&writer); - BuildAttributeDataIB(apSuite, AttributeDataIBBuilder); + BuildAttributeDataIB(AttributeDataIBBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); AttributeDataIBParser.Init(reader); - ParseAttributeDataIB(apSuite, AttributeDataIBParser); + ParseAttributeDataIB(AttributeDataIBParser); } -void AttributeDataIBsTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestAttributeDataIBs) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -1865,20 +1919,20 @@ void AttributeDataIBsTest(nlTestSuite * apSuite, void * apContext) writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); AttributeDataIBs::Builder AttributeDataIBsBuilder; AttributeDataIBsBuilder.Init(&writer); - BuildAttributeDataIBs(apSuite, AttributeDataIBsBuilder); + BuildAttributeDataIBs(AttributeDataIBsBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseAttributeDataIBs(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseAttributeDataIBs(reader); } -void CommandDataIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestCommandDataIB) { CHIP_ERROR err = CHIP_NO_ERROR; CommandDataIB::Builder commandDataIBBuilder; @@ -1887,22 +1941,22 @@ void CommandDataIBTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); commandDataIBBuilder.Init(&writer); - BuildCommandDataIB(apSuite, commandDataIBBuilder); + BuildCommandDataIB(commandDataIBBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); commandDataIBParser.Init(reader); - ParseCommandDataIB(apSuite, commandDataIBParser); + ParseCommandDataIB(commandDataIBParser); } -void CommandStatusIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestCommandStatusIB) { CHIP_ERROR err = CHIP_NO_ERROR; CommandStatusIB::Builder commandStatusIBBuilder; @@ -1911,22 +1965,22 @@ void CommandStatusIBTest(nlTestSuite * apSuite, void * apContext) chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); commandStatusIBBuilder.Init(&writer); - BuildCommandStatusIB(apSuite, commandStatusIBBuilder); + BuildCommandStatusIB(commandStatusIBBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); commandStatusIBParser.Init(reader); - ParseCommandStatusIB(apSuite, commandStatusIBParser); + ParseCommandStatusIB(commandStatusIBParser); } -void InvokeResponseIBWithCommandDataIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestInvokeResponseIBWithCommandDataIB) { CHIP_ERROR err = CHIP_NO_ERROR; InvokeResponseIB::Builder invokeResponseIBBuilder; @@ -1935,22 +1989,22 @@ void InvokeResponseIBWithCommandDataIBTest(nlTestSuite * apSuite, void * apConte chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); invokeResponseIBBuilder.Init(&writer); - BuildInvokeResponseIBWithCommandDataIB(apSuite, invokeResponseIBBuilder); + BuildInvokeResponseIBWithCommandDataIB(invokeResponseIBBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); invokeResponseIBParser.Init(reader); - ParseInvokeResponseIBWithCommandDataIB(apSuite, invokeResponseIBParser); + ParseInvokeResponseIBWithCommandDataIB(invokeResponseIBParser); } -void InvokeResponseIBWithCommandStatusIBTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestInvokeResponseIBWithCommandStatusIB) { CHIP_ERROR err = CHIP_NO_ERROR; InvokeResponseIB::Builder invokeResponseIBBuilder; @@ -1959,22 +2013,22 @@ void InvokeResponseIBWithCommandStatusIBTest(nlTestSuite * apSuite, void * apCon chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); invokeResponseIBBuilder.Init(&writer); - BuildInvokeResponseIBWithCommandStatusIB(apSuite, invokeResponseIBBuilder); + BuildInvokeResponseIBWithCommandStatusIB(invokeResponseIBBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); invokeResponseIBParser.Init(reader); - ParseInvokeResponseIBWithCommandStatusIB(apSuite, invokeResponseIBParser); + ParseInvokeResponseIBWithCommandStatusIB(invokeResponseIBParser); } -void InvokeResponseIBWithMalformDataTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestInvokeResponseIBWithMalformData) { CHIP_ERROR err = CHIP_NO_ERROR; InvokeResponseIB::Builder invokeResponseIBBuilder; @@ -1983,22 +2037,22 @@ void InvokeResponseIBWithMalformDataTest(nlTestSuite * apSuite, void * apContext chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); invokeResponseIBBuilder.Init(&writer); - BuildWrongInvokeResponseIB(apSuite, invokeResponseIBBuilder); + BuildWrongInvokeResponseIB(invokeResponseIBBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = invokeResponseIBParser.Init(reader); - NL_TEST_ASSERT(apSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); } -void InvokeRequestsTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestInvokeRequests) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -2006,20 +2060,20 @@ void InvokeRequestsTest(nlTestSuite * apSuite, void * apContext) InvokeRequests::Builder invokeRequestsBuilder; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); invokeRequestsBuilder.Init(&writer); - BuildInvokeRequests(apSuite, invokeRequestsBuilder); + BuildInvokeRequests(invokeRequestsBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseInvokeRequests(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseInvokeRequests(reader); } -void InvokeResponsesTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestInvokeResponses) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -2027,37 +2081,37 @@ void InvokeResponsesTest(nlTestSuite * apSuite, void * apContext) InvokeResponseIBs::Builder invokeResponsesBuilder; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); invokeResponsesBuilder.Init(&writer); - BuildInvokeResponses(apSuite, invokeResponsesBuilder); + BuildInvokeResponses(invokeResponsesBuilder); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - ParseInvokeResponses(apSuite, reader); + EXPECT_EQ(err, CHIP_NO_ERROR); + ParseInvokeResponses(reader); } -void InvokeInvokeRequestMessageTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestInvokeInvokeRequestMessage) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); - BuildInvokeRequestMessage(apSuite, writer); + BuildInvokeRequestMessage(writer); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); - ParseInvokeRequestMessage(apSuite, reader); + ParseInvokeRequestMessage(reader); } -void InvokeRequestMessageEndOfMessageReservationTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestInvokeRequestMessageEndOfMessageReservation) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -2065,18 +2119,18 @@ void InvokeRequestMessageEndOfMessageReservationTest(nlTestSuite * apSuite, void const uint32_t kSmallBufferSize = 100; writer.Init(chip::System::PacketBufferHandle::New(kSmallBufferSize, /* aReservedSize = */ 0), /* useChainedBuffers = */ false); err = invokeRequestMessageBuilder.InitWithEndBufferReserved(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t remainingLengthAfterInitWithReservation = writer.GetRemainingFreeLength(); err = invokeRequestMessageBuilder.EndOfInvokeRequestMessage(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t remainingLengthAfterEndingInvokeRequestMessage = writer.GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingLengthAfterInitWithReservation == remainingLengthAfterEndingInvokeRequestMessage); + EXPECT_EQ(remainingLengthAfterInitWithReservation, remainingLengthAfterEndingInvokeRequestMessage); } -void InvokeRequestsEndOfRequestReservationTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestInvokeRequestsEndOfRequestReservation) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -2084,41 +2138,41 @@ void InvokeRequestsEndOfRequestReservationTest(nlTestSuite * apSuite, void * apC const uint32_t kSmallBufferSize = 100; writer.Init(chip::System::PacketBufferHandle::New(kSmallBufferSize, /* aReservedSize = */ 0), /* useChainedBuffers = */ false); err = invokeRequestMessageBuilder.InitWithEndBufferReserved(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); invokeRequestMessageBuilder.CreateInvokeRequests(/* aReserveEndBuffer = */ true); InvokeRequests::Builder & invokeRequestsBuilder = invokeRequestMessageBuilder.GetInvokeRequests(); err = invokeRequestsBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); auto * invokeRequestsWriter = invokeRequestsBuilder.GetWriter(); uint32_t remainingLengthAfterInitWithReservation = invokeRequestsWriter->GetRemainingFreeLength(); err = invokeRequestsBuilder.EndOfInvokeRequests(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t remainingLengthAfterEndingInvokeRequests = invokeRequestsWriter->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingLengthAfterInitWithReservation == remainingLengthAfterEndingInvokeRequests); + EXPECT_EQ(remainingLengthAfterInitWithReservation, remainingLengthAfterEndingInvokeRequests); } -void InvokeInvokeResponseMessageTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestInvokeInvokeResponseMessage) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); - BuildInvokeResponseMessage(apSuite, writer); + BuildInvokeResponseMessage(writer); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); - ParseInvokeResponseMessage(apSuite, reader); + ParseInvokeResponseMessage(reader); } -void InvokeResponseMessageEndOfMessageReservationTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestInvokeResponseMessageEndOfMessageReservation) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -2126,17 +2180,17 @@ void InvokeResponseMessageEndOfMessageReservationTest(nlTestSuite * apSuite, voi const uint32_t kSmallBufferSize = 100; writer.Init(chip::System::PacketBufferHandle::New(kSmallBufferSize, /* aReservedSize = */ 0), /* useChainedBuffers = */ false); err = invokeResponseMessageBuilder.InitWithEndBufferReserved(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t remainingLengthAfterInitWithReservation = writer.GetRemainingFreeLength(); err = invokeResponseMessageBuilder.EndOfInvokeResponseMessage(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t remainingLengthAfterEndingInvokeResponseMessage = writer.GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingLengthAfterInitWithReservation == remainingLengthAfterEndingInvokeResponseMessage); + EXPECT_EQ(remainingLengthAfterInitWithReservation, remainingLengthAfterEndingInvokeResponseMessage); } -void InvokeResponseMessageReservationForEndandMoreChunkTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestInvokeResponseMessageReservationForEndandMoreChunk) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -2144,22 +2198,22 @@ void InvokeResponseMessageReservationForEndandMoreChunkTest(nlTestSuite * apSuit const uint32_t kSmallBufferSize = 100; writer.Init(chip::System::PacketBufferHandle::New(kSmallBufferSize, /* aReservedSize = */ 0), /* useChainedBuffers = */ false); err = invokeResponseMessageBuilder.InitWithEndBufferReserved(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = invokeResponseMessageBuilder.ReserveSpaceForMoreChunkedMessages(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t remainingLengthAllReservations = writer.GetRemainingFreeLength(); invokeResponseMessageBuilder.MoreChunkedMessages(/* aMoreChunkedMessages = */ true); - NL_TEST_ASSERT(apSuite, invokeResponseMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(invokeResponseMessageBuilder.GetError(), CHIP_NO_ERROR); err = invokeResponseMessageBuilder.EndOfInvokeResponseMessage(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t remainingLengthAfterEndingInvokeResponseMessage = writer.GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingLengthAllReservations == remainingLengthAfterEndingInvokeResponseMessage); + EXPECT_EQ(remainingLengthAllReservations, remainingLengthAfterEndingInvokeResponseMessage); } -void InvokeResponsesEndOfResponseReservationTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestInvokeResponsesEndOfResponseReservation) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; @@ -2167,142 +2221,142 @@ void InvokeResponsesEndOfResponseReservationTest(nlTestSuite * apSuite, void * a const uint32_t kSmallBufferSize = 100; writer.Init(chip::System::PacketBufferHandle::New(kSmallBufferSize, /* aReservedSize = */ 0), /* useChainedBuffers = */ false); err = invokeResponseMessageBuilder.InitWithEndBufferReserved(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); invokeResponseMessageBuilder.CreateInvokeResponses(/* aReserveEndBuffer = */ true); InvokeResponseIBs::Builder & invokeResponsesBuilder = invokeResponseMessageBuilder.GetInvokeResponses(); err = invokeResponsesBuilder.GetError(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); auto * invokeResponsesWriter = invokeResponsesBuilder.GetWriter(); uint32_t remainingLengthAfterInitWithReservation = invokeResponsesWriter->GetRemainingFreeLength(); err = invokeResponsesBuilder.EndOfInvokeResponses(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t remainingLengthAfterEndingInvokeResponses = invokeResponsesWriter->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingLengthAfterInitWithReservation == remainingLengthAfterEndingInvokeResponses); + EXPECT_EQ(remainingLengthAfterInitWithReservation, remainingLengthAfterEndingInvokeResponses); } -void ReportDataMessageTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestReportDataMessage) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); - BuildReportDataMessage(apSuite, writer); + BuildReportDataMessage(writer); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); - ParseReportDataMessage(apSuite, reader); + ParseReportDataMessage(reader); } -void ReadRequestMessageTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestReadRequestMessage) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); - BuildReadRequestMessage(apSuite, writer); + BuildReadRequestMessage(writer); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); - ParseReadRequestMessage(apSuite, reader); + ParseReadRequestMessage(reader); } -void WriteRequestMessageTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestWriteRequestMessage) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); - BuildWriteRequestMessage(apSuite, writer); + BuildWriteRequestMessage(writer); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); - ParseWriteRequestMessage(apSuite, reader); + ParseWriteRequestMessage(reader); } -void WriteResponseMessageTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestWriteResponseMessage) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); - BuildWriteResponseMessage(apSuite, writer); + BuildWriteResponseMessage(writer); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); - ParseWriteResponseMessage(apSuite, reader); + ParseWriteResponseMessage(reader); } -void SubscribeRequestMessageTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestSubscribeRequestMessage) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); - BuildSubscribeRequestMessage(apSuite, writer); + BuildSubscribeRequestMessage(writer); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); - ParseSubscribeRequestMessage(apSuite, reader); + ParseSubscribeRequestMessage(reader); } -void SubscribeResponseMessageTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestSubscribeResponseMessage) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); - BuildSubscribeResponseMessage(apSuite, writer); + BuildSubscribeResponseMessage(writer); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); - ParseSubscribeResponseMessage(apSuite, reader); + ParseSubscribeResponseMessage(reader); } -void TimedRequestMessageTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestTimedRequestMessage) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); - BuildTimedRequestMessage(apSuite, writer); + BuildTimedRequestMessage(writer); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); - ParseTimedRequestMessage(apSuite, reader); + ParseTimedRequestMessage(reader); } -void CheckPointRollbackTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestMessageDef, TestCheckPointRollback) { CHIP_ERROR err = CHIP_NO_ERROR; size_t NumDataElement = 0; @@ -2316,32 +2370,32 @@ void CheckPointRollbackTest(nlTestSuite * apSuite, void * apContext) // encode one attribute element AttributeDataIB::Builder & attributeDataIBBuilder1 = attributeDataIBsBuilder.CreateAttributeDataIBBuilder(); - NL_TEST_ASSERT(apSuite, attributeDataIBsBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributeDataIB(apSuite, attributeDataIBBuilder1); + EXPECT_EQ(attributeDataIBsBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributeDataIB(attributeDataIBBuilder1); // checkpoint attributeDataIBsBuilder.Checkpoint(checkpoint); // encode another attribute element AttributeDataIB::Builder & attributeDataIBBuilder2 = attributeDataIBsBuilder.CreateAttributeDataIBBuilder(); - NL_TEST_ASSERT(apSuite, attributeDataIBsBuilder.GetError() == CHIP_NO_ERROR); - BuildAttributeDataIB(apSuite, attributeDataIBBuilder2); + EXPECT_EQ(attributeDataIBsBuilder.GetError(), CHIP_NO_ERROR); + BuildAttributeDataIB(attributeDataIBBuilder2); // rollback to previous checkpoint attributeDataIBsBuilder.Rollback(checkpoint); attributeDataIBsBuilder.EndOfAttributeDataIBs(); - NL_TEST_ASSERT(apSuite, attributeDataIBsBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(attributeDataIBsBuilder.GetError(), CHIP_NO_ERROR); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); DebugPrettyPrint(buf); reader.Init(std::move(buf)); err = reader.Next(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = AttributeDataIBsParser.Init(reader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT AttributeDataIBsParser.PrettyPrint(); @@ -2351,101 +2405,7 @@ void CheckPointRollbackTest(nlTestSuite * apSuite, void * apContext) ++NumDataElement; } - NL_TEST_ASSERT(apSuite, NumDataElement == 1); + EXPECT_EQ(NumDataElement, 1u); } -/** - * Test Suite. It lists all the test functions. - */ - -// clang-format off -const nlTest sTests[] = - { - NL_TEST_DEF("ClusterPathIBTest", ClusterPathIBTest), - NL_TEST_DEF("DataVersionFilterIBTest", DataVersionFilterIBTest), - NL_TEST_DEF("DataVersionFilterIBsTest", DataVersionFilterIBsTest), - NL_TEST_DEF("EventFilterTest", EventFilterTest), - NL_TEST_DEF("EventFiltersTest", EventFiltersTest), - NL_TEST_DEF("AttributePathTest", AttributePathTest), - NL_TEST_DEF("AttributePathListTest", AttributePathListTest), - NL_TEST_DEF("AttributeStatusIBTest", AttributeStatusIBTest), - NL_TEST_DEF("AttributeStatusesTest", AttributeStatusesTest), - NL_TEST_DEF("AttributeDataIBTest", AttributeDataIBTest), - NL_TEST_DEF("AttributeDataIBsTest", AttributeDataIBsTest), - NL_TEST_DEF("AttributeReportIBTest", AttributeReportIBTest), - NL_TEST_DEF("AttributeReportIBsTest", AttributeReportIBsTest), - NL_TEST_DEF("EmptyAttributeReportIBsTest", EmptyAttributeReportIBsTest), - NL_TEST_DEF("EventPathTest", EventPathTest), - NL_TEST_DEF("EventPathsTest", EventPathsTest), - NL_TEST_DEF("EventDataIBTest", EventDataIBTest), - NL_TEST_DEF("EventReportIBTest", EventReportIBTest), - NL_TEST_DEF("EventReportsTest", EventReportsTest), - NL_TEST_DEF("EmptyEventReportsTest", EmptyEventReportsTest), - NL_TEST_DEF("StatusIBTest", StatusIBTest), - NL_TEST_DEF("EventStatusIBTest", EventStatusIBTest), - NL_TEST_DEF("CommandPathIBTest", CommandPathIBTest), - NL_TEST_DEF("CommandDataIBTest", CommandDataIBTest), - NL_TEST_DEF("CommandStatusIBTest", CommandStatusIBTest), - NL_TEST_DEF("InvokeResponseIBWithCommandDataIBTest", InvokeResponseIBWithCommandDataIBTest), - NL_TEST_DEF("InvokeResponseIBWithCommandStatusIBTest", InvokeResponseIBWithCommandStatusIBTest), - NL_TEST_DEF("InvokeResponseIBWithMalformDataTest", InvokeResponseIBWithMalformDataTest), - NL_TEST_DEF("InvokeRequestsTest", InvokeRequestsTest), - NL_TEST_DEF("InvokeResponsesTest", InvokeResponsesTest), - NL_TEST_DEF("InvokeInvokeRequestMessageTest", InvokeInvokeRequestMessageTest), - NL_TEST_DEF("InvokeRequestMessageEndOfMessageReservationTest", InvokeRequestMessageEndOfMessageReservationTest), - NL_TEST_DEF("InvokeRequestsEndOfRequestReservationTest", InvokeRequestsEndOfRequestReservationTest), - NL_TEST_DEF("InvokeInvokeResponseMessageTest", InvokeInvokeResponseMessageTest), - NL_TEST_DEF("InvokeResponseMessageEndOfMessageReservationTest", InvokeResponseMessageEndOfMessageReservationTest), - NL_TEST_DEF("InvokeResponseMessageReservationForEndandMoreChunkTest", InvokeResponseMessageReservationForEndandMoreChunkTest), - NL_TEST_DEF("InvokeResponsesEndOfResponseReservationTest", InvokeResponsesEndOfResponseReservationTest), - NL_TEST_DEF("ReportDataMessageTest", ReportDataMessageTest), - NL_TEST_DEF("ReadRequestMessageTest", ReadRequestMessageTest), - NL_TEST_DEF("WriteRequestMessageTest", WriteRequestMessageTest), - NL_TEST_DEF("WriteResponseMessageTest", WriteResponseMessageTest), - NL_TEST_DEF("SubscribeRequestMessageTest", SubscribeRequestMessageTest), - NL_TEST_DEF("SubscribeResponseMessageTest", SubscribeResponseMessageTest), - NL_TEST_DEF("TimedRequestMessageTest", TimedRequestMessageTest), - NL_TEST_DEF("CheckPointRollbackTest", CheckPointRollbackTest), - NL_TEST_SENTINEL() - }; -// clang-format on } // namespace - -/** - * Set up the test suite. - */ -static int TestSetup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -static int TestTeardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -int TestMessageDef() -{ - // clang-format off - nlTestSuite theSuite = - { - "MessageDef", - &sTests[0], - TestSetup, - TestTeardown, - }; - // clang-format on - - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestMessageDef) diff --git a/src/app/tests/TestNullable.cpp b/src/app/tests/TestNullable.cpp index 660037339d44e1..a08f59c6dc43a9 100644 --- a/src/app/tests/TestNullable.cpp +++ b/src/app/tests/TestNullable.cpp @@ -21,10 +21,10 @@ #include #include +#include + #include #include -#include -#include using namespace chip; using namespace chip::app::DataModel; @@ -79,7 +79,7 @@ int CtorDtorCounter::destroyed = 0; } // namespace -static void TestBasic(nlTestSuite * inSuite, void * inContext) +TEST(TestNullable, TestBasic) { // Set up our test CtorDtorCounter objects, which will mess with counts, before we reset the // counts. @@ -89,109 +89,109 @@ static void TestBasic(nlTestSuite * inSuite, void * inContext) { auto testNullable = MakeNullable(100); - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 1 && CtorDtorCounter::destroyed == 0); - NL_TEST_ASSERT(inSuite, !testNullable.IsNull() && testNullable.Value().m == 100); - NL_TEST_ASSERT(inSuite, testNullable == c100); - NL_TEST_ASSERT(inSuite, testNullable != c101); - NL_TEST_ASSERT(inSuite, testNullable != c102); + EXPECT_TRUE(CtorDtorCounter::created == 1 && CtorDtorCounter::destroyed == 0); + EXPECT_TRUE(!testNullable.IsNull() && testNullable.Value().m == 100); + EXPECT_EQ(testNullable, c100); + EXPECT_NE(testNullable, c101); + EXPECT_NE(testNullable, c102); testNullable.SetNull(); - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 1 && CtorDtorCounter::destroyed == 1); - NL_TEST_ASSERT(inSuite, !!testNullable.IsNull()); - NL_TEST_ASSERT(inSuite, testNullable != c100); - NL_TEST_ASSERT(inSuite, testNullable != c101); - NL_TEST_ASSERT(inSuite, testNullable != c102); + EXPECT_TRUE(CtorDtorCounter::created == 1 && CtorDtorCounter::destroyed == 1); + EXPECT_TRUE(testNullable.IsNull()); + EXPECT_NE(testNullable, c100); + EXPECT_NE(testNullable, c101); + EXPECT_NE(testNullable, c102); testNullable.SetNonNull(CtorDtorCounter(101)); - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 3 && CtorDtorCounter::destroyed == 2); - NL_TEST_ASSERT(inSuite, !testNullable.IsNull() && testNullable.Value().m == 101); - NL_TEST_ASSERT(inSuite, testNullable != c100); - NL_TEST_ASSERT(inSuite, testNullable == c101); - NL_TEST_ASSERT(inSuite, testNullable != c102); + EXPECT_TRUE(CtorDtorCounter::created == 3 && CtorDtorCounter::destroyed == 2); + EXPECT_TRUE(!testNullable.IsNull() && testNullable.Value().m == 101); + EXPECT_NE(testNullable, c100); + EXPECT_EQ(testNullable, c101); + EXPECT_NE(testNullable, c102); testNullable.SetNonNull(102); - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 4 && CtorDtorCounter::destroyed == 3); - NL_TEST_ASSERT(inSuite, !testNullable.IsNull() && testNullable.Value().m == 102); - NL_TEST_ASSERT(inSuite, testNullable != c100); - NL_TEST_ASSERT(inSuite, testNullable != c101); - NL_TEST_ASSERT(inSuite, testNullable == c102); + EXPECT_TRUE(CtorDtorCounter::created == 4 && CtorDtorCounter::destroyed == 3); + EXPECT_TRUE(!testNullable.IsNull() && testNullable.Value().m == 102); + EXPECT_NE(testNullable, c100); + EXPECT_NE(testNullable, c101); + EXPECT_EQ(testNullable, c102); } // Our test CtorDtorCounter objects are still in scope here. - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 4 && CtorDtorCounter::destroyed == 4); + EXPECT_TRUE(CtorDtorCounter::created == 4 && CtorDtorCounter::destroyed == 4); } -static void TestMake(nlTestSuite * inSuite, void * inContext) +TEST(TestNullable, TestMake) { CtorDtorCounter::ResetCounter(); { auto testNullable = MakeNullable(200); - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 1 && CtorDtorCounter::destroyed == 0); - NL_TEST_ASSERT(inSuite, !testNullable.IsNull() && testNullable.Value().m == 200); + EXPECT_TRUE(CtorDtorCounter::created == 1 && CtorDtorCounter::destroyed == 0); + EXPECT_TRUE(!testNullable.IsNull() && testNullable.Value().m == 200); } - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 1 && CtorDtorCounter::destroyed == 1); + EXPECT_TRUE(CtorDtorCounter::created == 1 && CtorDtorCounter::destroyed == 1); } -static void TestCopy(nlTestSuite * inSuite, void * inContext) +TEST(TestNullable, TestCopy) { CtorDtorCounter::ResetCounter(); { auto testSrc = MakeNullable(300); - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 1 && CtorDtorCounter::destroyed == 0); - NL_TEST_ASSERT(inSuite, !testSrc.IsNull() && testSrc.Value().m == 300); + EXPECT_TRUE(CtorDtorCounter::created == 1 && CtorDtorCounter::destroyed == 0); + EXPECT_TRUE(!testSrc.IsNull() && testSrc.Value().m == 300); { Nullable testDst(testSrc); - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 0); - NL_TEST_ASSERT(inSuite, !testDst.IsNull() && testDst.Value().m == 300); + EXPECT_TRUE(CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 0); + EXPECT_TRUE(!testDst.IsNull() && testDst.Value().m == 300); } - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 1); + EXPECT_TRUE(CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 1); { Nullable testDst; - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 1); - NL_TEST_ASSERT(inSuite, !!testDst.IsNull()); + EXPECT_TRUE(CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 1); + EXPECT_TRUE(testDst.IsNull()); testDst = testSrc; - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 3 && CtorDtorCounter::destroyed == 1); - NL_TEST_ASSERT(inSuite, !testDst.IsNull() && testDst.Value().m == 300); + EXPECT_TRUE(CtorDtorCounter::created == 3 && CtorDtorCounter::destroyed == 1); + EXPECT_TRUE(!testDst.IsNull() && testDst.Value().m == 300); } - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 3 && CtorDtorCounter::destroyed == 2); + EXPECT_TRUE(CtorDtorCounter::created == 3 && CtorDtorCounter::destroyed == 2); } - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 3 && CtorDtorCounter::destroyed == 3); + EXPECT_TRUE(CtorDtorCounter::created == 3 && CtorDtorCounter::destroyed == 3); } -static void TestMove(nlTestSuite * inSuite, void * inContext) +TEST(TestNullable, TestMove) { CtorDtorCounter::ResetCounter(); { auto testSrc = MakeNullable(400); // construct Nullable testDst(std::move(testSrc)); // move construct - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 0); - NL_TEST_ASSERT(inSuite, !testDst.IsNull() && testDst.Value().m == 400); + EXPECT_TRUE(CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 0); + EXPECT_TRUE(!testDst.IsNull() && testDst.Value().m == 400); // destroy both testsSrc and testDst } - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 2); + EXPECT_TRUE(CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 2); CtorDtorCounter::ResetCounter(); { Nullable testDst; // no object construction - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 0 && CtorDtorCounter::destroyed == 0); - NL_TEST_ASSERT(inSuite, !!testDst.IsNull()); + EXPECT_TRUE(CtorDtorCounter::created == 0 && CtorDtorCounter::destroyed == 0); + EXPECT_TRUE(testDst.IsNull()); auto testSrc = MakeNullable(401); // construct object testDst = std::move(testSrc); // construct a copy - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 0); - NL_TEST_ASSERT(inSuite, !testDst.IsNull() && testDst.Value().m == 401); + EXPECT_TRUE(CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 0); + EXPECT_TRUE(!testDst.IsNull() && testDst.Value().m == 401); } - NL_TEST_ASSERT(inSuite, CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 2); + EXPECT_TRUE(CtorDtorCounter::created == 2 && CtorDtorCounter::destroyed == 2); } -static void TestUpdate(nlTestSuite * inSuite, void * inContext) +TEST(TestNullable, TestUpdate) { using SmallArray = std::array; // Arrays @@ -199,19 +199,19 @@ static void TestUpdate(nlTestSuite * inSuite, void * inContext) auto nullable1 = MakeNullable({ 1, 2, 3 }); auto nullable2 = MakeNullable({ 1, 2, 3 }); - NL_TEST_ASSERT(inSuite, !nullable1.IsNull()); - NL_TEST_ASSERT(inSuite, !nullable2.IsNull()); - NL_TEST_ASSERT(inSuite, nullable1 == nullable2); + EXPECT_FALSE(nullable1.IsNull()); + EXPECT_FALSE(nullable2.IsNull()); + EXPECT_EQ(nullable1, nullable2); // No-op on change to same. - NL_TEST_ASSERT(inSuite, nullable1.Update(nullable2) == false); - NL_TEST_ASSERT(inSuite, nullable1 == nullable2); + EXPECT_FALSE(nullable1.Update(nullable2)); + EXPECT_EQ(nullable1, nullable2); nullable1.Value()[0] = 100; - NL_TEST_ASSERT(inSuite, nullable1 != nullable2); - NL_TEST_ASSERT(inSuite, nullable2.Update(nullable1) == true); - NL_TEST_ASSERT(inSuite, nullable1 == nullable2); + EXPECT_NE(nullable1, nullable2); + EXPECT_TRUE(nullable2.Update(nullable1)); + EXPECT_EQ(nullable1, nullable2); } // Structs @@ -227,83 +227,52 @@ static void TestUpdate(nlTestSuite * inSuite, void * inContext) auto nullable1 = MakeNullable({ 1, 2 }); auto nullable2 = MakeNullable({ 1, 2 }); - NL_TEST_ASSERT(inSuite, !nullable1.IsNull()); - NL_TEST_ASSERT(inSuite, !nullable2.IsNull()); - NL_TEST_ASSERT(inSuite, nullable1 == nullable2); + EXPECT_FALSE(nullable1.IsNull()); + EXPECT_FALSE(nullable2.IsNull()); + EXPECT_EQ(nullable1, nullable2); // No-op on change to same. - NL_TEST_ASSERT(inSuite, nullable1.Update(nullable2) == false); - NL_TEST_ASSERT(inSuite, nullable1 == nullable2); + EXPECT_FALSE(nullable1.Update(nullable2)); + EXPECT_EQ(nullable1, nullable2); nullable1.Value().a = 100; - NL_TEST_ASSERT(inSuite, nullable1 != nullable2); - NL_TEST_ASSERT(inSuite, nullable2.Update(nullable1) == true); - NL_TEST_ASSERT(inSuite, nullable1 == nullable2); + EXPECT_NE(nullable1, nullable2); + EXPECT_TRUE(nullable2.Update(nullable1)); + EXPECT_EQ(nullable1, nullable2); } // Scalar cases { auto nullable1 = MakeNullable(static_cast(1)); - NL_TEST_ASSERT(inSuite, !nullable1.IsNull()); + EXPECT_FALSE(nullable1.IsNull()); // Non-null to non-null same value - NL_TEST_ASSERT(inSuite, nullable1.Update(nullable1) == false); - NL_TEST_ASSERT(inSuite, !nullable1.IsNull()); + EXPECT_FALSE(nullable1.Update(nullable1)); + EXPECT_FALSE(nullable1.IsNull()); // Non-null to null - NL_TEST_ASSERT(inSuite, nullable1.Update(NullNullable) == true); - NL_TEST_ASSERT(inSuite, nullable1.IsNull()); + EXPECT_TRUE(nullable1.Update(NullNullable)); + EXPECT_TRUE(nullable1.IsNull()); // Null to null - NL_TEST_ASSERT(inSuite, nullable1.Update(NullNullable) == false); - NL_TEST_ASSERT(inSuite, nullable1.IsNull()); + EXPECT_FALSE(nullable1.Update(NullNullable)); + EXPECT_TRUE(nullable1.IsNull()); // Null to non-null - NL_TEST_ASSERT(inSuite, nullable1.Update(MakeNullable(static_cast(1))) == true); - NL_TEST_ASSERT(inSuite, !nullable1.IsNull()); - NL_TEST_ASSERT(inSuite, nullable1.Value() == 1); + EXPECT_TRUE(nullable1.Update(MakeNullable(static_cast(1)))); + EXPECT_FALSE(nullable1.IsNull()); + EXPECT_EQ(nullable1.Value(), 1); // Non-null to non-null different value - NL_TEST_ASSERT(inSuite, nullable1.Update(MakeNullable(static_cast(2))) == true); - NL_TEST_ASSERT(inSuite, !nullable1.IsNull()); - NL_TEST_ASSERT(inSuite, nullable1.Value() == 2); + EXPECT_TRUE(nullable1.Update(MakeNullable(static_cast(2)))); + EXPECT_FALSE(nullable1.IsNull()); + EXPECT_EQ(nullable1.Value(), 2); // Non-null to extent of range --> changes to "invalid" value in range. - NL_TEST_ASSERT(inSuite, nullable1.Update(MakeNullable(static_cast(255))) == true); - NL_TEST_ASSERT(inSuite, !nullable1.IsNull()); - NL_TEST_ASSERT(inSuite, nullable1.Value() == 255); + EXPECT_TRUE(nullable1.Update(MakeNullable(static_cast(255)))); + EXPECT_FALSE(nullable1.IsNull()); + EXPECT_EQ(nullable1.Value(), 255); } } - -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("NullableBasic", TestBasic), - NL_TEST_DEF("NullableMake", TestMake), - NL_TEST_DEF("NullableCopy", TestCopy), - NL_TEST_DEF("NullableMove", TestMove), - NL_TEST_DEF("Nullable Update operation", TestUpdate), - NL_TEST_SENTINEL() -}; -// clang-format on - -int TestNullable() -{ - // clang-format off - nlTestSuite theSuite = - { - "Test for Nullable abstraction", - &sTests[0], - nullptr, - nullptr - }; - // clang-format on - - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestNullable) diff --git a/src/app/tests/TestStatusIB.cpp b/src/app/tests/TestStatusIB.cpp index 2e5f78f7da64f7..2283dd04ff049a 100644 --- a/src/app/tests/TestStatusIB.cpp +++ b/src/app/tests/TestStatusIB.cpp @@ -15,84 +15,94 @@ * limitations under the License. */ +#include + #include #include #include #include #include #include -#include #include -#include - namespace { using namespace chip; using namespace chip::app; using namespace chip::Protocols::InteractionModel; +class TestStatusIB : public ::testing::Test +{ +public: + static void SetUpTestSuite() + { + ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); + StatusIB::RegisterErrorFormatter(); + } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + // Macro so failures will blame the right line. #define VERIFY_ROUNDTRIP(err, status) \ do \ { \ StatusIB newStatus; \ newStatus.InitFromChipError(err); \ - NL_TEST_ASSERT(aSuite, newStatus.mStatus == status.mStatus); \ - NL_TEST_ASSERT(aSuite, newStatus.mClusterStatus == status.mClusterStatus); \ + EXPECT_EQ(newStatus.mStatus, status.mStatus); \ + EXPECT_EQ(newStatus.mClusterStatus, status.mClusterStatus); \ } while (0); -void TestStatusIBToFromChipError(nlTestSuite * aSuite, void * aContext) +TEST_F(TestStatusIB, TestStatusIBToFromChipError) { StatusIB status; status.mStatus = Status::Success; CHIP_ERROR err = status.ToChipError(); - NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); VERIFY_ROUNDTRIP(err, status); status.mStatus = Status::Failure; err = status.ToChipError(); - NL_TEST_ASSERT(aSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); VERIFY_ROUNDTRIP(err, status); status.mStatus = Status::InvalidAction; err = status.ToChipError(); - NL_TEST_ASSERT(aSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); VERIFY_ROUNDTRIP(err, status); status.mClusterStatus = MakeOptional(static_cast(5)); status.mStatus = Status::Success; err = status.ToChipError(); - NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); status.mStatus = Status::Failure; err = status.ToChipError(); - NL_TEST_ASSERT(aSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); VERIFY_ROUNDTRIP(err, status); status.mStatus = Status::InvalidAction; err = status.ToChipError(); - NL_TEST_ASSERT(aSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); { StatusIB newStatus; newStatus.InitFromChipError(err); - NL_TEST_ASSERT(aSuite, newStatus.mStatus == Status::Failure); - NL_TEST_ASSERT(aSuite, newStatus.mClusterStatus == status.mClusterStatus); + EXPECT_EQ(newStatus.mStatus, Status::Failure); + EXPECT_EQ(newStatus.mClusterStatus, status.mClusterStatus); } err = CHIP_ERROR_NO_MEMORY; { StatusIB newStatus; newStatus.InitFromChipError(err); - NL_TEST_ASSERT(aSuite, newStatus.mStatus == Status::Failure); - NL_TEST_ASSERT(aSuite, !newStatus.mClusterStatus.HasValue()); + EXPECT_EQ(newStatus.mStatus, Status::Failure); + EXPECT_FALSE(newStatus.mClusterStatus.HasValue()); } } #if !CHIP_CONFIG_SHORT_ERROR_STR -void TestStatusIBErrorToString(nlTestSuite * aSuite, void * aContext) +TEST_F(TestStatusIB, TestStatusIBErrorToString) { StatusIB status; status.mStatus = Status::InvalidAction; @@ -100,108 +110,55 @@ void TestStatusIBErrorToString(nlTestSuite * aSuite, void * aContext) const char * str = ErrorStr(err); #if CHIP_CONFIG_IM_STATUS_CODE_VERBOSE_FORMAT - NL_TEST_ASSERT(aSuite, strcmp(str, "IM Error 0x00000580: General error: 0x80 (INVALID_ACTION)") == 0); + EXPECT_STREQ(str, "IM Error 0x00000580: General error: 0x80 (INVALID_ACTION)"); #else // CHIP_CONFIG_IM_STATUS_CODE_VERBOSE_FORMAT - NL_TEST_ASSERT(aSuite, strcmp(str, "IM Error 0x00000580: General error: 0x80") == 0); + EXPECT_STREQ(str, "IM Error 0x00000580: General error: 0x80"); #endif // CHIP_CONFIG_IM_STATUS_CODE_VERBOSE_FORMAT status.mStatus = Status::Failure; status.mClusterStatus = MakeOptional(static_cast(5)); err = status.ToChipError(); str = ErrorStr(err); - NL_TEST_ASSERT(aSuite, strcmp(str, "IM Error 0x00000605: Cluster-specific error: 0x05") == 0); + EXPECT_STREQ(str, "IM Error 0x00000605: Cluster-specific error: 0x05"); } #endif // !CHIP_CONFIG_SHORT_ERROR_STR -void TestStatusIBEqualityOperator(nlTestSuite * aSuite, void * /*aContext*/) +TEST_F(TestStatusIB, TestStatusIBEqualityOperator) { // Equality against self is true. StatusIB one; - NL_TEST_ASSERT(aSuite, one == one); + EXPECT_EQ(one, one); // Default constructors are equal. - NL_TEST_ASSERT(aSuite, one == StatusIB()); + EXPECT_EQ(one, StatusIB()); // Different imStatus is not equal. StatusIB with_imstatus(Status::Failure); - NL_TEST_ASSERT(aSuite, one != with_imstatus); + EXPECT_NE(one, with_imstatus); // Same imStatus are equal. - NL_TEST_ASSERT(aSuite, with_imstatus == StatusIB(Status::Failure)); + EXPECT_EQ(with_imstatus, StatusIB(Status::Failure)); // Same imStatus but different clusterStatus are not equal. StatusIB with_cluster_status(Status::Failure, /*clusterStatus=*/2); - NL_TEST_ASSERT(aSuite, with_imstatus != with_cluster_status); + EXPECT_NE(with_imstatus, with_cluster_status); // Different imStatus but same clusterStatus are not equal. - NL_TEST_ASSERT(aSuite, with_cluster_status != StatusIB(Status::Success, /*clusterStatus=*/2)); + EXPECT_NE(with_cluster_status, StatusIB(Status::Success, /*clusterStatus=*/2)); // Same imStatus and clusterStatus are equal. - NL_TEST_ASSERT(aSuite, with_cluster_status == StatusIB(Status::Failure, /*clusterStatus=*/2)); + EXPECT_EQ(with_cluster_status, StatusIB(Status::Failure, /*clusterStatus=*/2)); // From same CHIP_ERROR are equal. StatusIB invalid_argument(CHIP_ERROR_INVALID_ARGUMENT); - NL_TEST_ASSERT(aSuite, invalid_argument == StatusIB(CHIP_ERROR_INVALID_ARGUMENT)); + EXPECT_EQ(invalid_argument, StatusIB(CHIP_ERROR_INVALID_ARGUMENT)); // Different CHIP_ERROR are equal if they are not from kIMClusterStatus or // kIMGlobalStatus. - NL_TEST_ASSERT(aSuite, invalid_argument == StatusIB(CHIP_ERROR_INCORRECT_STATE)); + EXPECT_EQ(invalid_argument, StatusIB(CHIP_ERROR_INCORRECT_STATE)); // Error never equals NO_ERROR - NL_TEST_ASSERT(aSuite, invalid_argument != StatusIB(CHIP_NO_ERROR)); + EXPECT_NE(invalid_argument, StatusIB(CHIP_NO_ERROR)); } -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("StatusIBToFromChipError", TestStatusIBToFromChipError), -#if !CHIP_CONFIG_SHORT_ERROR_STR - NL_TEST_DEF("StatusIBErrorToString", TestStatusIBErrorToString), -#endif // !CHIP_CONFIG_SHORT_ERROR_STR - NL_TEST_DEF("StatusIBEqualityOperator", TestStatusIBEqualityOperator), - NL_TEST_SENTINEL() -}; -// clang-format on } // namespace - -/** - * Set up the test suite. - */ -static int TestSetup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - // Hand-register the error formatter. Normally it's registered by - // InteractionModelEngine::Init, but we don't want to mess with that here. - StatusIB::RegisterErrorFormatter(); - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -static int TestTeardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -int TestStatusIB() -{ - // clang-format off - nlTestSuite theSuite = - { - "StatusIB", - &sTests[0], - TestSetup, - TestTeardown, - }; - // clang-format on - - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestStatusIB) diff --git a/src/app/tests/TestStatusResponseMessage.cpp b/src/app/tests/TestStatusResponseMessage.cpp index 565ed85dfe8af0..06045f7f14898e 100644 --- a/src/app/tests/TestStatusResponseMessage.cpp +++ b/src/app/tests/TestStatusResponseMessage.cpp @@ -22,6 +22,8 @@ * */ +#include + #include #include #include @@ -29,27 +31,32 @@ #include #include -#include - namespace { using namespace chip::app; constexpr chip::Protocols::InteractionModel::Status statusValue = chip::Protocols::InteractionModel::Status::Success; constexpr chip::Protocols::InteractionModel::Status invalidStatusValue = chip::Protocols::InteractionModel::Status::Failure; -void BuildStatusResponseMessage(nlTestSuite * apSuite, chip::TLV::TLVWriter & aWriter) +class TestStatusResponseMessage : public ::testing::Test +{ +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +void BuildStatusResponseMessage(chip::TLV::TLVWriter & aWriter) { CHIP_ERROR err = CHIP_NO_ERROR; StatusResponseMessage::Builder statusResponse; err = statusResponse.Init(&aWriter); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); statusResponse.Status(statusValue); - NL_TEST_ASSERT(apSuite, statusResponse.GetError() == CHIP_NO_ERROR); + EXPECT_EQ(statusResponse.GetError(), CHIP_NO_ERROR); } -void ParseStatusResponseMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aReader, bool aTestPositiveCase) +void ParseStatusResponseMessage(chip::TLV::TLVReader & aReader, bool aTestPositiveCase) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -57,7 +64,7 @@ void ParseStatusResponseMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aR chip::Protocols::InteractionModel::Status status; err = statusResponse.Init(aReader); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #if CHIP_CONFIG_IM_PRETTY_PRINT statusResponse.PrettyPrint(); #endif @@ -65,87 +72,42 @@ void ParseStatusResponseMessage(nlTestSuite * apSuite, chip::TLV::TLVReader & aR err = statusResponse.GetStatus(status); if (aTestPositiveCase) { - NL_TEST_ASSERT(apSuite, status == statusValue && err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(status, statusValue); } else { - NL_TEST_ASSERT(apSuite, status != invalidStatusValue && err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_NE(status, invalidStatusValue); } } -void StatusResponseMessagePositiveTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestStatusResponseMessage, TestStatusResponseMessagePositive) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); - BuildStatusResponseMessage(apSuite, writer); + BuildStatusResponseMessage(writer); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(std::move(buf)); - ParseStatusResponseMessage(apSuite, reader, true /*aTestPositiveCase*/); + ParseStatusResponseMessage(reader, true /*aTestPositiveCase*/); } -void StatusResponseMessageNegativeTest(nlTestSuite * apSuite, void * apContext) +TEST_F(TestStatusResponseMessage, TestStatusResponseMessageNegative) { CHIP_ERROR err = CHIP_NO_ERROR; chip::System::PacketBufferTLVWriter writer; chip::System::PacketBufferTLVReader reader; writer.Init(chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSize)); - BuildStatusResponseMessage(apSuite, writer); + BuildStatusResponseMessage(writer); chip::System::PacketBufferHandle buf; err = writer.Finalize(&buf); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); reader.Init(std::move(buf)); - ParseStatusResponseMessage(apSuite, reader, false /*aTestPositiveCase*/); + ParseStatusResponseMessage(reader, false /*aTestPositiveCase*/); } -// clang-format off -const nlTest sTests[] = - { - NL_TEST_DEF("StatusResponseMessagePositiveTest", StatusResponseMessagePositiveTest), - NL_TEST_DEF("StatusResponseMessageNegativeTest", StatusResponseMessageNegativeTest), - NL_TEST_SENTINEL() - }; -// clang-format on } // namespace - -/** - * Set up the test suite. - */ -static int TestSetup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -static int TestTeardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -int TestStatusResponseMessage() -{ - // clang-format off - nlTestSuite theSuite = - { - "StatusResponseMessage", - &sTests[0], - TestSetup, - TestTeardown, - }; - // clang-format on - - nlTestRunner(&theSuite, nullptr); - - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestStatusResponseMessage) diff --git a/src/app/tests/TestTimedHandler.cpp b/src/app/tests/TestTimedHandler.cpp index 29e8aac71d35a7..7a59b025665218 100644 --- a/src/app/tests/TestTimedHandler.cpp +++ b/src/app/tests/TestTimedHandler.cpp @@ -16,21 +16,19 @@ * limitations under the License. */ +#include + #include #include #include #include #include #include -#include -#include #include #include #include #include -#include - using TestContext = chip::Test::AppContext; namespace chip { @@ -39,25 +37,50 @@ 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); + pTestContext = new TestContext; - static void TestInvokeNeverComes(nlTestSuite * aSuite, void * aContext); + pTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + pTestContext->TearDownTestSuite(); + if (pTestContext != nullptr) + { + delete pTestContext; + } + } -private: - static void TestFollowingMessageFastEnough(nlTestSuite * aSuite, void * aContext, MsgType aMsgType); - static void TestFollowingMessageTooSlow(nlTestSuite * aSuite, void * aContext, MsgType aMsgType); + void SetUp() override + { + if (pTestContext != nullptr) + { + pTestContext->SetUp(); + } + } + void TearDown() override + { + if (pTestContext != nullptr) + { + pTestContext->TearDown(); + } + } + static TestContext * pTestContext; - 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::pTestContext = nullptr; class TestExchangeDelegate : public Messaging::ExchangeDelegate { @@ -93,97 +116,97 @@ 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()); + EXPECT_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(err, 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(err, CHIP_NO_ERROR); } -void TestTimedHandler::TestFollowingMessageFastEnough(nlTestSuite * aSuite, void * aContext, MsgType aMsgType) +void TestTimedHandler::TestFollowingMessageFastEnough(MsgType aMsgType) { - TestContext & ctx = *static_cast(aContext); + // 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 = pTestContext->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(err, 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); + pTestContext->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()); + 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(err, 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); + pTestContext->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); + // 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 = pTestContext->NewExchangeToAlice(&delegate); + EXPECT_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(err, 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); + pTestContext->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 +214,51 @@ 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(err, 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); + pTestContext->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); + // 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 = pTestContext->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(err, 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); + pTestContext->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 +266,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], - TestContext::nlTestSetUpTestSuite, - TestContext::nlTestTearDownTestSuite, - TestContext::nlTestSetUp, - TestContext::nlTestTearDown, -}; -// clang-format on - -} // namespace - -int TestTimedHandler() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestTimedHandler) diff --git a/src/messaging/ReliableMessageContext.h b/src/messaging/ReliableMessageContext.h index 7e8f725cbed15b..ccb6bdbec756d0 100644 --- a/src/messaging/ReliableMessageContext.h +++ b/src/messaging/ReliableMessageContext.h @@ -36,6 +36,9 @@ #include namespace chip { +namespace Test { +class ReliableMessageContextTestAccess; +} namespace app { class TestCommandInteraction; class TestReadInteraction; @@ -213,6 +216,7 @@ class ReliableMessageContext friend class ::chip::app::TestCommandInteraction; friend class ::chip::app::TestReadInteraction; friend class ::chip::app::TestWriteInteraction; + friend class ::chip::Test::ReliableMessageContextTestAccess; System::Clock::Timestamp mNextAckTime; // Next time for triggering Solo Ack uint32_t mPendingPeerAckMessageCounter; diff --git a/src/messaging/tests/ReliableMessageContextTestAccess.h b/src/messaging/tests/ReliableMessageContextTestAccess.h new file mode 100644 index 00000000000000..00bdc199e36b19 --- /dev/null +++ b/src/messaging/tests/ReliableMessageContextTestAccess.h @@ -0,0 +1,48 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +namespace chip { +namespace Test { + +/** + * @brief Class acts as an accessor to private methods of the ReliableMessageContext class without needing to give friend access to + * each individual test. + * This is not a Global API and should only be used for (Unit) Testing. + */ +class ReliableMessageContextTestAccess +{ + +public: + ReliableMessageContextTestAccess(Messaging::ReliableMessageContext * aReliableMessageContext) : + pReliableMessageContext(aReliableMessageContext) + {} + + void SetPendingPeerAckMessageCounter(uint32_t aPeerAckMessageCounter) + { + pReliableMessageContext->SetPendingPeerAckMessageCounter(aPeerAckMessageCounter); + } + +private: + Messaging::ReliableMessageContext * pReliableMessageContext = nullptr; +}; + +} // namespace Test +} // namespace chip From 0ef1e4230483446572affb267cb094ee9a6c2a76 Mon Sep 17 00:00:00 2001 From: AYA Date: Thu, 16 May 2024 17:09:04 +0200 Subject: [PATCH 06/22] adding ember-test-compatibility --- src/BUILD.gn | 3 + src/app/tests/BUILD.gn | 96 +++- src/app/tests/CommandSenderTestAccess.h | 5 +- src/app/tests/TestCommandInteraction.cpp | 503 +++++++++++---------- src/app/tests/TestReadInteraction.cpp | 5 +- src/app/tests/TestTimedHandler.cpp | 1 - src/app/tests/ember-test-compatibility.cpp | 115 +++++ src/app/tests/ember-test-compatibility.h | 45 ++ 8 files changed, 520 insertions(+), 253 deletions(-) create mode 100644 src/app/tests/ember-test-compatibility.cpp create mode 100644 src/app/tests/ember-test-compatibility.h diff --git a/src/BUILD.gn b/src/BUILD.gn index b24036c1a3783a..2bb801d72928fd 100644 --- a/src/BUILD.gn +++ b/src/BUILD.gn @@ -96,7 +96,10 @@ if (chip_build_tests) { tests += [ # TODO(#10447): App test has HF on EFR32. "${chip_root}/src/app/tests", + "${chip_root}/src/app/tests:tests_ember", "${chip_root}/src/app/tests:tests_nltest", + "${chip_root}/src/app/tests:tests_nltest_ember", + "${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 9319f39732f2cc..49275ac7ae2c2c 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -121,13 +121,64 @@ source_set("operational-state-test-srcs") { ] } +source_set("ember-apptest-compatibility") { + sources = [ + "ember-test-compatibility.cpp", + "ember-test-compatibility.h", + ] + public_configs = [ "${chip_root}/src/lib/support/pw_log_chip:config" ] + + public_deps = [ + "${chip_root}/src/app/util/mock:mock_ember", + "${chip_root}/src/lib/core", + "${chip_root}/src/lib/support", + ] +} + +chip_test_suite("tests_ember") { + output_name = "libAppTestsEMBER" + + sources = [ + "${chip_root}/src/messaging/tests/ReliableMessageContextTestAccess.h", + "CommandHandlerTestAccess.h", + "CommandSenderTestAccess.h", + ] + test_sources = [ "TestCommandInteraction.cpp" ] + + cflags = [ "-Wconversion" ] + + public_deps = [ + ":binding-test-srcs", + ":ember-apptest-compatibility", + ":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", + ] +} + chip_test_suite("tests") { output_name = "libAppTests" - sources = [ "CommandSenderTestAccess.h" ] + sources = [ + "${chip_root}/src/messaging/tests/ReliableMessageContextTestAccess.h", + "CommandHandlerTestAccess.h", + "CommandSenderTestAccess.h", + ] test_sources = [ + "TestAclAttribute.cpp", "TestBuilderParser.cpp", - "TestCommandInteraction.cpp", + + # "TestCommandInteraction.cpp", "TestMessageDef.cpp", "TestNullable.cpp", "TestStatusIB.cpp", @@ -135,11 +186,40 @@ chip_test_suite("tests") { "TestTimedHandler.cpp", ] - test_sources += [ "TestAclAttribute.cpp" ] cflags = [ "-Wconversion" ] public_deps = [ ":binding-test-srcs", + ":ember-apptest-compatibility", + ":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", + ] +} + +chip_test_suite_using_nltest("tests_nltest_ember") { + output_name = "libAppTestsNLEMBER" + + test_sources = [ + "TestReadInteraction.cpp", + "TestWriteInteraction.cpp", + ] + + cflags = [ "-Wconversion" ] + + public_deps = [ + ":binding-test-srcs", + ":ember-apptest-compatibility", ":operational-state-test-srcs", ":ota-requestor-test-srcs", ":time-sync-data-provider-test-srcs", @@ -183,11 +263,9 @@ chip_test_suite_using_nltest("tests_nltest") { "TestPendingNotificationMap.cpp", "TestPendingResponseTrackerImpl.cpp", "TestPowerSourceCluster.cpp", - "TestReadInteraction.cpp", "TestReportingEngine.cpp", "TestTestEventTriggerDelegate.cpp", "TestTimeSyncDataProvider.cpp", - "TestWriteInteraction.cpp", ] if (!chip_fake_platform) { @@ -231,6 +309,7 @@ chip_test_suite_using_nltest("tests_nltest") { public_deps = [ ":binding-test-srcs", + ":ember-apptest-compatibility", ":operational-state-test-srcs", ":ota-requestor-test-srcs", ":time-sync-data-provider-test-srcs", @@ -270,10 +349,3 @@ chip_test_suite_using_nltest("tests_nltest") { test_sources += [ "TestSimpleSubscriptionResumptionStorage.cpp" ] } } - -group("test_migration") { - deps = [ - ":tests", - ":tests_nltest", - ] -} diff --git a/src/app/tests/CommandSenderTestAccess.h b/src/app/tests/CommandSenderTestAccess.h index b07837ce1447ca..6ff2bd0a7dfe64 100644 --- a/src/app/tests/CommandSenderTestAccess.h +++ b/src/app/tests/CommandSenderTestAccess.h @@ -44,9 +44,10 @@ class CommandSenderTestAccess Messaging::ExchangeHolder GetExchangeCtx() { return pCommandSender->mExchangeCtx; } - CHIP_ERROR OnMessageReceived(const PayloadHeader & aPayloadHeader, System::PacketBufferHandle && aPayload) + CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader, + System::PacketBufferHandle && aPayload) { - return pCommandSender->OnMessageReceived(pCommandSender->mExchangeCtx.Get(), aPayloadHeader, std::move(aPayload)); + return pCommandSender->OnMessageReceived(apExchangeContext, aPayloadHeader, std::move(aPayload)); } CHIP_ERROR Finalize(System::PacketBufferHandle & commandPacket) { return pCommandSender->Finalize(commandPacket); } diff --git a/src/app/tests/TestCommandInteraction.cpp b/src/app/tests/TestCommandInteraction.cpp index 4cd0b26a1d50cc..a998fb75f93ccc 100644 --- a/src/app/tests/TestCommandInteraction.cpp +++ b/src/app/tests/TestCommandInteraction.cpp @@ -50,6 +50,41 @@ #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. + * + * This is a macro so we get useful line numbers on assertion failures + */ +#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) { \ + chip::Test::ReliableMessageContextTestAccess(localExchange) \ + .SetPendingPeerAckMessageCounter(entry->retainedBuf.GetMessageCounter()); \ + return Loop::Break; \ + }); \ + } + using TestContext = chip::Test::AppContext; using namespace chip::Protocols; @@ -68,6 +103,24 @@ void CheckForInvalidAction(chip::Test::MessageCapturer & messageLog) namespace chip { +inline void PretendWeGotReplyFromServers(TestContext * aContext, Messaging::ExchangeContext * aClientExchange) +{ + Messaging::ReliableMessageMgr * localRm = aContext->GetExchangeManager().GetReliableMessageMgr(); + + EXPECT_EQ(localRm->TestGetCountRetransTable(), 2); + printf("AMINE checking TestGetCountRetransTable = %d", localRm->TestGetCountRetransTable()); + + localRm->ClearRetransTable(aClientExchange); + EXPECT_EQ(localRm->TestGetCountRetransTable(), 1); + printf("AMINE checking TestGetCountRetransTable = %d", localRm->TestGetCountRetransTable()); + + localRm->EnumerateRetransTable([aClientExchange](auto * entry) { + chip::Test::ReliableMessageContextTestAccess(aClientExchange) + .SetPendingPeerAckMessageCounter(entry->retainedBuf.GetMessageCounter()); + return Loop::Break; + }); +} + namespace { bool isCommandDispatched = false; size_t commandDispatchedCount = 0; @@ -695,234 +748,6 @@ void TestCommandInteraction::ValidateCommandHandlerEncodeInvokeResponseMessage(b EXPECT_FALSE(commandHandler.mMockCommandResponder.mChunks.IsNull()); } -TEST_F(TestCommandInteraction, TestCommandSenderWithWrongState) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); - EXPECT_EQ(err, CHIP_NO_ERROR); - - err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); - EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); -} - -TEST_F(TestCommandInteraction, TestCommandHandlerWithWrongState) -{ - 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 CommandHandler::InvokeResponseParameters prepareParams(requestCommandPath); - err = commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams); - EXPECT_EQ(err, CHIP_NO_ERROR); - } - EXPECT_TRUE(commandHandler.mMockCommandResponder.mChunks.IsNull()); -} - -TEST_F(TestCommandInteraction, TestCommandSenderWithSendCommand) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); - - System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - - AddInvokeRequestData(&commandSender); - err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); - EXPECT_EQ(err, CHIP_NO_ERROR); - - pTestContext->DrainAndServiceIO(); - - GenerateInvokeResponse(buf, kTestCommandIdWithData); - bool moreChunkedMessages = false; - chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); - err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); - EXPECT_EQ(err, CHIP_NO_ERROR); - EXPECT_FALSE(moreChunkedMessages); -} - -TEST_F(TestCommandInteraction, TestCommandHandlerWithSendEmptyCommand) -{ - 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 CommandHandler::InvokeResponseParameters prepareParams(requestCommandPath); - err = commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams); - EXPECT_EQ(err, CHIP_NO_ERROR); - err = commandHandler.FinishCommand(); - EXPECT_EQ(err, CHIP_NO_ERROR); - } - EXPECT_FALSE(commandHandler.mMockCommandResponder.mChunks.IsNull()); -} - -TEST_F(TestCommandInteraction, TestCommandSenderWithProcessReceivedMsg) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); - - System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - - GenerateInvokeResponse(buf, kTestCommandIdWithData); - bool moreChunkedMessages = false; - chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); - err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); - EXPECT_EQ(err, CHIP_NO_ERROR); - EXPECT_FALSE(moreChunkedMessages); -} - -TEST_F(TestCommandInteraction, TestCommandSenderExtendableApiWithProcessReceivedMsg) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - mockCommandSenderExtendedDelegate.ResetCounter(); - PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, - &pTestContext->GetExchangeManager(), &pendingResponseTracker); - - uint16_t mockCommandRef = 1; - pendingResponseTracker.Add(mockCommandRef); - chip::Test::CommandSenderTestAccess(&commandSender).SetFinishedCommandCount(1); - - System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - - GenerateInvokeResponse(buf, kTestCommandIdWithData); - bool moreChunkedMessages = false; - chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); - err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); - EXPECT_EQ(err, CHIP_NO_ERROR); - EXPECT_FALSE(moreChunkedMessages); - - chip::Test::CommandSenderTestAccess(&commandSender).FlushNoCommandResponse(); - - EXPECT_EQ(mockCommandSenderExtendedDelegate.onResponseCalledTimes, 1); - EXPECT_EQ(mockCommandSenderExtendedDelegate.onFinalCalledTimes, 0); - EXPECT_EQ(mockCommandSenderExtendedDelegate.onNoResponseCalledTimes, 0); - EXPECT_EQ(mockCommandSenderExtendedDelegate.onErrorCalledTimes, 0); -} - -TEST_F(TestCommandInteraction, TestCommandSenderExtendableApiWithProcessReceivedMsgContainingInvalidCommandRef) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - mockCommandSenderExtendedDelegate.ResetCounter(); - PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, - &pTestContext->GetExchangeManager(), &pendingResponseTracker); - - uint16_t mockCommandRef = 1; - pendingResponseTracker.Add(mockCommandRef); - chip::Test::CommandSenderTestAccess(&commandSender).SetFinishedCommandCount(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; - chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); - err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); - EXPECT_EQ(err, CHIP_ERROR_KEY_NOT_FOUND); - EXPECT_FALSE(moreChunkedMessages); - - chip::Test::CommandSenderTestAccess(&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(); - auto requestCommandPath = ConcreteCommandPath(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()); -} - -/** - * 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(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) { \ - chip::Test::ReliableMessageContextTestAccess(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. TEST_F(TestCommandInteraction, TestCommandInvalidMessage1) @@ -965,17 +790,21 @@ TEST_F(TestCommandInteraction, TestCommandInvalidMessage1) chip::Test::MessageCapturer messageLog(*pTestContext); messageLog.mCaptureStandaloneAcks = false; + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + // 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(pTestContext, chip::Test::CommandSenderTestAccess(&commandSender).GetExchangeCtx().Get()); + + // PretendWeGotReplyFromServer(pTestContext, privatecommandSender.GetExchangeCtx().Get()); + PretendWeGotReplyFromServers(pTestContext, privatecommandSender.GetExchangeCtx().Get()); pTestContext->GetLoopback().mSentMessageCount = 0; pTestContext->GetLoopback().mNumMessagesToDrop = 0; pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; pTestContext->GetLoopback().mDroppedMessageCount = 0; - err = chip::Test::CommandSenderTestAccess(&commandSender).OnMessageReceived(payloadHeader, std::move(msgBuf)); + err = privatecommandSender.OnMessageReceived(privatecommandSender.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); EXPECT_EQ(err, CHIP_IM_GLOBAL_STATUS(Busy)); EXPECT_EQ(mockCommandSenderDelegate.mError, CHIP_IM_GLOBAL_STATUS(Busy)); EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); @@ -1039,14 +868,17 @@ TEST_F(TestCommandInteraction, TestCommandInvalidMessage2) // 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(pTestContext, chip::Test::CommandSenderTestAccess(&commandSender).GetExchangeCtx().Get()); + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + + PretendWeGotReplyFromServer(pTestContext, privatecommandSender.GetExchangeCtx().Get()); pTestContext->GetLoopback().mSentMessageCount = 0; pTestContext->GetLoopback().mNumMessagesToDrop = 0; pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; pTestContext->GetLoopback().mDroppedMessageCount = 0; - err = chip::Test::CommandSenderTestAccess(&commandSender).OnMessageReceived(payloadHeader, std::move(msgBuf)); + err = privatecommandSender.OnMessageReceived(privatecommandSender.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); + // err = chip::Test::CommandSenderTestAccess(&commandSender).OnMessageReceived(payloadHeader, std::move(msgBuf)); EXPECT_EQ(err, CHIP_ERROR_INVALID_MESSAGE_TYPE); EXPECT_EQ(mockCommandSenderDelegate.mError, CHIP_ERROR_INVALID_MESSAGE_TYPE); EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); @@ -1109,14 +941,17 @@ TEST_F(TestCommandInteraction, TestCommandInvalidMessage3) // 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(pTestContext, chip::Test::CommandSenderTestAccess(&commandSender).GetExchangeCtx().Get()); + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + PretendWeGotReplyFromServer(pTestContext, privatecommandSender.GetExchangeCtx().Get()); pTestContext->GetLoopback().mSentMessageCount = 0; pTestContext->GetLoopback().mNumMessagesToDrop = 0; pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; pTestContext->GetLoopback().mDroppedMessageCount = 0; - err = chip::Test::CommandSenderTestAccess(&commandSender).OnMessageReceived(payloadHeader, std::move(msgBuf)); + err = privatecommandSender.OnMessageReceived(privatecommandSender.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); + + // err = chip::Test::CommandSenderTestAccess(&commandSender).OnMessageReceived(payloadHeader, std::move(msgBuf)); EXPECT_EQ(err, CHIP_ERROR_END_OF_TLV); EXPECT_EQ(mockCommandSenderDelegate.mError, CHIP_ERROR_END_OF_TLV); EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); @@ -1178,14 +1013,17 @@ TEST_F(TestCommandInteraction, TestCommandInvalidMessage4) // 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(pTestContext, chip::Test::CommandSenderTestAccess(&commandSender).GetExchangeCtx().Get()); + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + PretendWeGotReplyFromServer(pTestContext, privatecommandSender.GetExchangeCtx().Get()); pTestContext->GetLoopback().mSentMessageCount = 0; pTestContext->GetLoopback().mNumMessagesToDrop = 0; pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; pTestContext->GetLoopback().mDroppedMessageCount = 0; - err = chip::Test::CommandSenderTestAccess(&commandSender).OnMessageReceived(payloadHeader, std::move(msgBuf)); + err = privatecommandSender.OnMessageReceived(privatecommandSender.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); + + // err = chip::Test::CommandSenderTestAccess(&commandSender).OnMessageReceived(payloadHeader, std::move(msgBuf)); EXPECT_EQ(err, CHIP_ERROR_END_OF_TLV); EXPECT_EQ(mockCommandSenderDelegate.mError, CHIP_ERROR_END_OF_TLV); EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); @@ -1204,6 +1042,199 @@ TEST_F(TestCommandInteraction, TestCommandInvalidMessage4) pTestContext->CreateSessionBobToAlice(); } +TEST_F(TestCommandInteraction, TestCommandSenderWithWrongState) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); + EXPECT_EQ(err, CHIP_NO_ERROR); + + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); +} + +TEST_F(TestCommandInteraction, TestCommandHandlerWithWrongState) +{ + 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 CommandHandler::InvokeResponseParameters prepareParams(requestCommandPath); + err = commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams); + EXPECT_EQ(err, CHIP_NO_ERROR); + } + EXPECT_TRUE(commandHandler.mMockCommandResponder.mChunks.IsNull()); +} + +TEST_F(TestCommandInteraction, TestCommandSenderWithSendCommand) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); + + System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); + + AddInvokeRequestData(&commandSender); + err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_NO_ERROR); + + pTestContext->DrainAndServiceIO(); + + GenerateInvokeResponse(buf, kTestCommandIdWithData); + bool moreChunkedMessages = false; + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(moreChunkedMessages); +} + +TEST_F(TestCommandInteraction, TestCommandHandlerWithSendEmptyCommand) +{ + 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 CommandHandler::InvokeResponseParameters prepareParams(requestCommandPath); + err = commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams); + EXPECT_EQ(err, CHIP_NO_ERROR); + err = commandHandler.FinishCommand(); + EXPECT_EQ(err, CHIP_NO_ERROR); + } + EXPECT_FALSE(commandHandler.mMockCommandResponder.mChunks.IsNull()); +} + +TEST_F(TestCommandInteraction, TestCommandSenderWithProcessReceivedMsg) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); + + System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); + + GenerateInvokeResponse(buf, kTestCommandIdWithData); + bool moreChunkedMessages = false; + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(moreChunkedMessages); +} + +TEST_F(TestCommandInteraction, TestCommandSenderExtendableApiWithProcessReceivedMsg) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + mockCommandSenderExtendedDelegate.ResetCounter(); + PendingResponseTrackerImpl pendingResponseTracker; + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &pTestContext->GetExchangeManager(), &pendingResponseTracker); + + uint16_t mockCommandRef = 1; + pendingResponseTracker.Add(mockCommandRef); + chip::Test::CommandSenderTestAccess(&commandSender).SetFinishedCommandCount(1); + + System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); + + GenerateInvokeResponse(buf, kTestCommandIdWithData); + bool moreChunkedMessages = false; + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(moreChunkedMessages); + + chip::Test::CommandSenderTestAccess(&commandSender).FlushNoCommandResponse(); + + EXPECT_EQ(mockCommandSenderExtendedDelegate.onResponseCalledTimes, 1); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onFinalCalledTimes, 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onNoResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onErrorCalledTimes, 0); +} + +TEST_F(TestCommandInteraction, TestCommandSenderExtendableApiWithProcessReceivedMsgContainingInvalidCommandRef) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + mockCommandSenderExtendedDelegate.ResetCounter(); + PendingResponseTrackerImpl pendingResponseTracker; + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &pTestContext->GetExchangeManager(), &pendingResponseTracker); + + uint16_t mockCommandRef = 1; + pendingResponseTracker.Add(mockCommandRef); + chip::Test::CommandSenderTestAccess(&commandSender).SetFinishedCommandCount(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; + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); + EXPECT_EQ(err, CHIP_ERROR_KEY_NOT_FOUND); + EXPECT_FALSE(moreChunkedMessages); + + chip::Test::CommandSenderTestAccess(&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(); + auto requestCommandPath = ConcreteCommandPath(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 TEST_F(TestCommandInteraction, TestCommandHandlerInvalidMessageSync) { diff --git a/src/app/tests/TestReadInteraction.cpp b/src/app/tests/TestReadInteraction.cpp index 7e18cca7883c8f..56026d67da9568 100644 --- a/src/app/tests/TestReadInteraction.cpp +++ b/src/app/tests/TestReadInteraction.cpp @@ -22,6 +22,8 @@ * */ +// #include "app/tests/ember-test-compatibility.h" + #include "lib/support/CHIPMem.h" #include #include @@ -1363,8 +1365,7 @@ void TestReadInteraction::TestSetDirtyBetweenChunks(nlTestSuite * apSuite, void public: DirtyingMockDelegate(AttributePathParams (&aReadPaths)[2], int & aNumAttributeResponsesWhenSetDirty, int & aNumArrayItemsWhenSetDirty) : - mReadPaths(aReadPaths), - mNumAttributeResponsesWhenSetDirty(aNumAttributeResponsesWhenSetDirty), + mReadPaths(aReadPaths), mNumAttributeResponsesWhenSetDirty(aNumAttributeResponsesWhenSetDirty), mNumArrayItemsWhenSetDirty(aNumArrayItemsWhenSetDirty) {} diff --git a/src/app/tests/TestTimedHandler.cpp b/src/app/tests/TestTimedHandler.cpp index 7a59b025665218..0bc5011adf1e7a 100644 --- a/src/app/tests/TestTimedHandler.cpp +++ b/src/app/tests/TestTimedHandler.cpp @@ -46,7 +46,6 @@ class TestTimedHandler : public ::testing::Test { pTestContext = new TestContext; - pTestContext->SetUpTestSuite(); } static void TearDownTestSuite() diff --git a/src/app/tests/ember-test-compatibility.cpp b/src/app/tests/ember-test-compatibility.cpp new file mode 100644 index 00000000000000..98fec28e2c719b --- /dev/null +++ b/src/app/tests/ember-test-compatibility.cpp @@ -0,0 +1,115 @@ +#include "lib/support/CHIPMem.h" +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace chip { +namespace app { + +constexpr chip::ClusterId kTestClusterId = 6; +constexpr uint8_t kTestFieldValue1 = 1; +constexpr chip::EndpointId kTestEndpointId = 1; + +// strong defintion in TestWriteInteraction.cpp +__attribute__((weak)) CHIP_ERROR WriteSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, + const ConcreteDataAttributePath & aPath, TLV::TLVReader & aReader, + WriteHandler * aWriteHandler) +{ + + return CHIP_NO_ERROR; +} + +// strong defintion in TestWriteInteraction.cpp +__attribute__((weak)) const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aConcreteClusterPath) +{ + // Note: This test does not make use of the real attribute metadata. + static EmberAfAttributeMetadata stub = { .defaultValue = EmberAfDefaultOrMinMaxAttributeValue(uint32_t(0)) }; + return &stub; +} + +// strong defintion in TestAclAttribute.cpp +__attribute__((weak)) bool ConcreteAttributePathExists(const ConcreteAttributePath & aPath) +{ + return true; +} + +// strong defintion in TestAclAttribute.cpp +__attribute__((weak)) Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath) +{ + return Protocols::InteractionModel::Status::Success; +} + +// strong defintion in TestCommandInteraction.cpp +__attribute__((weak)) Protocols::InteractionModel::Status +ServerClusterCommandExists(const ConcreteCommandPath & aRequestCommandPath) +{ + // Mock cluster catalog, only support commands on one cluster on one endpoint. + using Protocols::InteractionModel::Status; + + return Status::Success; +} + +// strong defintion in TestCommandInteraction.cpp +__attribute__((weak)) void DispatchSingleClusterCommand(const ConcreteCommandPath & aRequestCommandPath, + chip::TLV::TLVReader & aReader, CommandHandler * apCommandObj) +{ + return; +} + +// strong defintion in TestReadInteraction.cpp +__attribute__((weak)) bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) +{ + return false; +} + +// strong defintion in TestReadInteraction.cpp +__attribute__((weak)) bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) +{ + return false; +} + +// strong defintion in TestReadInteraction.cpp +__attribute__((weak)) CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, + const ConcreteReadAttributePath & aPath, + AttributeReportIBs::Builder & aAttributeReports, + AttributeEncodeState * apEncoderState) +{ + if (aPath.mClusterId >= Test::kMockEndpointMin) + { + return Test::ReadSingleMockClusterData(aSubjectDescriptor.fabricIndex, aPath, aAttributeReports, apEncoderState); + } + + if (!(aPath.mClusterId == kTestClusterId && aPath.mEndpointId == kTestEndpointId)) + { + AttributeReportIB::Builder & attributeReport = aAttributeReports.CreateAttributeReport(); + ReturnErrorOnFailure(aAttributeReports.GetError()); + ChipLogDetail(DataManagement, "TEST Cluster %" PRIx32 ", Field %" PRIx32 " is dirty", aPath.mClusterId, aPath.mAttributeId); + + AttributeStatusIB::Builder & attributeStatus = attributeReport.CreateAttributeStatus(); + ReturnErrorOnFailure(attributeReport.GetError()); + AttributePathIB::Builder & attributePath = attributeStatus.CreatePath(); + ReturnErrorOnFailure(attributeStatus.GetError()); + + attributePath.Endpoint(aPath.mEndpointId).Cluster(aPath.mClusterId).Attribute(aPath.mAttributeId).EndOfAttributePathIB(); + ReturnErrorOnFailure(attributePath.GetError()); + StatusIB::Builder & errorStatus = attributeStatus.CreateErrorStatus(); + ReturnErrorOnFailure(attributeStatus.GetError()); + errorStatus.EncodeStatusIB(StatusIB(Protocols::InteractionModel::Status::UnsupportedAttribute)); + ReturnErrorOnFailure(errorStatus.GetError()); + ReturnErrorOnFailure(attributeStatus.EndOfAttributeStatusIB()); + return attributeReport.EndOfAttributeReportIB(); + } + + return AttributeValueEncoder(aAttributeReports, aSubjectDescriptor, aPath, 0 /* dataVersion */).Encode(kTestFieldValue1); +} + +} // namespace app + +} // namespace chip diff --git a/src/app/tests/ember-test-compatibility.h b/src/app/tests/ember-test-compatibility.h new file mode 100644 index 00000000000000..d1c16952269e30 --- /dev/null +++ b/src/app/tests/ember-test-compatibility.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace chip { +namespace app { + +// constexpr uint8_t kTestFieldValue1 = 1; + +// constexpr chip::ClusterId kTestClusterId = 3; +// constexpr chip::EndpointId kTestEndpointId = 1; +// constexpr chip::DataVersion kTestDataVersion1 = 3; +// constexpr chip::DataVersion kTestDataVersion2 = 5; + +// constexpr chip::DataVersion kRejectedDataVersion = 1; + +// constexpr chip::ClusterId kTestDeniedClusterId1 = 1000; + +// constexpr CommandId kTestNonExistCommandId = 0; + +CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, + const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, + AttributeEncodeState * apEncoderState); + +bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion); + +CHIP_ERROR WriteSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteDataAttributePath & aPath, + TLV::TLVReader & aReader, WriteHandler * aWriteHandler); +const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aConcreteClusterPath); + +bool ConcreteAttributePathExists(const ConcreteAttributePath & aPath); +Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath); + +Protocols::InteractionModel::Status ServerClusterCommandExists(const ConcreteCommandPath & aRequestCommandPath); + +void DispatchSingleClusterCommand(const ConcreteCommandPath & aRequestCommandPath, chip::TLV::TLVReader & aReader, + CommandHandler * apCommandObj); + +bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint); +} // namespace app +} // namespace chip From 1b6c148ed04c7ee5e9a27591ea2f0f6100a752e5 Mon Sep 17 00:00:00 2001 From: AYA Date: Thu, 16 May 2024 19:06:12 +0200 Subject: [PATCH 07/22] moving function definitions to ember-test-compatibility (execpt CommandInteraction) --- src/BUILD.gn | 3 - src/app/tests/BUILD.gn | 96 +++++-------- src/app/tests/TestAclAttribute.cpp | 46 +++---- src/app/tests/TestCommandInteraction.cpp | 152 ++++++++++----------- src/app/tests/TestReadInteraction.cpp | 111 +++++++-------- src/app/tests/TestWriteInteraction.cpp | 41 ++---- src/app/tests/ember-test-compatibility.cpp | 76 ++++++----- src/app/tests/ember-test-compatibility.h | 21 +-- 8 files changed, 248 insertions(+), 298 deletions(-) diff --git a/src/BUILD.gn b/src/BUILD.gn index 2bb801d72928fd..b24036c1a3783a 100644 --- a/src/BUILD.gn +++ b/src/BUILD.gn @@ -96,10 +96,7 @@ if (chip_build_tests) { tests += [ # TODO(#10447): App test has HF on EFR32. "${chip_root}/src/app/tests", - "${chip_root}/src/app/tests:tests_ember", "${chip_root}/src/app/tests:tests_nltest", - "${chip_root}/src/app/tests:tests_nltest_ember", - "${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 49275ac7ae2c2c..7b600a413cae39 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -135,36 +135,36 @@ source_set("ember-apptest-compatibility") { ] } -chip_test_suite("tests_ember") { - output_name = "libAppTestsEMBER" - - sources = [ - "${chip_root}/src/messaging/tests/ReliableMessageContextTestAccess.h", - "CommandHandlerTestAccess.h", - "CommandSenderTestAccess.h", - ] - test_sources = [ "TestCommandInteraction.cpp" ] - - cflags = [ "-Wconversion" ] - - public_deps = [ - ":binding-test-srcs", - ":ember-apptest-compatibility", - ":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", - ] -} +# chip_test_suite("tests_ember") { +# output_name = "libAppTestsEMBER" + +# sources = [ +# "${chip_root}/src/messaging/tests/ReliableMessageContextTestAccess.h", +# "CommandHandlerTestAccess.h", +# "CommandSenderTestAccess.h", +# ] +# test_sources = [ "TestCommandInteraction.cpp" ] + +# cflags = [ "-Wconversion" ] + +# public_deps = [ +# ":binding-test-srcs", +# ":ember-apptest-compatibility", +# ":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", +# ] +# } chip_test_suite("tests") { output_name = "libAppTests" @@ -177,8 +177,7 @@ chip_test_suite("tests") { test_sources = [ "TestAclAttribute.cpp", "TestBuilderParser.cpp", - - # "TestCommandInteraction.cpp", + "TestCommandInteraction.cpp", "TestMessageDef.cpp", "TestNullable.cpp", "TestStatusIB.cpp", @@ -202,37 +201,6 @@ chip_test_suite("tests") { "${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", - ] -} - -chip_test_suite_using_nltest("tests_nltest_ember") { - output_name = "libAppTestsNLEMBER" - - test_sources = [ - "TestReadInteraction.cpp", - "TestWriteInteraction.cpp", - ] - - cflags = [ "-Wconversion" ] - - public_deps = [ - ":binding-test-srcs", - ":ember-apptest-compatibility", - ":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", ] } @@ -263,9 +231,11 @@ chip_test_suite_using_nltest("tests_nltest") { "TestPendingNotificationMap.cpp", "TestPendingResponseTrackerImpl.cpp", "TestPowerSourceCluster.cpp", + "TestReadInteraction.cpp", "TestReportingEngine.cpp", "TestTestEventTriggerDelegate.cpp", "TestTimeSyncDataProvider.cpp", + "TestWriteInteraction.cpp", ] if (!chip_fake_platform) { diff --git a/src/app/tests/TestAclAttribute.cpp b/src/app/tests/TestAclAttribute.cpp index 4d0c27099377df..efa452db02423a 100644 --- a/src/app/tests/TestAclAttribute.cpp +++ b/src/app/tests/TestAclAttribute.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -45,10 +46,10 @@ namespace { using namespace chip; using namespace chip::Access; -chip::ClusterId kTestClusterId = 1; -chip::ClusterId kTestDeniedClusterId1 = 1000; -chip::ClusterId kTestDeniedClusterId2 = 3; -chip::EndpointId kTestEndpointId = 4; +// chip::ClusterId kTestClusterId = 1; +// chip::ClusterId kTestDeniedClusterId1 = 1000; +// chip::ClusterId kTestDeniedClusterId2 = 3; +// chip::EndpointId kTestEndpointId = 4; class TestAccessControlDelegate : public AccessControl::Delegate { @@ -56,7 +57,7 @@ class TestAccessControlDelegate : public AccessControl::Delegate CHIP_ERROR Check(const SubjectDescriptor & subjectDescriptor, const chip::Access::RequestPath & requestPath, Privilege requestPrivilege) override { - if (requestPath.cluster == kTestDeniedClusterId2) + if (requestPath.cluster == chip::Test::kTestDeniedClusterId2) { return CHIP_ERROR_ACCESS_DENIED; } @@ -112,21 +113,6 @@ class MockInteractionModelApp : public chip::app::ReadClient::Callback namespace chip { namespace app { -bool ConcreteAttributePathExists(const ConcreteAttributePath & aPath) -{ - return aPath.mClusterId != kTestDeniedClusterId1; -} - -Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath) -{ - if (aPath.mClusterId == kTestDeniedClusterId1) - { - return Protocols::InteractionModel::Status::UnsupportedCluster; - } - - return Protocols::InteractionModel::Status::Success; -} - class TestAclAttribute : public ::testing::Test { public: @@ -189,12 +175,12 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; - attributePathParams[0].mEndpointId = kTestEndpointId; - attributePathParams[0].mClusterId = kTestDeniedClusterId1; + attributePathParams[0].mEndpointId = chip::Test::kTestEndpointId; + attributePathParams[0].mClusterId = chip::Test::kTestDeniedClusterId1; attributePathParams[0].mAttributeId = 1; - attributePathParams[1].mEndpointId = kTestEndpointId; - attributePathParams[1].mClusterId = kTestDeniedClusterId1; + attributePathParams[1].mEndpointId = chip::Test::kTestEndpointId; + attributePathParams[1].mClusterId = chip::Test::kTestDeniedClusterId1; attributePathParams[1].mAttributeId = 2; ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); @@ -217,10 +203,10 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) chip::app::AttributePathParams attributePathParams[2]; - attributePathParams[0].mClusterId = kTestDeniedClusterId2; + attributePathParams[0].mClusterId = chip::Test::kTestDeniedClusterId2; attributePathParams[0].mAttributeId = 1; - attributePathParams[1].mClusterId = kTestDeniedClusterId2; + attributePathParams[1].mClusterId = chip::Test::kTestDeniedClusterId2; attributePathParams[1].mAttributeId = 2; ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); @@ -242,12 +228,12 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; - attributePathParams[0].mEndpointId = kTestEndpointId; - attributePathParams[0].mClusterId = kTestDeniedClusterId1; + attributePathParams[0].mEndpointId = chip::Test::kTestEndpointId; + attributePathParams[0].mClusterId = chip::Test::kTestDeniedClusterId1; attributePathParams[0].mAttributeId = 1; - attributePathParams[1].mEndpointId = kTestEndpointId; - attributePathParams[1].mClusterId = kTestClusterId; + attributePathParams[1].mEndpointId = chip::Test::kTestEndpointId; + attributePathParams[1].mClusterId = chip::Test::kTestClusterId; attributePathParams[1].mAttributeId = 2; ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); diff --git a/src/app/tests/TestCommandInteraction.cpp b/src/app/tests/TestCommandInteraction.cpp index a998fb75f93ccc..77f361987892a8 100644 --- a/src/app/tests/TestCommandInteraction.cpp +++ b/src/app/tests/TestCommandInteraction.cpp @@ -750,79 +750,79 @@ void TestCommandInteraction::ValidateCommandHandlerEncodeInvokeResponseMessage(b // 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. -TEST_F(TestCommandInteraction, TestCommandInvalidMessage1) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); - - AddInvokeRequestData(&commandSender); - asyncCommand = false; - - pTestContext->GetLoopback().mSentMessageCount = 0; - pTestContext->GetLoopback().mNumMessagesToDrop = 1; - pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); - EXPECT_EQ(err, CHIP_NO_ERROR); - pTestContext->DrainAndServiceIO(); - - EXPECT_EQ(pTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(pTestContext->GetLoopback().mDroppedMessageCount, 1u); - - 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); - EXPECT_FALSE(msgBuf.IsNull()); - System::PacketBufferTLVWriter writer; - writer.Init(std::move(msgBuf)); - StatusResponseMessage::Builder response; - response.Init(&writer); - response.Status(Protocols::InteractionModel::Status::Busy); - EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); - - PayloadHeader payloadHeader; - payloadHeader.SetExchangeID(0); - payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::StatusResponse); - chip::Test::MessageCapturer messageLog(*pTestContext); - messageLog.mCaptureStandaloneAcks = false; - - chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); - - // 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(pTestContext, privatecommandSender.GetExchangeCtx().Get()); - PretendWeGotReplyFromServers(pTestContext, privatecommandSender.GetExchangeCtx().Get()); - - pTestContext->GetLoopback().mSentMessageCount = 0; - pTestContext->GetLoopback().mNumMessagesToDrop = 0; - pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - pTestContext->GetLoopback().mDroppedMessageCount = 0; - - err = privatecommandSender.OnMessageReceived(privatecommandSender.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); - EXPECT_EQ(err, 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); - - pTestContext->DrainAndServiceIO(); - - // Client sent status report with invalid action, server's exchange has been closed, so all it sent is an MRP Ack - EXPECT_EQ(pTestContext->GetLoopback().mSentMessageCount, 2u); - CheckForInvalidAction(messageLog); - EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); - pTestContext->ExpireSessionAliceToBob(); - pTestContext->ExpireSessionBobToAlice(); - pTestContext->CreateSessionAliceToBob(); - pTestContext->CreateSessionBobToAlice(); -} +// TEST_F(TestCommandInteraction, TestCommandInvalidMessage1) +// { +// CHIP_ERROR err = CHIP_NO_ERROR; +// mockCommandSenderDelegate.ResetCounter(); +// app::CommandSender commandSender(&mockCommandSenderDelegate, &pTestContext->GetExchangeManager()); + +// AddInvokeRequestData(&commandSender); +// asyncCommand = false; + +// pTestContext->GetLoopback().mSentMessageCount = 0; +// pTestContext->GetLoopback().mNumMessagesToDrop = 1; +// pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; +// err = commandSender.SendCommandRequest(pTestContext->GetSessionBobToAlice()); +// EXPECT_EQ(err, CHIP_NO_ERROR); +// pTestContext->DrainAndServiceIO(); + +// EXPECT_EQ(pTestContext->GetLoopback().mSentMessageCount, 2u); +// EXPECT_EQ(pTestContext->GetLoopback().mDroppedMessageCount, 1u); + +// 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); +// EXPECT_FALSE(msgBuf.IsNull()); +// System::PacketBufferTLVWriter writer; +// writer.Init(std::move(msgBuf)); +// StatusResponseMessage::Builder response; +// response.Init(&writer); +// response.Status(Protocols::InteractionModel::Status::Busy); +// EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); + +// PayloadHeader payloadHeader; +// payloadHeader.SetExchangeID(0); +// payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::StatusResponse); +// chip::Test::MessageCapturer messageLog(*pTestContext); +// messageLog.mCaptureStandaloneAcks = false; + +// chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + +// // 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(pTestContext, privatecommandSender.GetExchangeCtx().Get()); +// PretendWeGotReplyFromServers(pTestContext, privatecommandSender.GetExchangeCtx().Get()); + +// pTestContext->GetLoopback().mSentMessageCount = 0; +// pTestContext->GetLoopback().mNumMessagesToDrop = 0; +// pTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; +// pTestContext->GetLoopback().mDroppedMessageCount = 0; + +// err = privatecommandSender.OnMessageReceived(privatecommandSender.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); +// EXPECT_EQ(err, 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); + +// pTestContext->DrainAndServiceIO(); + +// // Client sent status report with invalid action, server's exchange has been closed, so all it sent is an MRP Ack +// EXPECT_EQ(pTestContext->GetLoopback().mSentMessageCount, 2u); +// CheckForInvalidAction(messageLog); +// EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); +// pTestContext->ExpireSessionAliceToBob(); +// pTestContext->ExpireSessionBobToAlice(); +// pTestContext->CreateSessionAliceToBob(); +// pTestContext->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. @@ -870,7 +870,7 @@ TEST_F(TestCommandInteraction, TestCommandInvalidMessage2) // not gotten dropped. chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); - PretendWeGotReplyFromServer(pTestContext, privatecommandSender.GetExchangeCtx().Get()); + PretendWeGotReplyFromServers(pTestContext, privatecommandSender.GetExchangeCtx().Get()); pTestContext->GetLoopback().mSentMessageCount = 0; pTestContext->GetLoopback().mNumMessagesToDrop = 0; @@ -942,7 +942,7 @@ TEST_F(TestCommandInteraction, TestCommandInvalidMessage3) // MRP state to look like what it would have looked like if the packet had // not gotten dropped. chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); - PretendWeGotReplyFromServer(pTestContext, privatecommandSender.GetExchangeCtx().Get()); + PretendWeGotReplyFromServers(pTestContext, privatecommandSender.GetExchangeCtx().Get()); pTestContext->GetLoopback().mSentMessageCount = 0; pTestContext->GetLoopback().mNumMessagesToDrop = 0; @@ -1014,7 +1014,7 @@ TEST_F(TestCommandInteraction, TestCommandInvalidMessage4) // MRP state to look like what it would have looked like if the packet had // not gotten dropped. chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); - PretendWeGotReplyFromServer(pTestContext, privatecommandSender.GetExchangeCtx().Get()); + PretendWeGotReplyFromServers(pTestContext, privatecommandSender.GetExchangeCtx().Get()); pTestContext->GetLoopback().mSentMessageCount = 0; pTestContext->GetLoopback().mNumMessagesToDrop = 0; diff --git a/src/app/tests/TestReadInteraction.cpp b/src/app/tests/TestReadInteraction.cpp index 56026d67da9568..b4d82380f3f2cd 100644 --- a/src/app/tests/TestReadInteraction.cpp +++ b/src/app/tests/TestReadInteraction.cpp @@ -56,14 +56,14 @@ uint8_t gDebugEventBuffer[128]; uint8_t gInfoEventBuffer[128]; uint8_t gCritEventBuffer[128]; chip::app::CircularEventBuffer gCircularEventBuffer[3]; -chip::ClusterId kTestClusterId = 6; -chip::ClusterId kTestEventClusterId = chip::Test::MockClusterId(1); -chip::ClusterId kInvalidTestClusterId = 7; -chip::EndpointId kTestEndpointId = 1; -chip::EndpointId kTestEventEndpointId = chip::Test::kMockEndpoint1; -chip::EventId kTestEventIdDebug = chip::Test::MockEventId(1); -chip::EventId kTestEventIdCritical = chip::Test::MockEventId(2); -uint8_t kTestFieldValue1 = 1; +chip::ClusterId kTestClusterId = 6; +chip::ClusterId kTestEventClusterId = chip::Test::MockClusterId(1); +chip::ClusterId kInvalidTestClusterId = 7; +chip::EndpointId kTestEndpointId = 1; +chip::EndpointId kTestEventEndpointId = chip::Test::kMockEndpoint1; +chip::EventId kTestEventIdDebug = chip::Test::MockEventId(1); +chip::EventId kTestEventIdCritical = chip::Test::MockEventId(2); +// uint8_t kTestFieldValue1 = 1; chip::TLV::Tag kTestEventTag = chip::TLV::ContextTag(1); chip::EndpointId kInvalidTestEndpointId = 3; chip::DataVersion kTestDataVersion1 = 3; @@ -297,53 +297,54 @@ using ReadHandlerNode = chip::app::reporting::ReportScheduler::ReadHandlerNo namespace chip { namespace app { -CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, - const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, - AttributeEncodeState * apEncoderState) -{ - if (aPath.mClusterId >= Test::kMockEndpointMin) - { - return Test::ReadSingleMockClusterData(aSubjectDescriptor.fabricIndex, aPath, aAttributeReports, apEncoderState); - } - - if (!(aPath.mClusterId == kTestClusterId && aPath.mEndpointId == kTestEndpointId)) - { - AttributeReportIB::Builder & attributeReport = aAttributeReports.CreateAttributeReport(); - ReturnErrorOnFailure(aAttributeReports.GetError()); - ChipLogDetail(DataManagement, "TEST Cluster %" PRIx32 ", Field %" PRIx32 " is dirty", aPath.mClusterId, aPath.mAttributeId); - - AttributeStatusIB::Builder & attributeStatus = attributeReport.CreateAttributeStatus(); - ReturnErrorOnFailure(attributeReport.GetError()); - AttributePathIB::Builder & attributePath = attributeStatus.CreatePath(); - ReturnErrorOnFailure(attributeStatus.GetError()); - - attributePath.Endpoint(aPath.mEndpointId).Cluster(aPath.mClusterId).Attribute(aPath.mAttributeId).EndOfAttributePathIB(); - ReturnErrorOnFailure(attributePath.GetError()); - StatusIB::Builder & errorStatus = attributeStatus.CreateErrorStatus(); - ReturnErrorOnFailure(attributeStatus.GetError()); - errorStatus.EncodeStatusIB(StatusIB(Protocols::InteractionModel::Status::UnsupportedAttribute)); - ReturnErrorOnFailure(errorStatus.GetError()); - ReturnErrorOnFailure(attributeStatus.EndOfAttributeStatusIB()); - return attributeReport.EndOfAttributeReportIB(); - } - - return AttributeValueEncoder(aAttributeReports, aSubjectDescriptor, aPath, 0 /* dataVersion */).Encode(kTestFieldValue1); -} - -bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) -{ - if (kTestDataVersion1 == aRequiredVersion) - { - return true; - } - - return false; -} - -bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) -{ - return false; -} +// CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, +// const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, +// AttributeEncodeState * apEncoderState) +// { +// if (aPath.mClusterId >= Test::kMockEndpointMin) +// { +// return Test::ReadSingleMockClusterData(aSubjectDescriptor.fabricIndex, aPath, aAttributeReports, apEncoderState); +// } + +// if (!(aPath.mClusterId == kTestClusterId && aPath.mEndpointId == kTestEndpointId)) +// { +// AttributeReportIB::Builder & attributeReport = aAttributeReports.CreateAttributeReport(); +// ReturnErrorOnFailure(aAttributeReports.GetError()); +// ChipLogDetail(DataManagement, "TEST Cluster %" PRIx32 ", Field %" PRIx32 " is dirty", aPath.mClusterId, +// aPath.mAttributeId); + +// AttributeStatusIB::Builder & attributeStatus = attributeReport.CreateAttributeStatus(); +// ReturnErrorOnFailure(attributeReport.GetError()); +// AttributePathIB::Builder & attributePath = attributeStatus.CreatePath(); +// ReturnErrorOnFailure(attributeStatus.GetError()); + +// attributePath.Endpoint(aPath.mEndpointId).Cluster(aPath.mClusterId).Attribute(aPath.mAttributeId).EndOfAttributePathIB(); +// ReturnErrorOnFailure(attributePath.GetError()); +// StatusIB::Builder & errorStatus = attributeStatus.CreateErrorStatus(); +// ReturnErrorOnFailure(attributeStatus.GetError()); +// errorStatus.EncodeStatusIB(StatusIB(Protocols::InteractionModel::Status::UnsupportedAttribute)); +// ReturnErrorOnFailure(errorStatus.GetError()); +// ReturnErrorOnFailure(attributeStatus.EndOfAttributeStatusIB()); +// return attributeReport.EndOfAttributeReportIB(); +// } + +// return AttributeValueEncoder(aAttributeReports, aSubjectDescriptor, aPath, 0 /* dataVersion */).Encode(kTestFieldValue1); +// } + +// bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) +// { +// if (kTestDataVersion1 == aRequiredVersion) +// { +// return true; +// } + +// return false; +// } + +// bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) +// { +// return false; +// } class TestReadInteraction { diff --git a/src/app/tests/TestWriteInteraction.cpp b/src/app/tests/TestWriteInteraction.cpp index 16647ca523829e..6b070668b2bafa 100644 --- a/src/app/tests/TestWriteInteraction.cpp +++ b/src/app/tests/TestWriteInteraction.cpp @@ -16,6 +16,11 @@ * limitations under the License. */ +#include +#include +#include +#include + #include #include #include @@ -34,15 +39,11 @@ #include #include -#include -#include -#include - namespace { -uint8_t attributeDataTLV[CHIP_CONFIG_DEFAULT_UDP_MTU_SIZE]; -size_t attributeDataTLVLen = 0; -constexpr chip::DataVersion kRejectedDataVersion = 1; +// uint8_t attributeDataTLV[CHIP_CONFIG_DEFAULT_UDP_MTU_SIZE]; +// size_t attributeDataTLVLen = 0; +// constexpr chip::DataVersion kRejectedDataVersion = 1; constexpr chip::DataVersion kAcceptedDataVersion = 5; constexpr uint16_t kMaxGroupsPerFabric = 5; constexpr uint16_t kMaxGroupKeysPerFabric = 8; @@ -363,28 +364,6 @@ void TestWriteInteraction::TestWriteHandler(nlTestSuite * apSuite, void * apCont } } -const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aConcreteClusterPath) -{ - // Note: This test does not make use of the real attribute metadata. - static EmberAfAttributeMetadata stub = { .defaultValue = EmberAfDefaultOrMinMaxAttributeValue(uint32_t(0)) }; - return &stub; -} - -CHIP_ERROR WriteSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteDataAttributePath & aPath, - TLV::TLVReader & aReader, WriteHandler * aWriteHandler) -{ - if (aPath.mDataVersion.HasValue() && aPath.mDataVersion.Value() == kRejectedDataVersion) - { - return aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::DataVersionMismatch); - } - - TLV::TLVWriter writer; - writer.Init(attributeDataTLV); - writer.CopyElement(TLV::AnonymousTag(), aReader); - attributeDataTLVLen = writer.GetLengthWritten(); - return aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Success); -} - void TestWriteInteraction::TestWriteRoundtripWithClusterObjects(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast(apContext); @@ -434,7 +413,7 @@ void TestWriteInteraction::TestWriteRoundtripWithClusterObjects(nlTestSuite * ap { app::Clusters::UnitTesting::Structs::SimpleStruct::Type dataRx; TLV::TLVReader reader; - reader.Init(attributeDataTLV, attributeDataTLVLen); + 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); @@ -531,7 +510,7 @@ void TestWriteInteraction::TestWriteRoundtripWithClusterObjectsVersionMismatch(n dataTxValue.b = true; DataModel::Nullable dataTx; dataTx.SetNonNull(dataTxValue); - Optional version(kRejectedDataVersion); + Optional version(chip::Test::kRejectedDataVersion); writeClient.EncodeAttribute(attributePathParams, dataTx, version); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); diff --git a/src/app/tests/ember-test-compatibility.cpp b/src/app/tests/ember-test-compatibility.cpp index 98fec28e2c719b..e7474ce6743e60 100644 --- a/src/app/tests/ember-test-compatibility.cpp +++ b/src/app/tests/ember-test-compatibility.cpp @@ -11,38 +11,48 @@ #include namespace chip { +uint8_t chip::Test::attributeDataTLV[CHIP_CONFIG_DEFAULT_UDP_MTU_SIZE]; +size_t chip::Test::attributeDataTLVLen = 0; namespace app { -constexpr chip::ClusterId kTestClusterId = 6; -constexpr uint8_t kTestFieldValue1 = 1; -constexpr chip::EndpointId kTestEndpointId = 1; - -// strong defintion in TestWriteInteraction.cpp -__attribute__((weak)) CHIP_ERROR WriteSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, - const ConcreteDataAttributePath & aPath, TLV::TLVReader & aReader, - WriteHandler * aWriteHandler) -{ - - return CHIP_NO_ERROR; -} - -// strong defintion in TestWriteInteraction.cpp -__attribute__((weak)) const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aConcreteClusterPath) +// was previously in TestWriteInteraction.cpp +const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aConcreteClusterPath) { // Note: This test does not make use of the real attribute metadata. static EmberAfAttributeMetadata stub = { .defaultValue = EmberAfDefaultOrMinMaxAttributeValue(uint32_t(0)) }; return &stub; } -// strong defintion in TestAclAttribute.cpp -__attribute__((weak)) bool ConcreteAttributePathExists(const ConcreteAttributePath & aPath) +// was previously in TestWriteInteraction.cpp +CHIP_ERROR WriteSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteDataAttributePath & aPath, + TLV::TLVReader & aReader, WriteHandler * aWriteHandler) { - return true; + if (aPath.mDataVersion.HasValue() && aPath.mDataVersion.Value() == Test::kRejectedDataVersion) + { + return aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::DataVersionMismatch); + } + + TLV::TLVWriter writer; + writer.Init(chip::Test::attributeDataTLV); + writer.CopyElement(TLV::AnonymousTag(), aReader); + chip::Test::attributeDataTLVLen = writer.GetLengthWritten(); + return aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Success); } -// strong defintion in TestAclAttribute.cpp -__attribute__((weak)) Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath) +// was previously in TestAclAttribute.cpp +bool ConcreteAttributePathExists(const ConcreteAttributePath & aPath) { + return aPath.mClusterId != Test::kTestDeniedClusterId1; +} + +// was previously in TestAclAttribute.cpp +Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath) +{ + if (aPath.mClusterId == Test::kTestDeniedClusterId1) + { + return Protocols::InteractionModel::Status::UnsupportedCluster; + } + return Protocols::InteractionModel::Status::Success; } @@ -63,30 +73,34 @@ __attribute__((weak)) void DispatchSingleClusterCommand(const ConcreteCommandPat return; } -// strong defintion in TestReadInteraction.cpp -__attribute__((weak)) bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) +// was previously in TestReadInteraction.cpp +bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) { + if (Test::kTestDataVersion1 == aRequiredVersion) + { + return true; + } + return false; } -// strong defintion in TestReadInteraction.cpp -__attribute__((weak)) bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) +// was previously in TestReadInteraction.cpp +bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) { return false; } -// strong defintion in TestReadInteraction.cpp -__attribute__((weak)) CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, - const ConcreteReadAttributePath & aPath, - AttributeReportIBs::Builder & aAttributeReports, - AttributeEncodeState * apEncoderState) +// was previously in TestReadInteraction.cpp +CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, + const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, + AttributeEncodeState * apEncoderState) { if (aPath.mClusterId >= Test::kMockEndpointMin) { return Test::ReadSingleMockClusterData(aSubjectDescriptor.fabricIndex, aPath, aAttributeReports, apEncoderState); } - if (!(aPath.mClusterId == kTestClusterId && aPath.mEndpointId == kTestEndpointId)) + if (!(aPath.mClusterId == Test::kTestClusterId && aPath.mEndpointId == Test::kTestEndpointId)) { AttributeReportIB::Builder & attributeReport = aAttributeReports.CreateAttributeReport(); ReturnErrorOnFailure(aAttributeReports.GetError()); @@ -107,7 +121,7 @@ __attribute__((weak)) CHIP_ERROR ReadSingleClusterData(const Access::SubjectDesc return attributeReport.EndOfAttributeReportIB(); } - return AttributeValueEncoder(aAttributeReports, aSubjectDescriptor, aPath, 0 /* dataVersion */).Encode(kTestFieldValue1); + return AttributeValueEncoder(aAttributeReports, aSubjectDescriptor, aPath, 0 /* dataVersion */).Encode(Test::kTestFieldValue1); } } // namespace app diff --git a/src/app/tests/ember-test-compatibility.h b/src/app/tests/ember-test-compatibility.h index d1c16952269e30..c214cba275396f 100644 --- a/src/app/tests/ember-test-compatibility.h +++ b/src/app/tests/ember-test-compatibility.h @@ -7,20 +7,23 @@ #include namespace chip { -namespace app { -// constexpr uint8_t kTestFieldValue1 = 1; +namespace Test { -// constexpr chip::ClusterId kTestClusterId = 3; -// constexpr chip::EndpointId kTestEndpointId = 1; -// constexpr chip::DataVersion kTestDataVersion1 = 3; -// constexpr chip::DataVersion kTestDataVersion2 = 5; +constexpr chip::ClusterId kTestDeniedClusterId1 = 1000; +constexpr chip::ClusterId kTestDeniedClusterId2 = 3; -// constexpr chip::DataVersion kRejectedDataVersion = 1; +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::DataVersion kRejectedDataVersion = 1; +extern uint8_t attributeDataTLV[CHIP_CONFIG_DEFAULT_UDP_MTU_SIZE]; +extern size_t attributeDataTLVLen; -// constexpr CommandId kTestNonExistCommandId = 0; +} // namespace Test +namespace app { CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, From 13e11e6524e9847a8f48f32f1cd2dbdcf07964b3 Mon Sep 17 00:00:00 2001 From: AYA Date: Thu, 16 May 2024 19:30:05 +0200 Subject: [PATCH 08/22] applying restyled patch --- src/app/ReadHandler.h | 4 ++-- src/app/tests/TestReadInteraction.cpp | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/app/ReadHandler.h b/src/app/ReadHandler.h index db6b6cfe983bb6..a5155daa5837f5 100644 --- a/src/app/ReadHandler.h +++ b/src/app/ReadHandler.h @@ -130,14 +130,14 @@ class ReadHandler : public Messaging::ExchangeDelegate /* * Called after a subscription has been fully established. */ - virtual void OnSubscriptionEstablished(ReadHandler & aReadHandler) {}; + virtual void OnSubscriptionEstablished(ReadHandler & aReadHandler){}; /* * Called right before a subscription is about to get terminated. This is only called on subscriptions that were terminated * after they had been fully established (and therefore had called OnSubscriptionEstablished). * OnSubscriptionEstablishment(). */ - virtual void OnSubscriptionTerminated(ReadHandler & aReadHandler) {}; + virtual void OnSubscriptionTerminated(ReadHandler & aReadHandler){}; }; /* diff --git a/src/app/tests/TestReadInteraction.cpp b/src/app/tests/TestReadInteraction.cpp index 92940ce1bc2938..31b89f600eb844 100644 --- a/src/app/tests/TestReadInteraction.cpp +++ b/src/app/tests/TestReadInteraction.cpp @@ -1372,7 +1372,8 @@ void TestReadInteraction::TestSetDirtyBetweenChunks(nlTestSuite * apSuite, void public: DirtyingMockDelegate(AttributePathParams (&aReadPaths)[2], int & aNumAttributeResponsesWhenSetDirty, int & aNumArrayItemsWhenSetDirty) : - mReadPaths(aReadPaths), mNumAttributeResponsesWhenSetDirty(aNumAttributeResponsesWhenSetDirty), + mReadPaths(aReadPaths), + mNumAttributeResponsesWhenSetDirty(aNumAttributeResponsesWhenSetDirty), mNumArrayItemsWhenSetDirty(aNumArrayItemsWhenSetDirty) {} From c882cb3e5a671cd2f6e0117c831a338722eaf6f0 Mon Sep 17 00:00:00 2001 From: AYA Date: Thu, 16 May 2024 19:58:06 +0200 Subject: [PATCH 09/22] adding sourcefile to gn --- src/messaging/tests/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/src/messaging/tests/BUILD.gn b/src/messaging/tests/BUILD.gn index 89f0934486b9c1..813622224eeb77 100644 --- a/src/messaging/tests/BUILD.gn +++ b/src/messaging/tests/BUILD.gn @@ -26,6 +26,7 @@ static_library("helpers") { sources = [ "MessagingContext.cpp", "MessagingContext.h", + "ReliableMessageContextTestAccess.h", ] cflags = [ "-Wconversion" ] From b761799a6ae5109b6a467a9fbc8ec4cf83ac1752 Mon Sep 17 00:00:00 2001 From: AYA Date: Thu, 16 May 2024 22:42:47 +0200 Subject: [PATCH 10/22] openiot fix --- src/test_driver/openiotsdk/unit-tests/test_components.txt | 1 + src/test_driver/openiotsdk/unit-tests/test_components_nl.txt | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test_driver/openiotsdk/unit-tests/test_components.txt b/src/test_driver/openiotsdk/unit-tests/test_components.txt index 8c59caffcf8de4..f29450632e0e83 100644 --- a/src/test_driver/openiotsdk/unit-tests/test_components.txt +++ b/src/test_driver/openiotsdk/unit-tests/test_components.txt @@ -20,3 +20,4 @@ SecureChannelTests ICDServerTests DataModelTests InetLayerTests +AppTests diff --git a/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt b/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt index 55ebc4e3cd7e7e..bebe99d02a15c6 100644 --- a/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt +++ b/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt @@ -1,3 +1,3 @@ -AppTests +AppTestsNL MessagingLayerTests SecureChannelTestsNL From 14c059093e121379fd0f2ebe31b5860471a38231 Mon Sep 17 00:00:00 2001 From: AYA Date: Fri, 17 May 2024 10:30:38 +0200 Subject: [PATCH 11/22] clang-tidy fix --- src/app/tests/ember-test-compatibility.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/app/tests/ember-test-compatibility.cpp b/src/app/tests/ember-test-compatibility.cpp index e7474ce6743e60..471f4cfd43fa8c 100644 --- a/src/app/tests/ember-test-compatibility.cpp +++ b/src/app/tests/ember-test-compatibility.cpp @@ -69,9 +69,7 @@ ServerClusterCommandExists(const ConcreteCommandPath & aRequestCommandPath) // strong defintion in TestCommandInteraction.cpp __attribute__((weak)) void DispatchSingleClusterCommand(const ConcreteCommandPath & aRequestCommandPath, chip::TLV::TLVReader & aReader, CommandHandler * apCommandObj) -{ - return; -} +{} // was previously in TestReadInteraction.cpp bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) From db0160dd6d4acf71caf68ce13f72fe9d1e4f2394 Mon Sep 17 00:00:00 2001 From: AYA Date: Mon, 20 May 2024 17:23:32 +0200 Subject: [PATCH 12/22] Adding TestCommandInteraction and WriteInteraction --- src/app/WriteClient.h | 12 +- src/app/WriteHandler.h | 5 + src/app/tests/BUILD.gn | 4 +- src/app/tests/CommandSenderTestAccess.h | 2 +- src/app/tests/TestAclAttribute.cpp | 2 +- src/app/tests/TestCommandInteraction.cpp | 1805 ++++++++++------------ src/app/tests/TestWriteInteraction.cpp | 837 +++++----- src/app/tests/WriteClientTestAccess.h | 59 + src/app/tests/WriteHandlerTestAccess.h | 49 + 9 files changed, 1377 insertions(+), 1398 deletions(-) create mode 100644 src/app/tests/WriteClientTestAccess.h create mode 100644 src/app/tests/WriteHandlerTestAccess.h diff --git a/src/app/WriteClient.h b/src/app/WriteClient.h index 90f0f3a24b6c1a..354c6488f3b27d 100644 --- a/src/app/WriteClient.h +++ b/src/app/WriteClient.h @@ -42,6 +42,10 @@ #include namespace chip { +namespace Test { +class WriteClientTestAccess; + +} namespace app { class InteractionModelEngine; @@ -125,8 +129,7 @@ class WriteClient : public Messaging::ExchangeDelegate */ WriteClient(Messaging::ExchangeManager * apExchangeMgr, Callback * apCallback, const Optional & aTimedWriteTimeoutMs, bool aSuppressResponse = false) : - mpExchangeMgr(apExchangeMgr), - mExchangeCtx(*this), mpCallback(apCallback), mTimedWriteTimeoutMs(aTimedWriteTimeoutMs), + mpExchangeMgr(apExchangeMgr), mExchangeCtx(*this), mpCallback(apCallback), mTimedWriteTimeoutMs(aTimedWriteTimeoutMs), mSuppressResponse(aSuppressResponse) { assertChipStackLockedByCurrentThread(); @@ -135,8 +138,8 @@ class WriteClient : public Messaging::ExchangeDelegate #if CONFIG_BUILD_FOR_HOST_UNIT_TEST WriteClient(Messaging::ExchangeManager * apExchangeMgr, Callback * apCallback, const Optional & aTimedWriteTimeoutMs, uint16_t aReservedSize) : - mpExchangeMgr(apExchangeMgr), - mExchangeCtx(*this), mpCallback(apCallback), mTimedWriteTimeoutMs(aTimedWriteTimeoutMs), mReservedSize(aReservedSize) + mpExchangeMgr(apExchangeMgr), mExchangeCtx(*this), mpCallback(apCallback), mTimedWriteTimeoutMs(aTimedWriteTimeoutMs), + mReservedSize(aReservedSize) { assertChipStackLockedByCurrentThread(); } @@ -237,6 +240,7 @@ class WriteClient : public Messaging::ExchangeDelegate private: friend class TestWriteInteraction; friend class InteractionModelEngine; + friend class chip::Test::WriteClientTestAccess; enum class State { diff --git a/src/app/WriteHandler.h b/src/app/WriteHandler.h index 907aa043561eed..9919776fb62cee 100644 --- a/src/app/WriteHandler.h +++ b/src/app/WriteHandler.h @@ -35,6 +35,9 @@ #include namespace chip { +namespace Test { +class WriteHandlerTestAccess; +} namespace app { class WriteHandler; @@ -132,6 +135,8 @@ class WriteHandler : public Messaging::ExchangeDelegate private: friend class TestWriteInteraction; + friend class chip::Test::WriteHandlerTestAccess; + enum class State { Uninitialized = 0, // The handler has not been initialized diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index fe1c7935995123..cff63a1b5cdf90 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -147,12 +147,14 @@ chip_test_suite("tests") { test_sources = [ "TestAclAttribute.cpp", "TestBuilderParser.cpp", + "TestCommandInteraction.cpp", "TestMessageDef.cpp", "TestNullable.cpp", "TestReportingEngine.cpp", "TestStatusIB.cpp", "TestStatusResponseMessage.cpp", "TestTimedHandler.cpp", + "TestWriteInteraction.cpp", ] cflags = [ "-Wconversion" ] @@ -187,7 +189,6 @@ chip_test_suite_using_nltest("tests_nltest") { "TestBasicCommandPathRegistry.cpp", "TestBindingTable.cpp", "TestClusterInfo.cpp", - "TestCommandInteraction.cpp", "TestCommandPathParams.cpp", "TestConcreteAttributePath.cpp", "TestDataModelSerialization.cpp", @@ -205,7 +206,6 @@ chip_test_suite_using_nltest("tests_nltest") { "TestReadInteraction.cpp", "TestTestEventTriggerDelegate.cpp", "TestTimeSyncDataProvider.cpp", - "TestWriteInteraction.cpp", ] if (!chip_fake_platform) { diff --git a/src/app/tests/CommandSenderTestAccess.h b/src/app/tests/CommandSenderTestAccess.h index 6ff2bd0a7dfe64..0b67f2ef8f0979 100644 --- a/src/app/tests/CommandSenderTestAccess.h +++ b/src/app/tests/CommandSenderTestAccess.h @@ -42,7 +42,7 @@ class CommandSenderTestAccess void SetFinishedCommandCount(uint16_t aFinishedCommandCount) { pCommandSender->mFinishedCommandCount = aFinishedCommandCount; } - Messaging::ExchangeHolder GetExchangeCtx() { return pCommandSender->mExchangeCtx; } + Messaging::ExchangeHolder & GetExchangeCtx() { return pCommandSender->mExchangeCtx; } CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader, System::PacketBufferHandle && aPayload) diff --git a/src/app/tests/TestAclAttribute.cpp b/src/app/tests/TestAclAttribute.cpp index efa452db02423a..d143bffef9792a 100644 --- a/src/app/tests/TestAclAttribute.cpp +++ b/src/app/tests/TestAclAttribute.cpp @@ -16,7 +16,7 @@ * limitations under the License. */ -#include +#include #include #include diff --git a/src/app/tests/TestCommandInteraction.cpp b/src/app/tests/TestCommandInteraction.cpp index 195580ce8702a5..96284d19cc7dc5 100644 --- a/src/app/tests/TestCommandInteraction.cpp +++ b/src/app/tests/TestCommandInteraction.cpp @@ -24,44 +24,78 @@ #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 +/** + * 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(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) { \ + chip::Test::ReliableMessageContextTestAccess(localExchange) \ + .SetPendingPeerAckMessageCounter(entry->retainedBuf.GetMessageCounter()); \ + return Loop::Break; \ + }); \ + } 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 @@ -75,9 +109,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; @@ -93,6 +124,12 @@ namespace app { CommandHandler::Handle asyncCommandHandle; +enum class ForcedSizeBufferLengthHint +{ + kSizeBetween0and255, + kSizeGreaterThan255, +}; + struct ForcedSizeBuffer { chip::Platform::ScopedMemoryBufferWithSize mBuffer; @@ -119,10 +156,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) @@ -165,25 +225,25 @@ void DispatchSingleClusterCommand(const ConcreteCommandPath & aRequestCommandPat TLV::TLVType outerContainerType; CHIP_ERROR err = aReader.EnterContainer(outerContainerType); - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_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(err, CHIP_NO_ERROR); + EXPECT_TRUE(val); } err = aReader.ExitContainer(outerContainerType); - NL_TEST_ASSERT(gSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); if (asyncCommand) { @@ -319,66 +379,44 @@ class MockCommandHandlerCallback : public CommandHandler::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 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); + static void SetUpTestSuite() + { + mpTestContext = new TestContext; + mpTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + mpTestContext->TearDownTestSuite(); + if (mpTestContext != nullptr) + { + delete mpTestContext; + } + } - static void TestCommandSenderAbruptDestruction(nlTestSuite * apSuite, void * apContext); + void SetUp() override + { + if (mpTestContext != nullptr) + { + mpTestContext->SetUp(); + } + } + void TearDown() override + { + if (mpTestContext != nullptr) + { + mpTestContext->TearDown(); + } + } + static TestContext * mpTestContext; static size_t GetNumActiveCommandResponderObjects() { return chip::app::InteractionModelEngine::GetInstance()->mCommandResponderObjs.Allocated(); } -private: /** * With the introduction of batch invoke commands, CommandHandler keeps track of incoming * ConcreteCommandPath and the associated CommandRefs. These are normally populated @@ -390,8 +428,7 @@ class TestCommandInteraction { public: CommandHandlerWithUnrespondedCommand(CommandHandler::Callback * apCallback, const ConcreteCommandPath & aRequestCommandPath, - const Optional & aRef) : - CommandHandler(apCallback) + const Optional & aRef) : CommandHandler(apCallback) { GetCommandPathRegistry().Add(aRequestCommandPath, aRef.std_optional()); SetExchangeInterface(&mMockCommandResponder); @@ -401,28 +438,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, CommandHandler * apCommandHandler, - const ConcreteCommandPath & aRequestCommandPath, uint32_t aSizeToLeaveInBuffer); - static void ValidateCommandHandlerEncodeInvokeResponseMessage(nlTestSuite * apSuite, void * apContext, bool aNeedStatusCode); + static void FillCurrentInvokeResponseBuffer(CommandHandler * apCommandHandler, const ConcreteCommandPath & aRequestCommandPath, + uint32_t aSizeToLeaveInBuffer); + static void ValidateCommandHandlerEncodeInvokeResponseMessage(bool aNeedStatusCode); }; +TestContext * TestCommandInteraction::mpTestContext = nullptr; class TestExchangeDelegate : public Messaging::ExchangeDelegate { @@ -440,9 +474,8 @@ 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; @@ -451,20 +484,20 @@ void TestCommandInteraction::GenerateInvokeRequest(nlTestSuite * apSuite, void * writer.Init(std::move(aPayload)); err = invokeRequestMessageBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); invokeRequestMessageBuilder.SuppressResponse(true).TimedRequest(aIsTimedRequest); InvokeRequests::Builder & invokeRequests = invokeRequestMessageBuilder.CreateInvokeRequests(); - NL_TEST_ASSERT(apSuite, invokeRequestMessageBuilder.GetError() == CHIP_NO_ERROR); + EXPECT_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) { @@ -472,30 +505,30 @@ void TestCommandInteraction::GenerateInvokeRequest(nlTestSuite * apSuite, void * 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(err, CHIP_NO_ERROR); err = pWriter->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = pWriter->EndContainer(dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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); + EXPECT_EQ(invokeRequestMessageBuilder.GetError(), CHIP_NO_ERROR); err = writer.Finalize(&aPayload); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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) { @@ -505,23 +538,23 @@ void TestCommandInteraction::GenerateInvokeResponse(nlTestSuite * apSuite, void writer.Init(std::move(aPayload)); err = invokeResponseMessageBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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) { @@ -529,73 +562,71 @@ void TestCommandInteraction::GenerateInvokeResponse(nlTestSuite * apSuite, void 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(err, CHIP_NO_ERROR); err = pWriter->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = pWriter->EndContainer(dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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(err, 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(err, 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(err, CHIP_NO_ERROR); err = apCommandSender->FinishCommand(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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(err, 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(err, 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) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -611,237 +642,78 @@ void TestCommandInteraction::AddInvokeResponseData(nlTestSuite * apSuite, void * const CommandHandler::InvokeResponseParameters prepareParams(requestCommandPath); ConcreteCommandPath responseCommandPath = { kTestEndpointId, kTestClusterId, aResponseCommandId }; err = apCommandHandler->PrepareInvokeResponseCommand(responseCommandPath, prepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); chip::TLV::TLVWriter * writer = apCommandHandler->GetCommandDataIBTLVWriter(); err = writer->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = apCommandHandler->FinishCommand(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } } -uint32_t TestCommandInteraction::GetAddResponseDataOverheadSizeForPath(nlTestSuite * apSuite, - const ConcreteCommandPath & aRequestCommandPath, +uint32_t TestCommandInteraction::GetAddResponseDataOverheadSizeForPath(const ConcreteCommandPath & aRequestCommandPath, ForcedSizeBufferLengthHint aBufferSizeHint) { BasicCommandPathRegistry<4> basicCommandPathRegistry; MockCommandResponder mockCommandResponder; CommandHandler::TestOnlyOverrides testOnlyOverrides{ &basicCommandPathRegistry, &mockCommandResponder }; CommandHandler commandHandler(testOnlyOverrides, &mockCommandHandlerDelegate); - commandHandler.mReserveSpaceForMoreChunkMessages = true; - ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; - ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; + chip::Test::CommandHandlerTestAccess(&commandHandler).SetReserveSpaceForMoreChunkMessages(true); + 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = commandHandler.AllocateBuffer(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - uint32_t remainingSizeBefore = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); + EXPECT_EQ(err, CHIP_NO_ERROR); + + uint32_t remainingSizeBefore = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().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); - uint32_t remainingSizeAfter = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - uint32_t delta = remainingSizeBefore - remainingSizeAfter - sizeOfForcedSizeBuffer; + EXPECT_EQ(err, CHIP_NO_ERROR); + uint32_t remainingSizeAfter = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + uint32_t delta = remainingSizeBefore - remainingSizeAfter - sizeOfForcedSizeBuffer; return delta; } -void TestCommandInteraction::FillCurrentInvokeResponseBuffer(nlTestSuite * apSuite, CommandHandler * apCommandHandler, +void TestCommandInteraction::FillCurrentInvokeResponseBuffer(CommandHandler * 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(err, 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); + EXPECT_GE(sizeToFill, 256u); 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 CommandHandler::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); + EXPECT_EQ(err, CHIP_NO_ERROR); } -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 CommandHandler::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); - - 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::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, @@ -852,424 +724,519 @@ void TestCommandInteraction::ValidateCommandHandlerEncodeInvokeResponseMessage(n // be handle already acquired on the callers behalf. CommandHandler::Handle handle(&commandHandler); - AddInvokeResponseData(apSuite, apContext, &commandHandler, aNeedStatusCode); - } - NL_TEST_ASSERT(apSuite, !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(); - auto requestCommandPath = ConcreteCommandPath(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()); + AddInvokeResponseData(&commandHandler, aNeedStatusCode); } - NL_TEST_ASSERT(apSuite, !commandHandler.mMockCommandResponder.mChunks.IsNull()); + EXPECT_FALSE(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(TestCommandInteraction, TestCommandInvalidMessage1) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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; + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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()); + 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; + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + // 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, privatecommandSender.GetExchangeCtx().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); + err = privatecommandSender.OnMessageReceived(privatecommandSender.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); + EXPECT_EQ(err, 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(TestCommandInteraction, TestCommandInvalidMessage2) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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; + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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()); + 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); - 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()); + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + + PretendWeGotReplyFromServer(*mpTestContext, privatecommandSender.GetExchangeCtx().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_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); + err = privatecommandSender.OnMessageReceived(privatecommandSender.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); + EXPECT_EQ(err, 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); - 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 invoke response // message to client, client sends out status response with invalid action. -void TestCommandInteraction::TestCommandInvalidMessage3(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandInvalidMessage3) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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; + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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()); + EXPECT_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()); + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + PretendWeGotReplyFromServer(*mpTestContext, privatecommandSender.GetExchangeCtx().Get()); + + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + err = privatecommandSender.OnMessageReceived(privatecommandSender.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); - 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(err, 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(TestCommandInteraction, TestCommandInvalidMessage4) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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; + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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); - - 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()); + 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); - 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()); + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + PretendWeGotReplyFromServer(*mpTestContext, privatecommandSender.GetExchangeCtx().Get()); + + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; - ctx.GetLoopback().mSentMessageCount = 0; - ctx.GetLoopback().mNumMessagesToDrop = 0; - ctx.GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - ctx.GetLoopback().mDroppedMessageCount = 0; + err = privatecommandSender.OnMessageReceived(privatecommandSender.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); - 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(err, 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, TestCommandSenderWithWrongState) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + EXPECT_EQ(err, CHIP_NO_ERROR); + + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); +} + +TEST_F(TestCommandInteraction, TestCommandHandlerWithWrongState) +{ + 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 CommandHandler::InvokeResponseParameters prepareParams(requestCommandPath); + err = commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams); + EXPECT_EQ(err, CHIP_NO_ERROR); + } + EXPECT_TRUE(commandHandler.mMockCommandResponder.mChunks.IsNull()); +} + +TEST_F(TestCommandInteraction, TestCommandSenderWithSendCommand) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + + System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); + + AddInvokeRequestData(&commandSender); + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_NO_ERROR); + + mpTestContext->DrainAndServiceIO(); + + GenerateInvokeResponse(buf, kTestCommandIdWithData); + bool moreChunkedMessages = false; + err = chip::Test::CommandSenderTestAccess(&commandSender).ProcessInvokeResponse(std::move(buf), moreChunkedMessages); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(moreChunkedMessages); +} + +TEST_F(TestCommandInteraction, TestCommandHandlerWithSendEmptyCommand) +{ + 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 CommandHandler::InvokeResponseParameters prepareParams(requestCommandPath); + err = commandHandler.PrepareInvokeResponseCommand(responseCommandPath, prepareParams); + EXPECT_EQ(err, CHIP_NO_ERROR); + err = commandHandler.FinishCommand(); + EXPECT_EQ(err, CHIP_NO_ERROR); + } + EXPECT_FALSE(commandHandler.mMockCommandResponder.mChunks.IsNull()); +} + +TEST_F(TestCommandInteraction, TestCommandSenderWithProcessReceivedMsg) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + + System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); + + GenerateInvokeResponse(buf, kTestCommandIdWithData); + bool moreChunkedMessages = false; + + err = chip::Test::CommandSenderTestAccess(&commandSender).ProcessInvokeResponse(std::move(buf), moreChunkedMessages); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(moreChunkedMessages); +} + +TEST_F(TestCommandInteraction, TestCommandSenderExtendableApiWithProcessReceivedMsg) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + mockCommandSenderExtendedDelegate.ResetCounter(); + PendingResponseTrackerImpl pendingResponseTracker; + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &mpTestContext->GetExchangeManager(), &pendingResponseTracker); + + uint16_t mockCommandRef = 1; + pendingResponseTracker.Add(mockCommandRef); + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + privatecommandSender.SetFinishedCommandCount(1); + + System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); + + GenerateInvokeResponse(buf, kTestCommandIdWithData); + bool moreChunkedMessages = false; + err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(moreChunkedMessages); + + privatecommandSender.FlushNoCommandResponse(); + + EXPECT_EQ(mockCommandSenderExtendedDelegate.onResponseCalledTimes, 1); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onFinalCalledTimes, 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onNoResponseCalledTimes, 0); + EXPECT_EQ(mockCommandSenderExtendedDelegate.onErrorCalledTimes, 0); +} + +TEST_F(TestCommandInteraction, TestCommandSenderExtendableApiWithProcessReceivedMsgContainingInvalidCommandRef) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + mockCommandSenderExtendedDelegate.ResetCounter(); + PendingResponseTrackerImpl pendingResponseTracker; + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, + &mpTestContext->GetExchangeManager(), &pendingResponseTracker); + + uint16_t mockCommandRef = 1; + pendingResponseTracker.Add(mockCommandRef); + chip::Test::CommandSenderTestAccess privatecommandSender(&commandSender); + + privatecommandSender.SetFinishedCommandCount(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; + err = privatecommandSender.ProcessInvokeResponse(std::move(buf), moreChunkedMessages); + EXPECT_EQ(err, CHIP_ERROR_KEY_NOT_FOUND); + EXPECT_FALSE(moreChunkedMessages); + + privatecommandSender.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(); + auto requestCommandPath = ConcreteCommandPath(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; + 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); + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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(); @@ -1282,19 +1249,19 @@ void TestCommandInteraction::TestCommandHandlerCommandEncodeExternalFailure(nlTe CommandHandler::Handle handle(&commandHandler); err = commandHandler.AddResponseData(requestCommandPath, BadFields()); - NL_TEST_ASSERT(apSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, 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(TestCommandInteraction, TestCommandHandlerWithoutResponderCallingAddStatus) { chip::app::ConcreteCommandPath requestCommandPath(kTestEndpointId, kTestClusterId, kTestCommandIdWithData); CommandHandler commandHandler(&mockCommandHandlerDelegate); @@ -1303,25 +1270,24 @@ 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(chip::Test::CommandHandlerTestAccess(&commandHandler).TestOnlyIsInIdleState()); } -void TestCommandInteraction::TestCommandHandlerWithoutResponderCallingAddResponse(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerWithoutResponderCallingAddResponse) { chip::app::ConcreteCommandPath requestCommandPath(kTestEndpointId, kTestClusterId, kTestCommandIdWithData); CommandHandler 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(err, 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(chip::Test::CommandHandlerTestAccess(&commandHandler).TestOnlyIsInIdleState()); } -void TestCommandInteraction::TestCommandHandlerWithoutResponderCallingDirectPrepareFinishCommandApis(nlTestSuite * apSuite, - void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerWithoutResponderCallingDirectPrepareFinishCommandApis) { chip::app::ConcreteCommandPath requestCommandPath(kTestEndpointId, kTestClusterId, kTestCommandIdWithData); CommandHandler commandHandler(&mockCommandHandlerDelegate); @@ -1333,22 +1299,22 @@ void TestCommandInteraction::TestCommandHandlerWithoutResponderCallingDirectPrep const CommandHandler::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(err, 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(err, CHIP_ERROR_INCORRECT_STATE); - NL_TEST_ASSERT(apSuite, commandHandler.TestOnlyIsInIdleState()); + EXPECT_TRUE(chip::Test::CommandHandlerTestAccess(&commandHandler).TestOnlyIsInIdleState()); } -void TestCommandInteraction::TestCommandHandlerWithOnInvokeReceivedNotExistCommand(nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandlerWithOnInvokeReceivedNotExistCommand) { 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 */); CommandHandler commandHandler(&mockCommandHandlerDelegate); chip::isCommandDispatched = false; @@ -1356,13 +1322,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, TestCommandHandlerWithOnInvokeReceivedEmptyDataMsg) { bool allBooleans[] = { true, false }; for (auto messageIsTimed : allBooleans) @@ -1374,78 +1340,73 @@ 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; + 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); + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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, TestCommandSenderExtendableCallbackUnsupportedCommand) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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); + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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; + 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); @@ -1454,78 +1415,75 @@ 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(err, 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(err, 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = commandSender.FinishCommand(finishCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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(err, 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, TestCommandSenderExtendableCallbackBuildingBatchDuplicateCommandRefFails) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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(err, 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(err, 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = commandSender.FinishCommand(finishCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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(err, 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, TestCommandSenderExtendableCallbackBuildingBatchCommandSuccess) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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(err, 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. @@ -1535,140 +1493,133 @@ void TestCommandInteraction::TestCommandSenderExtendableCallbackBuildingBatchCom finishCommandParams.SetEndDataStruct(true).SetCommandRef(firstCommandRef); auto commandPathParams = MakeTestCommandPath(); err = commandSender.PrepareCommand(commandPathParams, prepareCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = commandSender.FinishCommand(finishCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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(err, CHIP_NO_ERROR); writer = commandSender.GetCommandDataIBTLVWriter(); err = writer->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = commandSender.FinishCommand(finishCommandParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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; + CHIP_ERROR err = CHIP_NO_ERROR; mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &ctx.GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + + AddInvokeRequestData(&commandSender); + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); - AddInvokeRequestData(apSuite, apContext, &commandSender); - err = commandSender.SendCommandRequest(ctx.GetSessionBobToAlice()); + EXPECT_EQ(err, 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; + 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); + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); - ctx.DrainAndServiceIO(); + EXPECT_EQ(err, 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; + 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); + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); - ctx.DrainAndServiceIO(); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(apSuite, - mockCommandSenderDelegate.onResponseCalledTimes == 1 && mockCommandSenderDelegate.onFinalCalledTimes == 1 && - mockCommandSenderDelegate.onErrorCalledTimes == 0); + mpTestContext->DrainAndServiceIO(); - 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; + 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()); + AddInvokeRequestData(&commandSender, kTestNonExistCommandId); + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); - ctx.DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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; + CHIP_ERROR err = CHIP_NO_ERROR; // // Don't send back a response, just keep the CommandHandler @@ -1679,47 +1630,46 @@ 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); + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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, TestCommandHandlerRejectMultipleIdenticalCommands) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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); @@ -1729,49 +1679,45 @@ 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()); + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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(TestCommandInteraction, TestCommandHandlerRejectsMultipleCommandsWithIdenticalCommandRef) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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; { @@ -1787,16 +1733,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)); } } @@ -1807,36 +1752,35 @@ 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); + err = chip::Test::CommandSenderTestAccess(&commandSender).Finalize(commandDatabuf); + EXPECT_EQ(err, CHIP_NO_ERROR); mockCommandHandlerDelegate.ResetCounter(); commandDispatchedCount = 0; - InteractionModel::Status status = commandHandler.ProcessInvokeRequest(std::move(commandDatabuf), false); - NL_TEST_ASSERT(apSuite, status == InteractionModel::Status::InvalidAction); + InteractionModel::Status status = + chip::Test::CommandHandlerTestAccess(&commandHandler).ProcessInvokeRequest(std::move(commandDatabuf), false); + 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(TestCommandInteraction, TestCommandHandlerRejectMultipleCommandsWhenHandlerOnlySupportsOne) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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; { @@ -1850,20 +1794,19 @@ 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); + err = chip::Test::CommandSenderTestAccess(&commandSender).Finalize(commandDatabuf); + EXPECT_EQ(err, CHIP_NO_ERROR); mockCommandHandlerDelegate.ResetCounter(); sendResponse = true; @@ -1872,27 +1815,26 @@ void TestCommandInteraction::TestCommandHandlerRejectMultipleCommandsWhenHandler CommandHandler 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(TestCommandInteraction, TestCommandHandlerAcceptMultipleCommands) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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; { @@ -1906,16 +1848,15 @@ 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); + // changing the state of commandSender to State::AddedCommand + chip::Test::CommandSenderTestAccess(&commandSender).MoveToStateAddedCommand(); } BasicCommandPathRegistry<4> basicCommandPathRegistry; @@ -1925,104 +1866,107 @@ 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); + err = chip::Test::CommandSenderTestAccess(&commandSender).Finalize(commandDatabuf); + EXPECT_EQ(err, 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); + InteractionModel::Status status = + chip::Test::CommandHandlerTestAccess(&commandHandler).ProcessInvokeRequest(std::move(commandDatabuf), false); + 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(TestCommandInteraction, TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsStatusResponse) { BasicCommandPathRegistry<4> basicCommandPathRegistry; MockCommandResponder mockCommandResponder; CommandHandler::TestOnlyOverrides testOnlyOverrides{ &basicCommandPathRegistry, &mockCommandResponder }; CommandHandler commandHandler(testOnlyOverrides, &mockCommandHandlerDelegate); - commandHandler.mReserveSpaceForMoreChunkMessages = true; - ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; - ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; + chip::Test::CommandHandlerTestAccess(&commandHandler).SetReserveSpaceForMoreChunkMessages(true); + 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t sizeToLeave = 0; - FillCurrentInvokeResponseBuffer(apSuite, &commandHandler, requestCommandPath1, sizeToLeave); - uint32_t remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize == sizeToLeave); + FillCurrentInvokeResponseBuffer(&commandHandler, requestCommandPath1, sizeToLeave); + uint32_t remainingSize = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + 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); + remainingSize = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + EXPECT_GT(remainingSize, sizeToLeave); } - -void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponsePrimative( - nlTestSuite * apSuite, void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponsePrimative) { BasicCommandPathRegistry<4> basicCommandPathRegistry; MockCommandResponder mockCommandResponder; CommandHandler::TestOnlyOverrides testOnlyOverrides{ &basicCommandPathRegistry, &mockCommandResponder }; CommandHandler commandHandler(testOnlyOverrides, &mockCommandHandlerDelegate); - commandHandler.mReserveSpaceForMoreChunkMessages = true; - ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; - ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; + chip::Test::CommandHandlerTestAccess(&commandHandler).SetReserveSpaceForMoreChunkMessages(true); + 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t sizeToLeave = 0; - FillCurrentInvokeResponseBuffer(apSuite, &commandHandler, requestCommandPath1, sizeToLeave); - uint32_t remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize == sizeToLeave); + FillCurrentInvokeResponseBuffer(&commandHandler, requestCommandPath1, sizeToLeave); + uint32_t remainingSize = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + 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); + remainingSize = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + EXPECT_GT(remainingSize, sizeToLeave); } -void TestCommandInteraction::TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponse(nlTestSuite * apSuite, - void * apContext) +TEST_F(TestCommandInteraction, TestCommandHandler_FillUpInvokeResponseMessageWhereSecondResponseIsDataResponse) { BasicCommandPathRegistry<4> basicCommandPathRegistry; MockCommandResponder mockCommandResponder; CommandHandler::TestOnlyOverrides testOnlyOverrides{ &basicCommandPathRegistry, &mockCommandResponder }; CommandHandler commandHandler(testOnlyOverrides, &mockCommandHandlerDelegate); - commandHandler.mReserveSpaceForMoreChunkMessages = true; - ConcreteCommandPath requestCommandPath1 = { kTestEndpointId, kTestClusterId, kTestCommandIdFillResponseMessage }; - ConcreteCommandPath requestCommandPath2 = { kTestEndpointId, kTestClusterId, kTestCommandIdCommandSpecificResponse }; + chip::Test::CommandHandlerTestAccess(&commandHandler).SetReserveSpaceForMoreChunkMessages(true); + 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); + EXPECT_EQ(err, CHIP_NO_ERROR); err = basicCommandPathRegistry.Add(requestCommandPath2, std::make_optional(static_cast(2))); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint32_t sizeToLeave = 0; - FillCurrentInvokeResponseBuffer(apSuite, &commandHandler, requestCommandPath1, sizeToLeave); - uint32_t remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize == sizeToLeave); + FillCurrentInvokeResponseBuffer(&commandHandler, requestCommandPath1, sizeToLeave); + uint32_t remainingSize = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + EXPECT_EQ(remainingSize, sizeToLeave); uint32_t sizeToFill = 50; err = commandHandler.AddResponseData(requestCommandPath2, ForcedSizeBuffer(sizeToFill)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - remainingSize = commandHandler.mInvokeResponseBuilder.GetWriter()->GetRemainingFreeLength(); - NL_TEST_ASSERT(apSuite, remainingSize > sizeToLeave); + remainingSize = + chip::Test::CommandHandlerTestAccess(&commandHandler).GetInvokeResponseBuilder().GetWriter()->GetRemainingFreeLength(); + EXPECT_GT(remainingSize, sizeToLeave); } #if CONFIG_BUILD_FOR_HOST_UNIT_TEST @@ -2030,29 +1974,32 @@ 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(TestCommandInteraction, TestCommandHandlerReleaseWithExchangeClosed) { - TestContext & ctx = *static_cast(apContext); - CHIP_ERROR err = CHIP_NO_ERROR; + 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()); + err = commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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. - asyncCommandHandle.Get()->mpResponder->GetExchangeContext()->GetSessionHolder().Release(); - asyncCommandHandle.Get()->mpResponder->GetExchangeContext()->OnSessionReleased(); + chip::Test::CommandHandlerTestAccess(asyncCommandHandle.Get()) + .GetmpResponder() + ->GetExchangeContext() + ->GetSessionHolder() + .Release(); + chip::Test::CommandHandlerTestAccess(asyncCommandHandle.Get()).GetmpResponder()->GetExchangeContext()->OnSessionReleased(); asyncCommandHandle = nullptr; } @@ -2060,79 +2007,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/TestWriteInteraction.cpp b/src/app/tests/TestWriteInteraction.cpp index 2caae1b1f59827..5f40c1bb66929f 100644 --- a/src/app/tests/TestWriteInteraction.cpp +++ b/src/app/tests/TestWriteInteraction.cpp @@ -16,15 +16,18 @@ * limitations under the License. */ -#include #include -#include #include +#include + #include #include #include #include +#include +#include +#include #include #include #include @@ -34,10 +37,9 @@ #include #include #include -#include -#include #include #include +#include namespace { @@ -52,67 +54,69 @@ 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(); + if (mpTestContext != nullptr) + { + delete mpTestContext; + } + } void SetUp() override { - chip::Test::AppContext::SetUp(); + if (mpTestContext != nullptr) + { + 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(); + } + if (mpTestContext != nullptr) + { + 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); + 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, @@ -149,7 +153,7 @@ 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; @@ -159,20 +163,19 @@ void TestWriteInteraction::AddAttributeDataIB(nlTestSuite * apSuite, void * apCo attributePathParams.mAttributeId = 4; err = aWriteClient.EncodeAttribute(attributePathParams, attributeValue); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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(err, 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; @@ -180,53 +183,53 @@ void TestWriteInteraction::GenerateWriteRequest(nlTestSuite * apSuite, void * ap WriteRequestMessage::Builder writeRequestBuilder; err = writeRequestBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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); + EXPECT_EQ(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(err, 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(err, CHIP_NO_ERROR); err = pWriter->PutBoolean(chip::TLV::ContextTag(1), true); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = pWriter->EndContainer(dummyType); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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(err, 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; @@ -234,101 +237,99 @@ void TestWriteInteraction::GenerateWriteResponse(nlTestSuite * apSuite, void * a WriteResponseMessage::Builder writeResponseBuilder; err = writeResponseBuilder.Init(&writer); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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); + EXPECT_EQ(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(err, 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(err, 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(err, CHIP_NO_ERROR); } -void TestWriteInteraction::TestWriteClient(nlTestSuite * apSuite, void * apContext) +TEST_F(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(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_NO_ERROR); - err = writeClient.SendWriteRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); - ctx.DrainAndServiceIO(); + GenerateWriteResponse(buf); - GenerateWriteResponse(apSuite, apContext, buf); + chip::Test::WriteClientTestAccess privatewriteClient(&writeClient); - err = writeClient.ProcessWriteResponseMessage(std::move(buf)); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + err = privatewriteClient.ProcessWriteResponseMessage(std::move(buf)); + EXPECT_EQ(err, CHIP_NO_ERROR); - writeClient.Close(); + privatewriteClient.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(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); + AddAttributeDataIB(writeClient); - SessionHandle groupSession = ctx.GetSessionBobToFriends(); - NL_TEST_ASSERT(apSuite, groupSession->IsGroupSession()); + SessionHandle groupSession = mpTestContext->GetSessionBobToFriends(); + EXPECT_TRUE(groupSession->IsGroupSession()); err = writeClient.SendWriteRequest(groupSession); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - - ctx.DrainAndServiceIO(); + EXPECT_EQ(err, CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); + chip::Test::WriteClientTestAccess privatewriteClient(&writeClient); // The WriteClient should be shutdown once we SendWriteRequest for group. - NL_TEST_ASSERT(apSuite, writeClient.mState == WriteClient::State::AwaitingDestruction); + EXPECT_EQ(privatewriteClient.GetState(), privatewriteClient.GetEnumStateAwaitingDestruction()); } -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) { @@ -341,43 +342,43 @@ void TestWriteInteraction::TestWriteHandler(nlTestSuite * apSuite, void * apCont System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); err = writeHandler.Init(chip::app::InteractionModelEngine::GetInstance()); - GenerateWriteRequest(apSuite, apContext, messageIsTimed, buf); + 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); + err = engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -399,53 +400,55 @@ void TestWriteInteraction::TestWriteRoundtripWithClusterObjects(nlTestSuite * ap dataTx.e = chip::Span(charSpanData, strlen(charSpanData)); writeClient.EncodeAttribute(attributePathParams, dataTx); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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); + err = writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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); + err = engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -461,40 +464,41 @@ void TestWriteInteraction::TestWriteRoundtripWithClusterObjectsVersionMatch(nlTe Optional version(kAcceptedDataVersion); writeClient.EncodeAttribute(attributePathParams, dataTx, version); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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); + err = writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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); + err = engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -512,58 +516,62 @@ void TestWriteInteraction::TestWriteRoundtripWithClusterObjectsVersionMismatch(n dataTx.SetNonNull(dataTxValue); Optional version(chip::Test::kRejectedDataVersion); writeClient.EncodeAttribute(attributePathParams, dataTx, version); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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); + err = writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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); + err = engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, 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); - err = writeClient.SendWriteRequest(ctx.GetSessionBobToAlice()); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + err = writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - - 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(); } @@ -571,121 +579,123 @@ 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(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); + err = engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, 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(err, 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; + err = writeClient.SendWriteRequest(sessionHandle); + EXPECT_EQ(err, 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; - writeHandler->OnMessageReceived(writeHandler->mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)); - ctx.DrainAndServiceIO(); - - NL_TEST_ASSERT(apSuite, writeCallback.mLastErrorReason.mStatus == Protocols::InteractionModel::Status::InvalidAction); - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers() == 0); + chip::Test::WriteHandlerTestAccess privatewriteHandler(writeHandler); + + rm->ClearRetransTable(chip::Test::WriteClientTestAccess(&writeClient).GetExchangeCtx().Get()); + rm->ClearRetransTable(privatewriteHandler.GetExchangeCtx().Get()); + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + privatewriteHandler.OnMessageReceived(privatewriteHandler.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); + mpTestContext->DrainAndServiceIO(); + + 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); + err = engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, 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); - - 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(); - - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers() == 1); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mSentMessageCount == 3); - NL_TEST_ASSERT(apSuite, ctx.GetLoopback().mDroppedMessageCount == 1); - - ctx.GetFabricTable().Delete(ctx.GetAliceFabricIndex()); - NL_TEST_ASSERT(apSuite, InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers() == 0); + EXPECT_EQ(err, CHIP_NO_ERROR); + + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 1; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 2; + err = writeClient.SendWriteRequest(sessionHandle); + EXPECT_EQ(err, CHIP_NO_ERROR); + mpTestContext->DrainAndServiceIO(); + + EXPECT_EQ(InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 1u); + EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 3u); + EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + + 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 @@ -709,350 +719,331 @@ void TestWriteInteraction::TestWriteHandlerInvalidateFabric(nlTestSuite * apSuit * * This is a macro so we get useful line numbers on assertion failures */ -#define PretendWeGotReplyFromServer(aSuite, aContext, aClientExchange) \ +#define PretendWeGotReplyFromServer(aContext, aClientExchange) \ { \ Messaging::ReliableMessageMgr * localRm = (aContext).GetExchangeManager().GetReliableMessageMgr(); \ Messaging::ExchangeContext * localExchange = aClientExchange; \ - NL_TEST_ASSERT(aSuite, localRm->TestGetCountRetransTable() == 2); \ + EXPECT_EQ(localRm->TestGetCountRetransTable(), 2); \ \ localRm->ClearRetransTable(localExchange); \ - NL_TEST_ASSERT(aSuite, localRm->TestGetCountRetransTable() == 1); \ + EXPECT_EQ(localRm->TestGetCountRetransTable(), 1); \ \ localRm->EnumerateRetransTable([localExchange](auto * entry) { \ - localExchange->SetPendingPeerAckMessageCounter(entry->retainedBuf.GetMessageCounter()); \ + chip::Test::ReliableMessageContextTestAccess(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(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); + err = engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, 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; + err = writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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); + chip::Test::WriteClientTestAccess privatewriteClient(&writeClient); // 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, privatewriteClient.GetExchangeCtx().Get()); + + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + err = privatewriteClient.OnMessageReceived(privatewriteClient.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); + EXPECT_EQ(err, 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(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); + err = engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, 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; + err = writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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); + chip::Test::WriteClientTestAccess privatewriteClient(&writeClient); + // 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, privatewriteClient.GetExchangeCtx().Get()); + + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + err = privatewriteClient.OnMessageReceived(privatewriteClient.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); + EXPECT_EQ(err, 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(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); + err = engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, 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; + err = writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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); + chip::Test::WriteClientTestAccess privatewriteClient(&writeClient); + // 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, privatewriteClient.GetExchangeCtx().Get()); + + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + err = privatewriteClient.OnMessageReceived(privatewriteClient.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); + EXPECT_EQ(err, 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(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); + err = engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, 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; + err = writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()); + EXPECT_EQ(err, 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); + chip::Test::WriteClientTestAccess privatewriteClient(&writeClient); // 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, privatewriteClient.GetExchangeCtx().Get()); + + mpTestContext->GetLoopback().mSentMessageCount = 0; + mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + mpTestContext->GetLoopback().mDroppedMessageCount = 0; + err = privatewriteClient.OnMessageReceived(privatewriteClient.GetExchangeCtx().Get(), payloadHeader, std::move(msgBuf)); + EXPECT_EQ(err, 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/WriteClientTestAccess.h b/src/app/tests/WriteClientTestAccess.h new file mode 100644 index 00000000000000..5834468b9a1ca5 --- /dev/null +++ b/src/app/tests/WriteClientTestAccess.h @@ -0,0 +1,59 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +namespace chip { +namespace Test { + +/** + * @brief Class acts as an accessor to private methods of the WriteClient class without needing to give friend access to + * each individual test. + * This is not a Global API and should only be used for (Unit) Testing. + */ +class WriteClientTestAccess +{ + +public: + WriteClientTestAccess(app::WriteClient * aWriteClient) : mpWriteClient(aWriteClient) {} + + CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader, + System::PacketBufferHandle && aPayload) + { + return mpWriteClient->OnMessageReceived(apExchangeContext, aPayloadHeader, std::move(aPayload)); + } + + Messaging::ExchangeHolder & GetExchangeCtx() { return mpWriteClient->mExchangeCtx; } + + app::WriteClient::State GetState() { return mpWriteClient->mState; } + app::WriteClient::State GetEnumStateAwaitingDestruction() { return app::WriteClient::State::AwaitingDestruction; } + + void Close() { mpWriteClient->Close(); } + + CHIP_ERROR ProcessWriteResponseMessage(System::PacketBufferHandle && payload) + { + return mpWriteClient->ProcessWriteResponseMessage(std::move(payload)); + } + +private: + app::WriteClient * mpWriteClient = nullptr; +}; + +} // namespace Test +} // namespace chip diff --git a/src/app/tests/WriteHandlerTestAccess.h b/src/app/tests/WriteHandlerTestAccess.h new file mode 100644 index 00000000000000..520bb261504a7e --- /dev/null +++ b/src/app/tests/WriteHandlerTestAccess.h @@ -0,0 +1,49 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +namespace chip { +namespace Test { + +/** + * @brief Class acts as an accessor to private methods of the WriteHandler class without needing to give friend access to + * each individual test. + * This is not a Global API and should only be used for (Unit) Testing. + */ +class WriteHandlerTestAccess +{ + +public: + WriteHandlerTestAccess(app::WriteHandler * aWriteHandler) : mpWriteHandler(aWriteHandler) {} + + CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader, + System::PacketBufferHandle && aPayload) + { + return mpWriteHandler->OnMessageReceived(apExchangeContext, aPayloadHeader, std::move(aPayload)); + } + + Messaging::ExchangeHolder & GetExchangeCtx() { return mpWriteHandler->mExchangeCtx; } + +private: + app::WriteHandler * mpWriteHandler = nullptr; +}; + +} // namespace Test +} // namespace chip From 37cf3660d823d26ce6bd88c20b98e67ff1f414b7 Mon Sep 17 00:00:00 2001 From: AYA Date: Mon, 20 May 2024 17:51:24 +0200 Subject: [PATCH 13/22] build.gn fix --- src/app/WriteClient.h | 7 ++++--- src/app/tests/BUILD.gn | 3 ++- src/app/tests/TestCommandInteraction.cpp | 3 ++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/app/WriteClient.h b/src/app/WriteClient.h index 354c6488f3b27d..b033821c5db2cd 100644 --- a/src/app/WriteClient.h +++ b/src/app/WriteClient.h @@ -129,7 +129,8 @@ class WriteClient : public Messaging::ExchangeDelegate */ WriteClient(Messaging::ExchangeManager * apExchangeMgr, Callback * apCallback, const Optional & aTimedWriteTimeoutMs, bool aSuppressResponse = false) : - mpExchangeMgr(apExchangeMgr), mExchangeCtx(*this), mpCallback(apCallback), mTimedWriteTimeoutMs(aTimedWriteTimeoutMs), + mpExchangeMgr(apExchangeMgr), + mExchangeCtx(*this), mpCallback(apCallback), mTimedWriteTimeoutMs(aTimedWriteTimeoutMs), mSuppressResponse(aSuppressResponse) { assertChipStackLockedByCurrentThread(); @@ -138,8 +139,8 @@ class WriteClient : public Messaging::ExchangeDelegate #if CONFIG_BUILD_FOR_HOST_UNIT_TEST WriteClient(Messaging::ExchangeManager * apExchangeMgr, Callback * apCallback, const Optional & aTimedWriteTimeoutMs, uint16_t aReservedSize) : - mpExchangeMgr(apExchangeMgr), mExchangeCtx(*this), mpCallback(apCallback), mTimedWriteTimeoutMs(aTimedWriteTimeoutMs), - mReservedSize(aReservedSize) + mpExchangeMgr(apExchangeMgr), + mExchangeCtx(*this), mpCallback(apCallback), mTimedWriteTimeoutMs(aTimedWriteTimeoutMs), mReservedSize(aReservedSize) { assertChipStackLockedByCurrentThread(); } diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index cff63a1b5cdf90..4b4f9af51ae0d7 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -138,11 +138,12 @@ chip_test_suite("tests") { output_name = "libAppTests" sources = [ - "${chip_root}/src/messaging/tests/ReliableMessageContextTestAccess.h", "CommandHandlerTestAccess.h", "CommandSenderTestAccess.h", "EngineTestAccess.h", "ReadHandlerTestAccess.h", + "WriteClientTestAccess.h", + "WriteHandlerTestAccess.h", ] test_sources = [ "TestAclAttribute.cpp", diff --git a/src/app/tests/TestCommandInteraction.cpp b/src/app/tests/TestCommandInteraction.cpp index 96284d19cc7dc5..35e53462a79b5c 100644 --- a/src/app/tests/TestCommandInteraction.cpp +++ b/src/app/tests/TestCommandInteraction.cpp @@ -428,7 +428,8 @@ class TestCommandInteraction : public ::testing::Test { public: CommandHandlerWithUnrespondedCommand(CommandHandler::Callback * apCallback, const ConcreteCommandPath & aRequestCommandPath, - const Optional & aRef) : CommandHandler(apCallback) + const Optional & aRef) : + CommandHandler(apCallback) { GetCommandPathRegistry().Add(aRequestCommandPath, aRef.std_optional()); SetExchangeInterface(&mMockCommandResponder); From 41a4bb81dbd6d7febf7eff11d2b86ec68efe3c51 Mon Sep 17 00:00:00 2001 From: AYA Date: Mon, 20 May 2024 18:14:19 +0200 Subject: [PATCH 14/22] build.gn fix v2 --- src/app/tests/BUILD.gn | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index 4b4f9af51ae0d7..da5587cf0dbd10 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -38,9 +38,10 @@ static_library("helpers") { "${chip_root}/src/access", "${chip_root}/src/app", "${chip_root}/src/lib/support", - "${chip_root}/src/messaging/tests:helpers", "${chip_root}/src/transport/raw/tests:helpers", ] + + public_deps = [ "${chip_root}/src/messaging/tests:helpers" ] } source_set("binding-test-srcs") { From 64020eb8c283d5882627ba7a74c641526189153f Mon Sep 17 00:00:00 2001 From: AYA Date: Tue, 21 May 2024 09:09:22 +0200 Subject: [PATCH 15/22] removing TestACLAttribute --- src/app/tests/BUILD.gn | 2 +- src/app/tests/TestAclAttribute.cpp | 169 +++++++++++++++-------------- 2 files changed, 86 insertions(+), 85 deletions(-) diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index da5587cf0dbd10..ed40da3c45bc1f 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -147,7 +147,6 @@ chip_test_suite("tests") { "WriteHandlerTestAccess.h", ] test_sources = [ - "TestAclAttribute.cpp", "TestBuilderParser.cpp", "TestCommandInteraction.cpp", "TestMessageDef.cpp", @@ -182,6 +181,7 @@ chip_test_suite_using_nltest("tests_nltest") { output_name = "libAppTestsNL" test_sources = [ + "TestAclAttribute.cpp", "TestAclEvent.cpp", "TestAttributeAccessInterfaceCache.cpp", "TestAttributePathExpandIterator.cpp", diff --git a/src/app/tests/TestAclAttribute.cpp b/src/app/tests/TestAclAttribute.cpp index d143bffef9792a..5e3a5bfdd9afa3 100644 --- a/src/app/tests/TestAclAttribute.cpp +++ b/src/app/tests/TestAclAttribute.cpp @@ -16,8 +16,6 @@ * limitations under the License. */ -#include - #include #include #include @@ -26,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -36,8 +33,11 @@ #include #include #include +#include +#include #include #include +#include #include #include @@ -46,10 +46,10 @@ namespace { using namespace chip; using namespace chip::Access; -// chip::ClusterId kTestClusterId = 1; -// chip::ClusterId kTestDeniedClusterId1 = 1000; -// chip::ClusterId kTestDeniedClusterId2 = 3; -// chip::EndpointId kTestEndpointId = 4; +chip::ClusterId kTestClusterId = 1; +chip::ClusterId kTestDeniedClusterId1 = 1000; +chip::ClusterId kTestDeniedClusterId2 = 3; +chip::EndpointId kTestEndpointId = 4; class TestAccessControlDelegate : public AccessControl::Delegate { @@ -57,7 +57,7 @@ class TestAccessControlDelegate : public AccessControl::Delegate CHIP_ERROR Check(const SubjectDescriptor & subjectDescriptor, const chip::Access::RequestPath & requestPath, Privilege requestPrivilege) override { - if (requestPath.cluster == chip::Test::kTestDeniedClusterId2) + if (requestPath.cluster == kTestDeniedClusterId2) { return CHIP_ERROR_ACCESS_DENIED; } @@ -77,6 +77,18 @@ 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: @@ -113,147 +125,136 @@ class MockInteractionModelApp : public chip::app::ReadClient::Callback namespace chip { namespace app { -class TestAclAttribute : public ::testing::Test +class TestAclAttribute { public: - static void SetUpTestSuite() - { - - pTestContext = new chip::Test::AppContext; - - pTestContext->SetUpTestSuite(); - } - static void TearDownTestSuite() - { - pTestContext->TearDownTestSuite(); - if (pTestContext != nullptr) - { - delete pTestContext; - } - } - - void SetUp() override - { - - if (pTestContext != nullptr) - { - pTestContext->SetUp(); - - Access::GetAccessControl().Finish(); - Access::GetAccessControl().Init(GetTestAccessControlDelegate(), gDeviceTypeResolver); - } - } - void TearDown() override - { - if (pTestContext != nullptr) - { - pTestContext->TearDown(); - } - } - static chip::Test::AppContext * pTestContext; + static void TestACLDeniedAttribute(nlTestSuite * apSuite, void * apContext); }; -chip::Test::AppContext * TestAclAttribute::pTestContext = 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. -TEST_F(TestAclAttribute, TestACLDeniedAttribute) +void TestAclAttribute::TestACLDeniedAttribute(nlTestSuite * apSuite, void * apContext) { - CHIP_ERROR err = CHIP_NO_ERROR; + TestAccessContext & ctx = *static_cast(apContext); + CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = pTestContext->GetExchangeManager().GetReliableMessageMgr(); - EXPECT_EQ(rm->TestGetCountRetransTable(), 0); + Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&pTestContext->GetExchangeManager(), &pTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()); - EXPECT_EQ(err, CHIP_NO_ERROR); + err = engine->Init(&ctx.GetExchangeManager(), &ctx.GetFabricTable(), app::reporting::GetDefaultReportScheduler()); + NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &pTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; - attributePathParams[0].mEndpointId = chip::Test::kTestEndpointId; - attributePathParams[0].mClusterId = chip::Test::kTestDeniedClusterId1; + attributePathParams[0].mEndpointId = kTestEndpointId; + attributePathParams[0].mClusterId = kTestDeniedClusterId1; attributePathParams[0].mAttributeId = 1; - attributePathParams[1].mEndpointId = chip::Test::kTestEndpointId; - attributePathParams[1].mClusterId = chip::Test::kTestDeniedClusterId1; + attributePathParams[1].mEndpointId = kTestEndpointId; + attributePathParams[1].mClusterId = kTestDeniedClusterId1; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); - EXPECT_EQ(err, CHIP_NO_ERROR); + NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - pTestContext->DrainAndServiceIO(); - EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); - EXPECT_FALSE(delegate.mGotReport); + ctx.DrainAndServiceIO(); + NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(InvalidAction)); + NL_TEST_ASSERT(apSuite, !delegate.mGotReport); delegate.mError = CHIP_NO_ERROR; delegate.mGotReport = false; } { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &pTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; - attributePathParams[0].mClusterId = chip::Test::kTestDeniedClusterId2; + attributePathParams[0].mClusterId = kTestDeniedClusterId2; attributePathParams[0].mAttributeId = 1; - attributePathParams[1].mClusterId = chip::Test::kTestDeniedClusterId2; + attributePathParams[1].mClusterId = kTestDeniedClusterId2; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); - EXPECT_EQ(err, CHIP_NO_ERROR); + NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - pTestContext->DrainAndServiceIO(); - EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); - EXPECT_FALSE(delegate.mGotReport); + ctx.DrainAndServiceIO(); + NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(InvalidAction)); + NL_TEST_ASSERT(apSuite, !delegate.mGotReport); delegate.mError = CHIP_NO_ERROR; delegate.mGotReport = false; } { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &pTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; - attributePathParams[0].mEndpointId = chip::Test::kTestEndpointId; - attributePathParams[0].mClusterId = chip::Test::kTestDeniedClusterId1; + attributePathParams[0].mEndpointId = kTestEndpointId; + attributePathParams[0].mClusterId = kTestDeniedClusterId1; attributePathParams[0].mAttributeId = 1; - attributePathParams[1].mEndpointId = chip::Test::kTestEndpointId; - attributePathParams[1].mClusterId = chip::Test::kTestClusterId; + attributePathParams[1].mEndpointId = kTestEndpointId; + attributePathParams[1].mClusterId = kTestClusterId; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); - EXPECT_EQ(err, CHIP_NO_ERROR); + NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); - pTestContext->DrainAndServiceIO(); - EXPECT_EQ(delegate.mError, CHIP_NO_ERROR); - EXPECT_TRUE(delegate.mGotReport); - EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); + 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); delegate.mError = CHIP_NO_ERROR; delegate.mGotReport = false; } - EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); + NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); engine->Shutdown(); - EXPECT_EQ(pTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); } } // 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) From eb01e7ad6723209c1718d540e2f31122cf069353 Mon Sep 17 00:00:00 2001 From: AYA Date: Thu, 23 May 2024 10:55:14 +0200 Subject: [PATCH 16/22] Revert "removing TestACLAttribute" This reverts commit 64020eb8c283d5882627ba7a74c641526189153f. --- src/app/tests/BUILD.gn | 2 +- src/app/tests/TestAclAttribute.cpp | 169 ++++++++++++++--------------- 2 files changed, 85 insertions(+), 86 deletions(-) diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index ed40da3c45bc1f..da5587cf0dbd10 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -147,6 +147,7 @@ chip_test_suite("tests") { "WriteHandlerTestAccess.h", ] test_sources = [ + "TestAclAttribute.cpp", "TestBuilderParser.cpp", "TestCommandInteraction.cpp", "TestMessageDef.cpp", @@ -181,7 +182,6 @@ chip_test_suite_using_nltest("tests_nltest") { output_name = "libAppTestsNL" test_sources = [ - "TestAclAttribute.cpp", "TestAclEvent.cpp", "TestAttributeAccessInterfaceCache.cpp", "TestAttributePathExpandIterator.cpp", diff --git a/src/app/tests/TestAclAttribute.cpp b/src/app/tests/TestAclAttribute.cpp index 5e3a5bfdd9afa3..d143bffef9792a 100644 --- a/src/app/tests/TestAclAttribute.cpp +++ b/src/app/tests/TestAclAttribute.cpp @@ -16,6 +16,8 @@ * limitations under the License. */ +#include + #include #include #include @@ -24,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -33,11 +36,8 @@ #include #include #include -#include -#include #include #include -#include #include #include @@ -46,10 +46,10 @@ namespace { using namespace chip; using namespace chip::Access; -chip::ClusterId kTestClusterId = 1; -chip::ClusterId kTestDeniedClusterId1 = 1000; -chip::ClusterId kTestDeniedClusterId2 = 3; -chip::EndpointId kTestEndpointId = 4; +// chip::ClusterId kTestClusterId = 1; +// chip::ClusterId kTestDeniedClusterId1 = 1000; +// chip::ClusterId kTestDeniedClusterId2 = 3; +// chip::EndpointId kTestEndpointId = 4; class TestAccessControlDelegate : public AccessControl::Delegate { @@ -57,7 +57,7 @@ class TestAccessControlDelegate : public AccessControl::Delegate CHIP_ERROR Check(const SubjectDescriptor & subjectDescriptor, const chip::Access::RequestPath & requestPath, Privilege requestPrivilege) override { - if (requestPath.cluster == kTestDeniedClusterId2) + if (requestPath.cluster == chip::Test::kTestDeniedClusterId2) { return CHIP_ERROR_ACCESS_DENIED; } @@ -77,18 +77,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: @@ -125,136 +113,147 @@ 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() + { + + pTestContext = new chip::Test::AppContext; + + pTestContext->SetUpTestSuite(); + } + static void TearDownTestSuite() + { + pTestContext->TearDownTestSuite(); + if (pTestContext != nullptr) + { + delete pTestContext; + } + } + + void SetUp() override + { + + if (pTestContext != nullptr) + { + pTestContext->SetUp(); + + Access::GetAccessControl().Finish(); + Access::GetAccessControl().Init(GetTestAccessControlDelegate(), gDeviceTypeResolver); + } + } + void TearDown() override + { + if (pTestContext != nullptr) + { + pTestContext->TearDown(); + } + } + static chip::Test::AppContext * pTestContext; }; +chip::Test::AppContext * TestAclAttribute::pTestContext = 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; + CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); - NL_TEST_ASSERT(apSuite, rm->TestGetCountRetransTable() == 0); + Messaging::ReliableMessageMgr * rm = pTestContext->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); + err = engine->Init(&pTestContext->GetExchangeManager(), &pTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, CHIP_NO_ERROR); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &pTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; - attributePathParams[0].mEndpointId = kTestEndpointId; - attributePathParams[0].mClusterId = kTestDeniedClusterId1; + attributePathParams[0].mEndpointId = chip::Test::kTestEndpointId; + attributePathParams[0].mClusterId = chip::Test::kTestDeniedClusterId1; attributePathParams[0].mAttributeId = 1; - attributePathParams[1].mEndpointId = kTestEndpointId; - attributePathParams[1].mClusterId = kTestDeniedClusterId1; + attributePathParams[1].mEndpointId = chip::Test::kTestEndpointId; + attributePathParams[1].mClusterId = chip::Test::kTestDeniedClusterId1; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(InvalidAction)); - NL_TEST_ASSERT(apSuite, !delegate.mGotReport); + pTestContext->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(), &pTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; - attributePathParams[0].mClusterId = kTestDeniedClusterId2; + attributePathParams[0].mClusterId = chip::Test::kTestDeniedClusterId2; attributePathParams[0].mAttributeId = 1; - attributePathParams[1].mClusterId = kTestDeniedClusterId2; + attributePathParams[1].mClusterId = chip::Test::kTestDeniedClusterId2; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(apSuite, delegate.mError == CHIP_IM_GLOBAL_STATUS(InvalidAction)); - NL_TEST_ASSERT(apSuite, !delegate.mGotReport); + pTestContext->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(), &pTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; - attributePathParams[0].mEndpointId = kTestEndpointId; - attributePathParams[0].mClusterId = kTestDeniedClusterId1; + attributePathParams[0].mEndpointId = chip::Test::kTestEndpointId; + attributePathParams[0].mClusterId = chip::Test::kTestDeniedClusterId1; attributePathParams[0].mAttributeId = 1; - attributePathParams[1].mEndpointId = kTestEndpointId; - attributePathParams[1].mClusterId = kTestClusterId; + attributePathParams[1].mEndpointId = chip::Test::kTestEndpointId; + attributePathParams[1].mClusterId = chip::Test::kTestClusterId; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, 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); + pTestContext->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(pTestContext->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) From 46dd357cfe37fc30b0f8b9919fa7f120153e79cd Mon Sep 17 00:00:00 2001 From: AYA Date: Thu, 23 May 2024 15:39:49 +0200 Subject: [PATCH 17/22] Add more tests --- src/app/tests/BUILD.gn | 12 +- src/app/tests/TestAclEvent.cpp | 231 ++++++++++++-------------- src/app/tests/TestBindingTable.cpp | 182 +++++++++----------- src/app/tests/TestFailSafeContext.cpp | 102 ++++-------- 4 files changed, 222 insertions(+), 305 deletions(-) diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index da5587cf0dbd10..ba22bfcbf37fb8 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -148,6 +148,8 @@ chip_test_suite("tests") { ] test_sources = [ "TestAclAttribute.cpp", + "TestAclEvent.cpp", + "TestBindingTable.cpp", "TestBuilderParser.cpp", "TestCommandInteraction.cpp", "TestMessageDef.cpp", @@ -159,6 +161,10 @@ chip_test_suite("tests") { "TestWriteInteraction.cpp", ] + if (!chip_fake_platform) { + test_sources += [ "TestFailSafeContext.cpp" ] + } + cflags = [ "-Wconversion" ] public_deps = [ @@ -182,14 +188,12 @@ chip_test_suite_using_nltest("tests_nltest") { output_name = "libAppTestsNL" test_sources = [ - "TestAclEvent.cpp", "TestAttributeAccessInterfaceCache.cpp", "TestAttributePathExpandIterator.cpp", "TestAttributePersistenceProvider.cpp", "TestAttributeValueDecoder.cpp", "TestAttributeValueEncoder.cpp", "TestBasicCommandPathRegistry.cpp", - "TestBindingTable.cpp", "TestClusterInfo.cpp", "TestCommandPathParams.cpp", "TestConcreteAttributePath.cpp", @@ -210,10 +214,6 @@ chip_test_suite_using_nltest("tests_nltest") { "TestTimeSyncDataProvider.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" ] diff --git a/src/app/tests/TestAclEvent.cpp b/src/app/tests/TestAclEvent.cpp index 8f377cc263e9bd..5da3deec488d38 100644 --- a/src/app/tests/TestAclEvent.cpp +++ b/src/app/tests/TestAclEvent.cpp @@ -16,6 +16,10 @@ * limitations under the License. */ +#include + +#include + #include #include #include @@ -31,15 +35,10 @@ #include #include #include -#include -#include #include #include -#include #include -#include - namespace { using namespace chip; using namespace chip::Access; @@ -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,7 +99,7 @@ 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; @@ -153,10 +116,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(err, CHIP_NO_ERROR); testEventGenerator.SetStatus(1); err = logMgmt.LogEvent(&testEventGenerator, options2, eid2); - NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } class MockInteractionModelApp : public chip::app::ReadClient::Callback @@ -210,26 +173,75 @@ 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(); + if (mpTestContext != nullptr) + { + 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; + 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); + err = engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + app::reporting::GetDefaultReportScheduler()); + EXPECT_EQ(err, 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 @@ -239,29 +251,29 @@ void TestAclEvent::TestReadRoundtripWithEventStatusIBInEventReport(nlTestSuite * eventPathParams[0].mClusterId = kTestClusterId1; 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(err, 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. @@ -270,27 +282,27 @@ void TestAclEvent::TestReadRoundtripWithEventStatusIBInEventReport(nlTestSuite * eventPathParams[0].mEndpointId = kTestEndpointId; eventPathParams[0].mClusterId = kTestClusterId1; - 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(err, 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,27 +310,27 @@ 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(err, 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 @@ -331,64 +343,29 @@ void TestAclEvent::TestReadRoundtripWithEventStatusIBInEventReport(nlTestSuite * 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(err, 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/TestBindingTable.cpp b/src/app/tests/TestBindingTable.cpp index db95408813a0c1..7259c63ff16327 100644 --- a/src/app/tests/TestBindingTable.cpp +++ b/src/app/tests/TestBindingTable.cpp @@ -15,122 +15,122 @@ * limitations under the License. */ +#include + #include #include #include #include #include -#include using chip::BindingTable; namespace { -void TestEmptyBindingTable(nlTestSuite * aSuite, void * aContext) +void VerifyTableSame(BindingTable & table, const std::vector & expected) +{ + EXPECT_EQ(table.Size(), expected.size()); + auto iter1 = table.begin(); + auto iter2 = expected.begin(); + while (iter2 != expected.end()) + { + EXPECT_NE(iter1, table.end()); + EXPECT_EQ(*iter1, *iter2); + ++iter1; + ++iter2; + } + EXPECT_EQ(iter1, table.end()); +} + +void VerifyRestored(chip::TestPersistentStorageDelegate & storage, const std::vector & expected) +{ + BindingTable restoredTable; + restoredTable.SetPersistentStorage(&storage); + EXPECT_EQ(restoredTable.LoadFromStorage(), CHIP_NO_ERROR); + VerifyTableSame(restoredTable, expected); +} + +TEST(TestBindingTable, TestEmptyBindingTable) { BindingTable table; chip::TestPersistentStorageDelegate testStorage; table.SetPersistentStorage(&testStorage); - NL_TEST_ASSERT(aSuite, table.Size() == 0); - NL_TEST_ASSERT(aSuite, table.begin() == table.end()); + EXPECT_EQ(table.Size(), 0u); + EXPECT_EQ(table.begin(), table.end()); } -void TestAdd(nlTestSuite * aSuite, void * aContext) +TEST(TestBindingTable, TestAdd) { BindingTable table; chip::TestPersistentStorageDelegate testStorage; table.SetPersistentStorage(&testStorage); EmberBindingTableEntry unusedEntry; unusedEntry.type = MATTER_UNUSED_BINDING; - NL_TEST_ASSERT(aSuite, table.Add(unusedEntry) == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(table.Add(unusedEntry), CHIP_ERROR_INVALID_ARGUMENT); for (uint8_t i = 0; i < MATTER_BINDING_TABLE_SIZE; i++) { - NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, i, 0, 0, std::nullopt)) == CHIP_NO_ERROR); + EXPECT_EQ(table.Add(EmberBindingTableEntry::ForNode(0, i, 0, 0, std::nullopt)), CHIP_NO_ERROR); } - NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, 0, 0, 0, std::nullopt)) == CHIP_ERROR_NO_MEMORY); - NL_TEST_ASSERT(aSuite, table.Size() == MATTER_BINDING_TABLE_SIZE); + EXPECT_EQ(table.Add(EmberBindingTableEntry::ForNode(0, 0, 0, 0, std::nullopt)), CHIP_ERROR_NO_MEMORY); + EXPECT_EQ(table.Size(), MATTER_BINDING_TABLE_SIZE); auto iter = table.begin(); for (uint8_t i = 0; i < MATTER_BINDING_TABLE_SIZE; i++) { - NL_TEST_ASSERT(aSuite, iter != table.end()); - NL_TEST_ASSERT(aSuite, iter->nodeId == i); - NL_TEST_ASSERT(aSuite, iter.GetIndex() == i); + EXPECT_NE(iter, table.end()); + EXPECT_EQ(iter->nodeId, i); + EXPECT_EQ(iter.GetIndex(), i); ++iter; } - NL_TEST_ASSERT(aSuite, iter == table.end()); + EXPECT_EQ(iter, table.end()); } -void TestRemoveThenAdd(nlTestSuite * aSuite, void * aContext) +TEST(TestBindingTable, TestRemoveThenAdd) { BindingTable table; chip::TestPersistentStorageDelegate testStorage; table.SetPersistentStorage(&testStorage); - NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, 0, 0, 0, std::nullopt)) == CHIP_NO_ERROR); + EXPECT_EQ(table.Add(EmberBindingTableEntry::ForNode(0, 0, 0, 0, std::nullopt)), CHIP_NO_ERROR); auto iter = table.begin(); - NL_TEST_ASSERT(aSuite, table.RemoveAt(iter) == CHIP_NO_ERROR); - NL_TEST_ASSERT(aSuite, iter == table.end()); - NL_TEST_ASSERT(aSuite, table.Size() == 0); - NL_TEST_ASSERT(aSuite, table.begin() == table.end()); + EXPECT_EQ(table.RemoveAt(iter), CHIP_NO_ERROR); + EXPECT_EQ(iter, table.end()); + EXPECT_EQ(table.Size(), 0u); + EXPECT_EQ(table.begin(), table.end()); for (uint8_t i = 0; i < MATTER_BINDING_TABLE_SIZE; i++) { - NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, i, 0, 0, std::nullopt)) == CHIP_NO_ERROR); + EXPECT_EQ(table.Add(EmberBindingTableEntry::ForNode(0, i, 0, 0, std::nullopt)), CHIP_NO_ERROR); } iter = table.begin(); ++iter; - NL_TEST_ASSERT(aSuite, table.RemoveAt(iter) == CHIP_NO_ERROR); - NL_TEST_ASSERT(aSuite, table.Size() == MATTER_BINDING_TABLE_SIZE - 1); - NL_TEST_ASSERT(aSuite, iter->nodeId == 2); - NL_TEST_ASSERT(aSuite, iter.GetIndex() == 2); + EXPECT_EQ(table.RemoveAt(iter), CHIP_NO_ERROR); + EXPECT_EQ(table.Size(), MATTER_BINDING_TABLE_SIZE - 1); + EXPECT_EQ(iter->nodeId, 2u); + EXPECT_EQ(iter.GetIndex(), 2u); auto iterCheck = table.begin(); ++iterCheck; - NL_TEST_ASSERT(aSuite, iter == iterCheck); + EXPECT_EQ(iter, iterCheck); - NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(0, 1, 0, 0, std::nullopt)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(aSuite, table.Size() == MATTER_BINDING_TABLE_SIZE); + EXPECT_EQ(table.Add(EmberBindingTableEntry::ForNode(0, 1, 0, 0, std::nullopt)), CHIP_NO_ERROR); + EXPECT_EQ(table.Size(), MATTER_BINDING_TABLE_SIZE); iter = table.begin(); for (uint8_t i = 0; i < MATTER_BINDING_TABLE_SIZE - 1; i++) { ++iter; } - NL_TEST_ASSERT(aSuite, iter->nodeId == 1); - NL_TEST_ASSERT(aSuite, iter.GetIndex() == 1); + EXPECT_EQ(iter->nodeId, 1u); + EXPECT_EQ(iter.GetIndex(), 1u); ++iter; - NL_TEST_ASSERT(aSuite, iter == table.end()); + EXPECT_EQ(iter, table.end()); iter = table.begin(); - NL_TEST_ASSERT(aSuite, table.RemoveAt(iter) == CHIP_NO_ERROR); - NL_TEST_ASSERT(aSuite, table.Size() == MATTER_BINDING_TABLE_SIZE - 1); - NL_TEST_ASSERT(aSuite, iter == table.begin()); - NL_TEST_ASSERT(aSuite, iter.GetIndex() == 2); - NL_TEST_ASSERT(aSuite, iter->nodeId == 2); - NL_TEST_ASSERT(aSuite, table.GetAt(0).type == MATTER_UNUSED_BINDING); -} - -void VerifyTableSame(nlTestSuite * aSuite, BindingTable & table, const std::vector & expected) -{ - NL_TEST_ASSERT(aSuite, table.Size() == expected.size()); - auto iter1 = table.begin(); - auto iter2 = expected.begin(); - while (iter2 != expected.end()) - { - NL_TEST_ASSERT(aSuite, iter1 != table.end()); - NL_TEST_ASSERT(aSuite, *iter1 == *iter2); - ++iter1; - ++iter2; - } - NL_TEST_ASSERT(aSuite, iter1 == table.end()); + EXPECT_EQ(table.RemoveAt(iter), CHIP_NO_ERROR); + EXPECT_EQ(table.Size(), MATTER_BINDING_TABLE_SIZE - 1); + EXPECT_EQ(iter, table.begin()); + EXPECT_EQ(iter.GetIndex(), 2u); + EXPECT_EQ(iter->nodeId, 2u); + EXPECT_EQ(table.GetAt(0).type, MATTER_UNUSED_BINDING); } -void VerifyRestored(nlTestSuite * aSuite, chip::TestPersistentStorageDelegate & storage, - const std::vector & expected) -{ - BindingTable restoredTable; - restoredTable.SetPersistentStorage(&storage); - NL_TEST_ASSERT(aSuite, restoredTable.LoadFromStorage() == CHIP_NO_ERROR); - VerifyTableSame(aSuite, restoredTable, expected); -} - -void TestPersistentStorage(nlTestSuite * aSuite, void * aContext) +TEST(TestBindingTable, TestPersistentStorage) { chip::TestPersistentStorageDelegate testStorage; BindingTable table; @@ -142,68 +142,46 @@ void TestPersistentStorage(nlTestSuite * aSuite, void * aContext) EmberBindingTableEntry::ForGroup(3, 3, 0, cluster.std_optional()), }; table.SetPersistentStorage(&testStorage); - NL_TEST_ASSERT(aSuite, table.Add(expected[0]) == CHIP_NO_ERROR); - NL_TEST_ASSERT(aSuite, table.Add(expected[1]) == CHIP_NO_ERROR); - NL_TEST_ASSERT(aSuite, table.Add(expected[2]) == CHIP_NO_ERROR); - NL_TEST_ASSERT(aSuite, table.Add(expected[3]) == CHIP_NO_ERROR); - VerifyRestored(aSuite, testStorage, expected); + EXPECT_EQ(table.Add(expected[0]), CHIP_NO_ERROR); + EXPECT_EQ(table.Add(expected[1]), CHIP_NO_ERROR); + EXPECT_EQ(table.Add(expected[2]), CHIP_NO_ERROR); + EXPECT_EQ(table.Add(expected[3]), CHIP_NO_ERROR); + VerifyRestored(testStorage, expected); // Verify storage untouched if add fails testStorage.AddPoisonKey(chip::DefaultStorageKeyAllocator::BindingTableEntry(4).KeyName()); - NL_TEST_ASSERT(aSuite, table.Add(EmberBindingTableEntry::ForNode(4, 4, 0, 0, std::nullopt)) != CHIP_NO_ERROR); - VerifyRestored(aSuite, testStorage, expected); + EXPECT_NE(table.Add(EmberBindingTableEntry::ForNode(4, 4, 0, 0, std::nullopt)), CHIP_NO_ERROR); + VerifyRestored(testStorage, expected); testStorage.ClearPoisonKeys(); // Verify storage untouched if removing head fails testStorage.AddPoisonKey(chip::DefaultStorageKeyAllocator::BindingTable().KeyName()); auto iter = table.begin(); - NL_TEST_ASSERT(aSuite, table.RemoveAt(iter) != CHIP_NO_ERROR); - VerifyTableSame(aSuite, table, expected); + EXPECT_NE(table.RemoveAt(iter), CHIP_NO_ERROR); + VerifyTableSame(table, expected); testStorage.ClearPoisonKeys(); - VerifyRestored(aSuite, testStorage, expected); + VerifyRestored(testStorage, expected); // Verify storage untouched if removing other nodes fails testStorage.AddPoisonKey(chip::DefaultStorageKeyAllocator::BindingTableEntry(0).KeyName()); iter = table.begin(); ++iter; - NL_TEST_ASSERT(aSuite, table.RemoveAt(iter) != CHIP_NO_ERROR); - VerifyTableSame(aSuite, table, expected); + EXPECT_NE(table.RemoveAt(iter), CHIP_NO_ERROR); + VerifyTableSame(table, expected); testStorage.ClearPoisonKeys(); - VerifyRestored(aSuite, testStorage, expected); + VerifyRestored(testStorage, expected); // Verify removing head iter = table.begin(); - NL_TEST_ASSERT(aSuite, table.RemoveAt(iter) == CHIP_NO_ERROR); - VerifyTableSame(aSuite, table, { expected[1], expected[2], expected[3] }); - VerifyRestored(aSuite, testStorage, { expected[1], expected[2], expected[3] }); + EXPECT_EQ(table.RemoveAt(iter), CHIP_NO_ERROR); + VerifyTableSame(table, { expected[1], expected[2], expected[3] }); + VerifyRestored(testStorage, { expected[1], expected[2], expected[3] }); // Verify removing other nodes ++iter; - NL_TEST_ASSERT(aSuite, table.RemoveAt(iter) == CHIP_NO_ERROR); - VerifyTableSame(aSuite, table, { expected[1], expected[3] }); - VerifyRestored(aSuite, testStorage, { expected[1], expected[3] }); + EXPECT_EQ(table.RemoveAt(iter), CHIP_NO_ERROR); + VerifyTableSame(table, { expected[1], expected[3] }); + VerifyRestored(testStorage, { expected[1], expected[3] }); } } // namespace - -int TestBindingTable() -{ - static nlTest sTests[] = { - NL_TEST_DEF("TestEmptyBindingTable", TestEmptyBindingTable), - NL_TEST_DEF("TestAdd", TestAdd), - NL_TEST_DEF("TestRemoveThenAdd", TestRemoveThenAdd), - NL_TEST_DEF("TestPersistentStorage", TestPersistentStorage), - NL_TEST_SENTINEL(), - }; - - nlTestSuite theSuite = { - "BindingTable", - &sTests[0], - nullptr, - nullptr, - }; - nlTestRunner(&theSuite, nullptr); - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestBindingTable) diff --git a/src/app/tests/TestFailSafeContext.cpp b/src/app/tests/TestFailSafeContext.cpp index 2d2b9fa15d2b7d..96868ff241fa28 100644 --- a/src/app/tests/TestFailSafeContext.cpp +++ b/src/app/tests/TestFailSafeContext.cpp @@ -28,11 +28,11 @@ #include #include +#include + #include #include #include -#include -#include #include using namespace chip; @@ -44,100 +44,62 @@ namespace { constexpr FabricIndex kTestAccessingFabricIndex1 = 1; constexpr FabricIndex kTestAccessingFabricIndex2 = 2; +class TestFailSafeContext : public ::testing::Test +{ +public: + static void SetUpTestSuite() + { + ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); + ASSERT_EQ(PlatformMgr().InitChipStack(), CHIP_NO_ERROR); + } + static void TearDownTestSuite() + { + PlatformMgr().Shutdown(); + chip::Platform::MemoryShutdown(); + } +}; + // ================================= // Unit tests // ================================= -static void TestPlatformMgr_Init(nlTestSuite * inSuite, void * inContext) -{ - CHIP_ERROR err = PlatformMgr().InitChipStack(); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); -} - -static void TestFailSafeContext_ArmFailSafe(nlTestSuite * inSuite, void * inContext) +TEST_F(TestFailSafeContext, TestFailSafeContext_ArmFailSafe) { CHIP_ERROR err = CHIP_NO_ERROR; chip::app::FailSafeContext failSafeContext; err = failSafeContext.ArmFailSafe(kTestAccessingFabricIndex1, System::Clock::Seconds16(1)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, failSafeContext.IsFailSafeArmed() == true); - NL_TEST_ASSERT(inSuite, failSafeContext.GetFabricIndex() == kTestAccessingFabricIndex1); - NL_TEST_ASSERT(inSuite, failSafeContext.IsFailSafeArmed(kTestAccessingFabricIndex1) == true); - NL_TEST_ASSERT(inSuite, failSafeContext.IsFailSafeArmed(kTestAccessingFabricIndex2) == false); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(failSafeContext.IsFailSafeArmed()); + EXPECT_EQ(failSafeContext.GetFabricIndex(), kTestAccessingFabricIndex1); + EXPECT_TRUE(failSafeContext.IsFailSafeArmed(kTestAccessingFabricIndex1)); + EXPECT_FALSE(failSafeContext.IsFailSafeArmed(kTestAccessingFabricIndex2)); failSafeContext.DisarmFailSafe(); - NL_TEST_ASSERT(inSuite, failSafeContext.IsFailSafeArmed() == false); + EXPECT_FALSE(failSafeContext.IsFailSafeArmed()); } -static void TestFailSafeContext_NocCommandInvoked(nlTestSuite * inSuite, void * inContext) +TEST_F(TestFailSafeContext, TestFailSafeContext_NocCommandInvoked) { CHIP_ERROR err = CHIP_NO_ERROR; chip::app::FailSafeContext failSafeContext; err = failSafeContext.ArmFailSafe(kTestAccessingFabricIndex1, System::Clock::Seconds16(1)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, failSafeContext.GetFabricIndex() == kTestAccessingFabricIndex1); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(failSafeContext.GetFabricIndex(), kTestAccessingFabricIndex1); failSafeContext.SetAddNocCommandInvoked(kTestAccessingFabricIndex2); - NL_TEST_ASSERT(inSuite, failSafeContext.NocCommandHasBeenInvoked() == true); - NL_TEST_ASSERT(inSuite, failSafeContext.AddNocCommandHasBeenInvoked() == true); - NL_TEST_ASSERT(inSuite, failSafeContext.GetFabricIndex() == kTestAccessingFabricIndex2); + EXPECT_TRUE(failSafeContext.NocCommandHasBeenInvoked()); + EXPECT_TRUE(failSafeContext.AddNocCommandHasBeenInvoked()); + EXPECT_EQ(failSafeContext.GetFabricIndex(), kTestAccessingFabricIndex2); failSafeContext.SetUpdateNocCommandInvoked(); - NL_TEST_ASSERT(inSuite, failSafeContext.NocCommandHasBeenInvoked() == true); - NL_TEST_ASSERT(inSuite, failSafeContext.UpdateNocCommandHasBeenInvoked() == true); + EXPECT_TRUE(failSafeContext.NocCommandHasBeenInvoked()); + EXPECT_TRUE(failSafeContext.UpdateNocCommandHasBeenInvoked()); failSafeContext.DisarmFailSafe(); } -/** - * Test Suite. It lists all the test functions. - */ -static const nlTest sTests[] = { - - NL_TEST_DEF("Test PlatformMgr::Init", TestPlatformMgr_Init), - NL_TEST_DEF("Test FailSafeContext::ArmFailSafe", TestFailSafeContext_ArmFailSafe), - NL_TEST_DEF("Test FailSafeContext::NocCommandInvoked", TestFailSafeContext_NocCommandInvoked), - - NL_TEST_SENTINEL() -}; - -/** - * Set up the test suite. - */ -int TestFailSafeContext_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int TestFailSafeContext_Teardown(void * inContext) -{ - PlatformMgr().Shutdown(); - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - } // namespace - -/** - * Main - */ -int TestFailSafeContext() -{ - nlTestSuite theSuite = { "FailSafeContext tests", &sTests[0], TestFailSafeContext_Setup, TestFailSafeContext_Teardown }; - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestFailSafeContext) From 2f71a2d351c56c58afcde30ba6b5a0bc20d3c624 Mon Sep 17 00:00:00 2001 From: AYA Date: Mon, 27 May 2024 16:50:23 +0200 Subject: [PATCH 18/22] switching order of running tests for nordic --- src/test_driver/nrfconnect/main/runner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test_driver/nrfconnect/main/runner.cpp b/src/test_driver/nrfconnect/main/runner.cpp index d779f1d5300d09..68e2b60ed22af0 100644 --- a/src/test_driver/nrfconnect/main/runner.cpp +++ b/src/test_driver/nrfconnect/main/runner.cpp @@ -36,8 +36,8 @@ extern "C" int main(void) LOG_INF("Starting CHIP tests!"); int status = 0; - status += chip::test::RunAllTests(); status += RunRegisteredUnitTests(); + status += chip::test::RunAllTests(); LOG_INF("CHIP test status: %d", status); _exit(status); From 642671c63c0bf66efc0ff69c65575b1c6f56a860 Mon Sep 17 00:00:00 2001 From: AYA Date: Mon, 27 May 2024 16:57:27 +0200 Subject: [PATCH 19/22] workaround, make TestAclAttribute run after other tests --- src/app/tests/BUILD.gn | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index ba22bfcbf37fb8..af3a75cae3cb59 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -147,7 +147,6 @@ chip_test_suite("tests") { "WriteHandlerTestAccess.h", ] test_sources = [ - "TestAclAttribute.cpp", "TestAclEvent.cpp", "TestBindingTable.cpp", "TestBuilderParser.cpp", @@ -161,6 +160,10 @@ chip_test_suite("tests") { "TestWriteInteraction.cpp", ] + # TestAclAttribute is a test that causes failures in TestAclEvent or TestReadInteraction if it is run before them on Zephyr Native_Posix used by Nordic CI. + ##TODO resolve this test to make sure its teardown does not cause failures in those tests. and put it in the above test_sources list + test_sources += [ "TestAclAttribute.cpp" ] + if (!chip_fake_platform) { test_sources += [ "TestFailSafeContext.cpp" ] } From 74d663b101210ae75727ed24cfc94b9c07ae236b Mon Sep 17 00:00:00 2001 From: AYA Date: Tue, 28 May 2024 16:22:06 +0200 Subject: [PATCH 20/22] Fix TearDown issue of some App Tests --- src/app/tests/AppTestContext.cpp | 6 ++++++ src/app/tests/BUILD.gn | 12 +++++------- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/app/tests/AppTestContext.cpp b/src/app/tests/AppTestContext.cpp index eca7a2db76c83b..a4f763046bf7a5 100644 --- a/src/app/tests/AppTestContext.cpp +++ b/src/app/tests/AppTestContext.cpp @@ -49,6 +49,12 @@ void AppContext::SetUpTestSuite() void AppContext::TearDownTestSuite() { + // Adding a DrainAndServiceIO call fixes the teardown for some tests (TestAclAttribute and TestReportScheduler); these were + // triggering failures in tests that follow them when running on nRF CI (Zephyr native_posix where all Unit Tests are compiled + // into a single file) + // TODO: understand this more and solve underlying issue + LoopbackMessagingContext::DrainAndServiceIO(); + chip::DeviceLayer::PlatformMgr().Shutdown(); LoopbackMessagingContext::TearDownTestSuite(); } diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index af3a75cae3cb59..98e8c014046589 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -147,6 +147,7 @@ chip_test_suite("tests") { "WriteHandlerTestAccess.h", ] test_sources = [ + "TestAclAttribute.cpp", "TestAclEvent.cpp", "TestBindingTable.cpp", "TestBuilderParser.cpp", @@ -160,10 +161,6 @@ chip_test_suite("tests") { "TestWriteInteraction.cpp", ] - # TestAclAttribute is a test that causes failures in TestAclEvent or TestReadInteraction if it is run before them on Zephyr Native_Posix used by Nordic CI. - ##TODO resolve this test to make sure its teardown does not cause failures in those tests. and put it in the above test_sources list - test_sources += [ "TestAclAttribute.cpp" ] - if (!chip_fake_platform) { test_sources += [ "TestFailSafeContext.cpp" ] } @@ -242,11 +239,12 @@ chip_test_suite_using_nltest("tests_nltest") { # The platform manager is not properly clearing queues in test teardown, which results in # DrainIO calls not being able to run in expected time (5seconds) if unprocessed reported engine - # runs are remaining, causing tests to crash in Open IoT SDK and Zephyr tests since they are + # runs are remaining, causing tests to crash in Open IoT SDK since they are # running all tests in one file. We need to figure out how to properly clean the event queues # before enabling this test for these platforms. - if (chip_device_platform != "nrfconnect" && - chip_device_platform != "openiotsdk") { + # Update: This was fixed for Nordic Zephyr Tests by calling DrainAndServiceIO in AppContext::TearDownTestSuite() + # TODO: check if above solution works for openiotsdk as well + if (chip_device_platform != "openiotsdk") { test_sources += [ "TestReportScheduler.cpp" ] } From 6d7f58e302db695f31cbc67b563cbdf4a9830d2b Mon Sep 17 00:00:00 2001 From: AYA Date: Tue, 28 May 2024 16:22:57 +0200 Subject: [PATCH 21/22] clean TestAclAttribute and TestAclEvent --- src/app/tests/TestAclAttribute.cpp | 51 ++++++++++++++---------------- src/app/tests/TestAclEvent.cpp | 13 ++++---- 2 files changed, 29 insertions(+), 35 deletions(-) diff --git a/src/app/tests/TestAclAttribute.cpp b/src/app/tests/TestAclAttribute.cpp index d143bffef9792a..47c3eb61289ad4 100644 --- a/src/app/tests/TestAclAttribute.cpp +++ b/src/app/tests/TestAclAttribute.cpp @@ -46,11 +46,6 @@ namespace { using namespace chip; using namespace chip::Access; -// chip::ClusterId kTestClusterId = 1; -// chip::ClusterId kTestDeniedClusterId1 = 1000; -// chip::ClusterId kTestDeniedClusterId2 = 3; -// chip::EndpointId kTestEndpointId = 4; - class TestAccessControlDelegate : public AccessControl::Delegate { public: @@ -119,25 +114,25 @@ class TestAclAttribute : public ::testing::Test static void SetUpTestSuite() { - pTestContext = new chip::Test::AppContext; + mpTestContext = new chip::Test::AppContext; - pTestContext->SetUpTestSuite(); + mpTestContext->SetUpTestSuite(); } static void TearDownTestSuite() { - pTestContext->TearDownTestSuite(); - if (pTestContext != nullptr) + mpTestContext->TearDownTestSuite(); + if (mpTestContext != nullptr) { - delete pTestContext; + delete mpTestContext; } } void SetUp() override { - if (pTestContext != nullptr) + if (mpTestContext != nullptr) { - pTestContext->SetUp(); + mpTestContext->SetUp(); Access::GetAccessControl().Finish(); Access::GetAccessControl().Init(GetTestAccessControlDelegate(), gDeviceTypeResolver); @@ -145,15 +140,15 @@ class TestAclAttribute : public ::testing::Test } void TearDown() override { - if (pTestContext != nullptr) + if (mpTestContext != nullptr) { - pTestContext->TearDown(); + mpTestContext->TearDown(); } } - static chip::Test::AppContext * pTestContext; + static chip::Test::AppContext * mpTestContext; }; -chip::Test::AppContext * TestAclAttribute::pTestContext = nullptr; +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. @@ -161,17 +156,17 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) { CHIP_ERROR err = CHIP_NO_ERROR; - Messaging::ReliableMessageMgr * rm = pTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - err = engine->Init(&pTestContext->GetExchangeManager(), &pTestContext->GetFabricTable(), + err = engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), app::reporting::GetDefaultReportScheduler()); EXPECT_EQ(err, CHIP_NO_ERROR); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &pTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; @@ -183,14 +178,14 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) attributePathParams[1].mClusterId = chip::Test::kTestDeniedClusterId1; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - pTestContext->DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); EXPECT_FALSE(delegate.mGotReport); delegate.mError = CHIP_NO_ERROR; @@ -198,7 +193,7 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) } { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &pTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; @@ -209,14 +204,14 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) attributePathParams[1].mClusterId = chip::Test::kTestDeniedClusterId2; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - pTestContext->DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); EXPECT_FALSE(delegate.mGotReport); delegate.mError = CHIP_NO_ERROR; @@ -224,7 +219,7 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) } { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &pTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; @@ -236,14 +231,14 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) attributePathParams[1].mClusterId = chip::Test::kTestClusterId; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(pTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - pTestContext->DrainAndServiceIO(); + mpTestContext->DrainAndServiceIO(); EXPECT_EQ(delegate.mError, CHIP_NO_ERROR); EXPECT_TRUE(delegate.mGotReport); EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); @@ -253,7 +248,7 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(pTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); } } // namespace app } // namespace chip diff --git a/src/app/tests/TestAclEvent.cpp b/src/app/tests/TestAclEvent.cpp index 5da3deec488d38..3e9ad3f631c17f 100644 --- a/src/app/tests/TestAclEvent.cpp +++ b/src/app/tests/TestAclEvent.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -47,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; @@ -61,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; } @@ -104,7 +104,7 @@ 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; @@ -215,7 +215,6 @@ class TestAclEvent : public ::testing::Test // Performs teardown for each individual test in the test suite void TearDown() override { - chip::app::EventManagement::DestroyEventManagement(); mpTestContext->TearDown(); } @@ -248,7 +247,7 @@ TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) { 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(mpTestContext->GetSessionBobToAlice()); @@ -280,7 +279,7 @@ TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) { chip::app::EventPathParams eventPathParams[1]; eventPathParams[0].mEndpointId = kTestEndpointId; - eventPathParams[0].mClusterId = kTestClusterId1; + eventPathParams[0].mClusterId = chip::Test::kTestDeniedClusterId2; ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = eventPathParams; @@ -337,7 +336,7 @@ TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) { 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; From d033c0b3ffb0b5dbf28b17b6fa51ea9b747c354f Mon Sep 17 00:00:00 2001 From: AYA Date: Tue, 28 May 2024 18:03:02 +0200 Subject: [PATCH 22/22] Check if fix for Test Teardown works for OpenIoTSDK --- src/app/tests/BUILD.gn | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index 98e8c014046589..ac8704deac28a8 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -210,6 +210,7 @@ chip_test_suite_using_nltest("tests_nltest") { "TestPendingResponseTrackerImpl.cpp", "TestPowerSourceCluster.cpp", "TestReadInteraction.cpp", + "TestReportScheduler.cpp", "TestTestEventTriggerDelegate.cpp", "TestTimeSyncDataProvider.cpp", ] @@ -245,7 +246,7 @@ chip_test_suite_using_nltest("tests_nltest") { # Update: This was fixed for Nordic Zephyr Tests by calling DrainAndServiceIO in AppContext::TearDownTestSuite() # TODO: check if above solution works for openiotsdk as well if (chip_device_platform != "openiotsdk") { - test_sources += [ "TestReportScheduler.cpp" ] + test_sources += [] } cflags = [ "-Wconversion" ]