From f3bf1098527f0e1c19d2586d46821c65adc3dcef Mon Sep 17 00:00:00 2001 From: Jeff Feasel Date: Thu, 16 May 2024 23:50:04 -0400 Subject: [PATCH 01/16] Modified MessagingContext and its subclasses as well as AppContext to reflect PW migration. --- src/app/tests/AppTestContext.cpp | 26 +- src/app/tests/AppTestContext.h | 4 +- src/controller/tests/TestEventCaching.cpp | 77 ++---- src/controller/tests/TestWriteChunking.cpp | 266 +++++++++------------ src/messaging/tests/MessagingContext.cpp | 4 +- src/messaging/tests/MessagingContext.h | 90 +++---- 6 files changed, 197 insertions(+), 270 deletions(-) diff --git a/src/app/tests/AppTestContext.cpp b/src/app/tests/AppTestContext.cpp index eca7a2db76c83b..28ce87d473935c 100644 --- a/src/app/tests/AppTestContext.cpp +++ b/src/app/tests/AppTestContext.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include "AppTestContext.h" #include #include @@ -40,11 +40,10 @@ namespace Test { void AppContext::SetUpTestSuite() { - CHIP_ERROR err = CHIP_NO_ERROR; LoopbackMessagingContext::SetUpTestSuite(); - // TODO: use ASSERT_EQ, once transition to pw_unit_test is complete - VerifyOrDieWithMsg((err = chip::DeviceLayer::PlatformMgr().InitChipStack()) == CHIP_NO_ERROR, AppServer, - "Init CHIP stack failed: %" CHIP_ERROR_FORMAT, err.Format()); + VerifyOrReturn(!HasFailure()); // Stop if parent had a failure. + + ASSERT_EQ(chip::DeviceLayer::PlatformMgr().InitChipStack(), CHIP_NO_ERROR); } void AppContext::TearDownTestSuite() @@ -55,17 +54,15 @@ void AppContext::TearDownTestSuite() void AppContext::SetUp() { - CHIP_ERROR err = CHIP_NO_ERROR; LoopbackMessagingContext::SetUp(); - // TODO: use ASSERT_EQ, once transition to pw_unit_test is complete - VerifyOrDieWithMsg((err = app::InteractionModelEngine::GetInstance()->Init(&GetExchangeManager(), &GetFabricTable(), - app::reporting::GetDefaultReportScheduler())) == - CHIP_NO_ERROR, - AppServer, "Init InteractionModelEngine failed: %" CHIP_ERROR_FORMAT, err.Format()); + VerifyOrReturn(!HasFailure()); // Stop if parent had a failure. + + ASSERT_EQ(app::InteractionModelEngine::GetInstance()->Init(&GetExchangeManager(), &GetFabricTable(), + app::reporting::GetDefaultReportScheduler()), + CHIP_NO_ERROR); Access::SetAccessControl(gPermissiveAccessControl); - VerifyOrDieWithMsg((err = Access::GetAccessControl().Init(chip::Access::Examples::GetPermissiveAccessControlDelegate(), - gDeviceTypeResolver)) == CHIP_NO_ERROR, - AppServer, "Init AccessControl failed: %" CHIP_ERROR_FORMAT, err.Format()); + ASSERT_EQ(Access::GetAccessControl().Init(chip::Access::Examples::GetPermissiveAccessControlDelegate(), gDeviceTypeResolver), + CHIP_NO_ERROR); } void AppContext::TearDown() @@ -73,6 +70,7 @@ void AppContext::TearDown() Access::GetAccessControl().Finish(); Access::ResetAccessControlToDefault(); chip::app::InteractionModelEngine::GetInstance()->Shutdown(); + LoopbackMessagingContext::TearDown(); } diff --git a/src/app/tests/AppTestContext.h b/src/app/tests/AppTestContext.h index a2fe3387d2d7aa..c05e490fb9e6aa 100644 --- a/src/app/tests/AppTestContext.h +++ b/src/app/tests/AppTestContext.h @@ -32,9 +32,9 @@ class AppContext : public LoopbackMessagingContext // Performs shared teardown for all tests in the test suite static void TearDownTestSuite(); // Performs setup for each individual test in the test suite - void SetUp(); + virtual void SetUp(); // Performs teardown for each individual test in the test suite - void TearDown(); + virtual void TearDown(); }; } // namespace Test diff --git a/src/controller/tests/TestEventCaching.cpp b/src/controller/tests/TestEventCaching.cpp index b4c262725f74d3..e31e3ed358b6f0 100644 --- a/src/controller/tests/TestEventCaching.cpp +++ b/src/controller/tests/TestEventCaching.cpp @@ -16,8 +16,6 @@ * limitations under the License. */ -#include - #include "app-common/zap-generated/ids/Attributes.h" #include "app-common/zap-generated/ids/Clusters.h" #include "app/ClusterStateCache.h" @@ -37,7 +35,6 @@ #include #include #include -#include using namespace chip; using namespace chip::app; @@ -50,8 +47,6 @@ static uint8_t gInfoEventBuffer[4096]; static uint8_t gCritEventBuffer[4096]; static chip::app::CircularEventBuffer gCircularEventBuffer[3]; -using TestContext = chip::Test::AppContext; - // // The generated endpoint_config for the controller app has Endpoint 1 // already used in the fixed endpoint set of size 1. Consequently, let's use the next @@ -59,33 +54,10 @@ using TestContext = chip::Test::AppContext; // constexpr EndpointId kTestEndpointId = 2; -class TestEventCaching : public ::testing::Test +class TestEventCaching : public Test::AppContext { -public: - // Performs shared setup for all tests in the test suite - static void SetUpTestSuite() - { - if (mpContext == nullptr) - { - mpContext = new TestContext(); - ASSERT_NE(mpContext, nullptr); - } - mpContext->SetUpTestSuite(); - } - - // Performs shared teardown for all tests in the test suite - static void TearDownTestSuite() - { - mpContext->TearDownTestSuite(); - if (mpContext != nullptr) - { - delete mpContext; - mpContext = nullptr; - } - } - protected: - // Performs setup for each test in the suite + // Performs setup for each test in the suite. Run once for each test function. void SetUp() { const chip::app::LogStorageResources logStorageResources[] = { @@ -94,29 +66,24 @@ class TestEventCaching : public ::testing::Test { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - mpContext->SetUp(); + AppContext::SetUp(); // Call parent. + VerifyOrReturn(!HasFailure()); // Stop if parent had a failure. - 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(&mpContext->GetExchangeManager(), ArraySize(logStorageResources), + ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); + chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); } - // Performs teardown for each test in the suite + // Performs teardown for each test in the suite. Run once for each test function. void TearDown() { chip::app::EventManagement::DestroyEventManagement(); - mpContext->TearDown(); + AppContext::TearDown(); // Call parent. } - static TestContext * mpContext; - private: MonotonicallyIncreasingCounter mEventCounter; }; -TestContext * TestEventCaching::mpContext = nullptr; //clang-format off DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(testClusterAttrs) @@ -179,7 +146,7 @@ void GenerateEvents(chip::EventNumber & firstEventNumber, chip::EventNumber & la */ TEST_F(TestEventCaching, TestBasicCaching) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance(); // Initialize the ember side server logic @@ -207,12 +174,12 @@ TEST_F(TestEventCaching, TestBasicCaching) TestReadCallback readCallback; { - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), - readCallback.mClusterCacheAdapter.GetBufferedCallback(), app::ReadClient::InteractionType::Read); + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mClusterCacheAdapter.GetBufferedCallback(), + app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); uint8_t generationCount = 0; readCallback.mClusterCacheAdapter.ForEachEventData( @@ -340,12 +307,12 @@ TEST_F(TestEventCaching, TestBasicCaching) GenerateEvents(firstEventNumber, lastEventNumber); { - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), - readCallback.mClusterCacheAdapter.GetBufferedCallback(), app::ReadClient::InteractionType::Read); + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mClusterCacheAdapter.GetBufferedCallback(), + app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // // Validate that we still have all 5 of the old events we received, as well as the new ones that just got generated. @@ -392,8 +359,8 @@ TEST_F(TestEventCaching, TestBasicCaching) // we don't receive events lower than that value. // { - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), - readCallback.mClusterCacheAdapter.GetBufferedCallback(), app::ReadClient::InteractionType::Read); + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mClusterCacheAdapter.GetBufferedCallback(), + app::ReadClient::InteractionType::Read); readCallback.mClusterCacheAdapter.ClearEventCache(); constexpr EventNumber kLastSeenEventNumber = 3; @@ -405,7 +372,7 @@ TEST_F(TestEventCaching, TestBasicCaching) EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // We should only get events with event numbers larger than kHighestEventNumberSeen. EXPECT_EQ(readCallback.mEventsSeen, lastEventNumber - kLastSeenEventNumber); @@ -441,12 +408,12 @@ TEST_F(TestEventCaching, TestBasicCaching) { readParams.mEventNumber.SetValue(5); - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), - readCallback.mClusterCacheAdapter.GetBufferedCallback(), app::ReadClient::InteractionType::Read); + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mClusterCacheAdapter.GetBufferedCallback(), + app::ReadClient::InteractionType::Read); readCallback.mClusterCacheAdapter.ClearEventCache(true); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // // Validate that we would receive 5 events @@ -474,7 +441,7 @@ TEST_F(TestEventCaching, TestBasicCaching) EXPECT_TRUE(highestEventNumber.HasValue() && highestEventNumber.Value() == 9); } - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); emberAfClearDynamicEndpoint(0); } diff --git a/src/controller/tests/TestWriteChunking.cpp b/src/controller/tests/TestWriteChunking.cpp index 60be2212aa00e8..5059b8eb40f2ac 100644 --- a/src/controller/tests/TestWriteChunking.cpp +++ b/src/controller/tests/TestWriteChunking.cpp @@ -19,8 +19,6 @@ #include #include -#include - #include "app-common/zap-generated/ids/Attributes.h" #include "app-common/zap-generated/ids/Clusters.h" #include "app/ConcreteAttributePath.h" @@ -40,7 +38,6 @@ #include #include -using TestContext = chip::Test::AppContext; using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; @@ -62,41 +59,39 @@ constexpr uint32_t kTestListLength = 5; // We don't really care about the content, we just need a buffer. uint8_t sByteSpanData[app::kMaxSecureSduLengthBytes]; -class TestWriteChunking : public ::testing::Test +class TestWriteChunking : public Test::AppContext { -public: - // Performs shared setup for all tests in the test suite - static void SetUpTestSuite() - { - if (mpContext == nullptr) - { - mpContext = new TestContext(); - ASSERT_NE(mpContext, nullptr); - } - mpContext->SetUpTestSuite(); - } +private: + using PathStatus = std::pair; - // Performs shared teardown for all tests in the test suite - static void TearDownTestSuite() +protected: + enum class Operations : uint8_t { - mpContext->TearDownTestSuite(); - if (mpContext != nullptr) - { - delete mpContext; - mpContext = nullptr; - } - } + kNoop, + kShutdownWriteClient, + }; -protected: - // Performs setup for each test in the suite - void SetUp() { mpContext->SetUp(); } + enum class ListData : uint8_t + { + kNull, + kList, + kBadValue, + }; - // Performs teardown for each test in the suite - void TearDown() { mpContext->TearDown(); } + struct Instructions + { + // The paths used in write request + std::vector paths; + // The type of content of the list, it should be an empty vector or its size should equals to the list of paths. + std::vector data; + // operations on OnListWriteBegin and OnListWriteEnd on the server side. + std::function onListWriteBeginActions; + // The expected status when OnListWriteEnd is called. In the same order as paths + std::vector expectedStatus; + }; - static TestContext * mpContext; + void RunTest(Instructions instructions); }; -TestContext * TestWriteChunking::mpContext = nullptr; //clang-format off DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(testClusterAttrsOnEndpoint) @@ -211,7 +206,7 @@ CHIP_ERROR TestAttrAccess::Write(const app::ConcreteDataAttributePath & aPath, a */ TEST_F(TestWriteChunking, TestListChunking) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); // Initialize the ember side server logic InitDataModelHandler(); @@ -238,7 +233,7 @@ TEST_F(TestWriteChunking, TestListChunking) gIterationCount = i; - app::WriteClient writeClient(&mpContext->GetExchangeManager(), &writeCallback, Optional::Missing(), + app::WriteClient writeClient(&GetExchangeManager(), &writeCallback, Optional::Missing(), static_cast(minReservationSize + i) /* reserved buffer size */); ByteSpan list[kTestListLength]; @@ -256,14 +251,14 @@ TEST_F(TestWriteChunking, TestListChunking) // for (int j = 0; j < 10 && writeCallback.mOnDoneCount == 0; j++) { - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); } EXPECT_EQ(writeCallback.mSuccessCount, kTestListLength + 1 /* an extra item for the empty list at the beginning */); EXPECT_EQ(writeCallback.mErrorCount, 0u); EXPECT_EQ(writeCallback.mOnDoneCount, 1u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); // // Stop the test if we detected an error. Otherwise, it'll be difficult to read the logs. @@ -281,7 +276,7 @@ TEST_F(TestWriteChunking, TestListChunking) // As the actual overhead may change, we will test over a few possible payload lengths, from 850 to MTU used in write clients. TEST_F(TestWriteChunking, TestBadChunking) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool atLeastOneRequestSent = false; bool atLeastOneRequestFailed = false; @@ -306,7 +301,7 @@ TEST_F(TestWriteChunking, TestBadChunking) gIterationCount = (uint32_t) i; - app::WriteClient writeClient(&mpContext->GetExchangeManager(), &writeCallback, Optional::Missing()); + app::WriteClient writeClient(&GetExchangeManager(), &writeCallback, Optional::Missing()); ByteSpan list[kTestListLength]; for (auto & item : list) @@ -335,14 +330,14 @@ TEST_F(TestWriteChunking, TestBadChunking) // for (int j = 0; j < 10 && writeCallback.mOnDoneCount == 0; j++) { - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); } EXPECT_EQ(writeCallback.mSuccessCount, kTestListLength + 1 /* an extra item for the empty list at the beginning */); EXPECT_EQ(writeCallback.mErrorCount, 0u); EXPECT_EQ(writeCallback.mOnDoneCount, 1u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); // // Stop the test if we detected an error. Otherwise, it'll be difficult to read the logs. @@ -352,7 +347,7 @@ TEST_F(TestWriteChunking, TestBadChunking) break; } } - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); EXPECT_TRUE(atLeastOneRequestSent && atLeastOneRequestFailed); emberAfClearDynamicEndpoint(0); } @@ -363,7 +358,7 @@ TEST_F(TestWriteChunking, TestBadChunking) */ TEST_F(TestWriteChunking, TestConflictWrite) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); // Initialize the ember side server logic InitDataModelHandler(); @@ -380,11 +375,11 @@ TEST_F(TestWriteChunking, TestConflictWrite) constexpr size_t kReserveSize = kMaxSecureSduLengthBytes - 128; TestWriteCallback writeCallback1; - app::WriteClient writeClient1(&mpContext->GetExchangeManager(), &writeCallback1, Optional::Missing(), + app::WriteClient writeClient1(&GetExchangeManager(), &writeCallback1, Optional::Missing(), static_cast(kReserveSize)); TestWriteCallback writeCallback2; - app::WriteClient writeClient2(&mpContext->GetExchangeManager(), &writeCallback2, Optional::Missing(), + app::WriteClient writeClient2(&GetExchangeManager(), &writeCallback2, Optional::Missing(), static_cast(kReserveSize)); ByteSpan list[kTestListLength]; @@ -402,7 +397,7 @@ TEST_F(TestWriteChunking, TestConflictWrite) err = writeClient2.SendWriteRequest(sessionHandle); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); { const TestWriteCallback * writeCallbackRef1 = &writeCallback1; @@ -426,7 +421,7 @@ TEST_F(TestWriteChunking, TestConflictWrite) EXPECT_EQ(writeCallbackRef2->mOnDoneCount, 1u); } - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); emberAfClearDynamicEndpoint(0); } @@ -437,7 +432,7 @@ TEST_F(TestWriteChunking, TestConflictWrite) */ TEST_F(TestWriteChunking, TestNonConflictWrite) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); // Initialize the ember side server logic InitDataModelHandler(); @@ -455,11 +450,11 @@ TEST_F(TestWriteChunking, TestNonConflictWrite) constexpr size_t kReserveSize = kMaxSecureSduLengthBytes - 128; TestWriteCallback writeCallback1; - app::WriteClient writeClient1(&mpContext->GetExchangeManager(), &writeCallback1, Optional::Missing(), + app::WriteClient writeClient1(&GetExchangeManager(), &writeCallback1, Optional::Missing(), static_cast(kReserveSize)); TestWriteCallback writeCallback2; - app::WriteClient writeClient2(&mpContext->GetExchangeManager(), &writeCallback2, Optional::Missing(), + app::WriteClient writeClient2(&GetExchangeManager(), &writeCallback2, Optional::Missing(), static_cast(kReserveSize)); ByteSpan list[kTestListLength]; @@ -477,7 +472,7 @@ TEST_F(TestWriteChunking, TestNonConflictWrite) err = writeClient2.SendWriteRequest(sessionHandle); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); { EXPECT_EQ(writeCallback1.mErrorCount, 0u); @@ -489,48 +484,19 @@ TEST_F(TestWriteChunking, TestNonConflictWrite) EXPECT_EQ(writeCallback2.mOnDoneCount, 1u); } - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); emberAfClearDynamicEndpoint(0); } -namespace TestTransactionalListInstructions { - -using PathStatus = std::pair; - -enum class Operations : uint8_t -{ - kNoop, - kShutdownWriteClient, -}; - -enum class ListData : uint8_t -{ - kNull, - kList, - kBadValue, -}; - -struct Instructions -{ - // The paths used in write request - std::vector paths; - // The type of content of the list, it should be an empty vector or its size should equals to the list of paths. - std::vector data; - // operations on OnListWriteBegin and OnListWriteEnd on the server side. - std::function onListWriteBeginActions; - // The expected status when OnListWriteEnd is called. In the same order as paths - std::vector expectedStatus; -}; - -void RunTest(TestContext * pContext, Instructions instructions) +void TestWriteChunking::RunTest(Instructions instructions) { CHIP_ERROR err = CHIP_NO_ERROR; - auto sessionHandle = pContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); TestWriteCallback writeCallback; std::unique_ptr writeClient = std::make_unique( - &pContext->GetExchangeManager(), &writeCallback, Optional::Missing(), + &GetExchangeManager(), &writeCallback, Optional::Missing(), static_cast(kMaxSecureSduLengthBytes - 128) /* use a smaller chunk so we only need a few attributes in the write request. */); @@ -598,9 +564,9 @@ void RunTest(TestContext * pContext, Instructions instructions) err = writeClient->SendWriteRequest(sessionHandle); EXPECT_EQ(err, CHIP_NO_ERROR); - pContext->GetIOContext().DriveIOUntil(sessionHandle->ComputeRoundTripTimeout(app::kExpectedIMProcessingTime) + - System::Clock::Seconds16(1), - [&]() { return pContext->GetExchangeManager().GetNumActiveExchanges() == 0; }); + GetIOContext().DriveIOUntil(sessionHandle->ComputeRoundTripTimeout(app::kExpectedIMProcessingTime) + + System::Clock::Seconds16(1), + [&]() { return GetExchangeManager().GetNumActiveExchanges() == 0; }); EXPECT_EQ(onGoingPath, app::ConcreteAttributePath()); EXPECT_EQ(status.size(), instructions.expectedStatus.size()); @@ -614,12 +580,8 @@ void RunTest(TestContext * pContext, Instructions instructions) testServer.mOnListWriteEnd = nullptr; } -} // namespace TestTransactionalListInstructions - TEST_F(TestWriteChunking, TestTransactionalList) { - using namespace TestTransactionalListInstructions; - // Initialize the ember side server logic InitDataModelHandler(); @@ -631,98 +593,88 @@ TEST_F(TestWriteChunking, TestTransactionalList) // Test 1: we should receive transaction notifications ChipLogProgress(Zcl, "Test 1: we should receive transaction notifications"); - RunTest(mpContext, - Instructions{ - .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, - .expectedStatus = { true }, - }); + RunTest(Instructions{ + .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, + .expectedStatus = { true }, + }); ChipLogProgress(Zcl, "Test 2: we should receive transaction notifications for incomplete list operations"); - RunTest( - mpContext, - Instructions{ - .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, - .onListWriteBeginActions = [&](const app::ConcreteAttributePath & aPath) { return Operations::kShutdownWriteClient; }, - .expectedStatus = { false }, - }); + RunTest(Instructions{ + .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, + .onListWriteBeginActions = [&](const app::ConcreteAttributePath & aPath) { return Operations::kShutdownWriteClient; }, + .expectedStatus = { false }, + }); ChipLogProgress(Zcl, "Test 3: we should receive transaction notifications for every list in the transaction"); - RunTest(mpContext, - Instructions{ - .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute), - ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute2) }, - .expectedStatus = { true, true }, - }); + RunTest(Instructions{ + .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute), + ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute2) }, + .expectedStatus = { true, true }, + }); ChipLogProgress(Zcl, "Test 4: we should receive transaction notifications with the status of each list"); - RunTest(mpContext, - Instructions{ - .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute), - ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute2) }, - .onListWriteBeginActions = - [&](const app::ConcreteAttributePath & aPath) { - if (aPath.mAttributeId == kTestListAttribute2) - { - return Operations::kShutdownWriteClient; - } - return Operations::kNoop; - }, - .expectedStatus = { true, false }, - }); + RunTest(Instructions{ + .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute), + ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute2) }, + .onListWriteBeginActions = + [&](const app::ConcreteAttributePath & aPath) { + if (aPath.mAttributeId == kTestListAttribute2) + { + return Operations::kShutdownWriteClient; + } + return Operations::kNoop; + }, + .expectedStatus = { true, false }, + }); ChipLogProgress(Zcl, "Test 5: transactional list callbacks will be called for nullable lists, test if it is handled correctly for " "null value before non null values"); - RunTest(mpContext, - Instructions{ - .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute), - ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, - .data = { ListData::kNull, ListData::kList }, - .expectedStatus = { true }, - }); + RunTest(Instructions{ + .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute), + ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, + .data = { ListData::kNull, ListData::kList }, + .expectedStatus = { true }, + }); ChipLogProgress(Zcl, "Test 6: transactional list callbacks will be called for nullable lists, test if it is handled correctly for " "null value after non null values"); - RunTest(mpContext, - Instructions{ - .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute), - ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, - .data = { ListData::kList, ListData::kNull }, - .expectedStatus = { true }, - }); + RunTest(Instructions{ + .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute), + ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, + .data = { ListData::kList, ListData::kNull }, + .expectedStatus = { true }, + }); ChipLogProgress(Zcl, "Test 7: transactional list callbacks will be called for nullable lists, test if it is handled correctly for " "null value between non null values"); - RunTest(mpContext, - Instructions{ - .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute), - ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute), - ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, - .data = { ListData::kList, ListData::kNull, ListData::kList }, - .expectedStatus = { true }, - }); + RunTest(Instructions{ + .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute), + ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute), + ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, + .data = { ListData::kList, ListData::kNull, ListData::kList }, + .expectedStatus = { true }, + }); ChipLogProgress(Zcl, "Test 8: transactional list callbacks will be called for nullable lists"); - RunTest(mpContext, - Instructions{ - .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, - .data = { ListData::kNull }, - .expectedStatus = { true }, - }); + RunTest(Instructions{ + .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, + .data = { ListData::kNull }, + .expectedStatus = { true }, + }); ChipLogProgress(Zcl, "Test 9: for nullable lists, we should receive notifications for unsuccessful writes when non-fatal occurred " "during processing the requests"); - RunTest(mpContext, - Instructions{ - .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, - .data = { ListData::kBadValue }, - .expectedStatus = { false }, - }); - - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + RunTest(Instructions{ + .paths = { ConcreteAttributePath(kTestEndpointId, Clusters::UnitTesting::Id, kTestListAttribute) }, + .data = { ListData::kBadValue }, + .expectedStatus = { false }, + }); + + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); emberAfClearDynamicEndpoint(0); } diff --git a/src/messaging/tests/MessagingContext.cpp b/src/messaging/tests/MessagingContext.cpp index 61565da1cd4ac0..c5bd53a2a7da86 100644 --- a/src/messaging/tests/MessagingContext.cpp +++ b/src/messaging/tests/MessagingContext.cpp @@ -304,9 +304,9 @@ Messaging::ExchangeContext * MessagingContext::NewExchangeToBob(Messaging::Excha return mExchangeManager.NewContext(GetSessionAliceToBob(), delegate, isInitiator); } -LoopbackTransportManager LoopbackMessagingContext::sLoopbackTransportManager; +LoopbackTransportManager * LoopbackMessagingContext::spLoopbackTransportManager = nullptr; -UDPTransportManager UDPMessagingContext::sUDPTransportManager; +UDPTransportManager * UDPMessagingContext::spUDPTransportManager = nullptr; void MessageCapturer::OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader, const SessionHandle & session, DuplicateMessage isDuplicate, diff --git a/src/messaging/tests/MessagingContext.h b/src/messaging/tests/MessagingContext.h index ab9912924e713c..2af05379706f2e 100644 --- a/src/messaging/tests/MessagingContext.h +++ b/src/messaging/tests/MessagingContext.h @@ -26,14 +26,13 @@ #include #include #include +#include #include #include #include #include #include -#include - #include namespace chip { @@ -207,94 +206,105 @@ class MessagingContext : public PlatformMemoryUser }; // LoopbackMessagingContext enriches MessagingContext with an async loopback transport -class LoopbackMessagingContext : public MessagingContext +class LoopbackMessagingContext : public ::testing::Test, public MessagingContext { public: virtual ~LoopbackMessagingContext() {} - // These functions wrap sLoopbackTransportManager methods - static auto & GetSystemLayer() { return sLoopbackTransportManager.GetSystemLayer(); } - static auto & GetLoopback() { return sLoopbackTransportManager.GetLoopback(); } - static auto & GetTransportMgr() { return sLoopbackTransportManager.GetTransportMgr(); } - static auto & GetIOContext() { return sLoopbackTransportManager.GetIOContext(); } + // These functions wrap spLoopbackTransportManager methods + static auto & GetSystemLayer() { return spLoopbackTransportManager->GetSystemLayer(); } + static auto & GetLoopback() { return spLoopbackTransportManager->GetLoopback(); } + static auto & GetTransportMgr() { return spLoopbackTransportManager->GetTransportMgr(); } + static auto & GetIOContext() { return spLoopbackTransportManager->GetIOContext(); } template static void DrainAndServiceIO(Ts... args) { - return sLoopbackTransportManager.DrainAndServiceIO(args...); + return spLoopbackTransportManager->DrainAndServiceIO(args...); } // Performs shared setup for all tests in the test suite static void SetUpTestSuite() { - CHIP_ERROR err = CHIP_NO_ERROR; - // TODO: use ASSERT_EQ, once transition to pw_unit_test is complete - VerifyOrDieWithMsg((err = chip::Platform::MemoryInit()) == CHIP_NO_ERROR, AppServer, - "Init CHIP memory failed: %" CHIP_ERROR_FORMAT, err.Format()); - VerifyOrDieWithMsg((err = sLoopbackTransportManager.Init()) == CHIP_NO_ERROR, AppServer, - "Init LoopbackTransportManager failed: %" CHIP_ERROR_FORMAT, err.Format()); + // Initialize memory. + ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); + // Instantiate the LoopbackTransportManager. + ASSERT_EQ(spLoopbackTransportManager, nullptr); + spLoopbackTransportManager = new LoopbackTransportManager(); + ASSERT_NE(spLoopbackTransportManager, nullptr); + // Initialize the LoopbackTransportManager. + ASSERT_EQ(spLoopbackTransportManager->Init(), CHIP_NO_ERROR); } // Performs shared teardown for all tests in the test suite static void TearDownTestSuite() { - sLoopbackTransportManager.Shutdown(); + // Shutdown the LoopbackTransportManager. + spLoopbackTransportManager->Shutdown(); + // Destroy the LoopbackTransportManager. + if (spLoopbackTransportManager != nullptr) + { + delete spLoopbackTransportManager; + spLoopbackTransportManager = nullptr; + } + // Shutdown memory. chip::Platform::MemoryShutdown(); } // Performs setup for each individual test in the test suite - virtual void SetUp() - { - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrDieWithMsg((err = MessagingContext::Init(&GetTransportMgr(), &GetIOContext())) == CHIP_NO_ERROR, AppServer, - "Init MessagingContext failed: %" CHIP_ERROR_FORMAT, err.Format()); - } + virtual void SetUp() { ASSERT_EQ(MessagingContext::Init(&GetTransportMgr(), &GetIOContext()), CHIP_NO_ERROR); } // Performs teardown for each individual test in the test suite virtual void TearDown() { MessagingContext::Shutdown(); } - static LoopbackTransportManager sLoopbackTransportManager; + static LoopbackTransportManager * spLoopbackTransportManager; }; // UDPMessagingContext enriches MessagingContext with an UDP transport -class UDPMessagingContext : public MessagingContext +class UDPMessagingContext : public ::testing::Test, public MessagingContext { public: virtual ~UDPMessagingContext() {} - static auto & GetSystemLayer() { return sUDPTransportManager.GetSystemLayer(); } - static auto & GetTransportMgr() { return sUDPTransportManager.GetTransportMgr(); } - static auto & GetIOContext() { return sUDPTransportManager.GetIOContext(); } + static auto & GetSystemLayer() { return spUDPTransportManager->GetSystemLayer(); } + static auto & GetTransportMgr() { return spUDPTransportManager->GetTransportMgr(); } + static auto & GetIOContext() { return spUDPTransportManager->GetIOContext(); } // Performs shared setup for all tests in the test suite static void SetUpTestSuite() { - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrDieWithMsg((err = chip::Platform::MemoryInit()) == CHIP_NO_ERROR, AppServer, - "Init CHIP memory failed: %" CHIP_ERROR_FORMAT, err.Format()); - VerifyOrDieWithMsg((err = sUDPTransportManager.Init()) == CHIP_NO_ERROR, AppServer, - "Init UDPTransportManager failed: %" CHIP_ERROR_FORMAT, err.Format()); + // Initialize memory. + ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); + // Instantiate the UDPTransportManager. + ASSERT_EQ(spUDPTransportManager, nullptr); + spUDPTransportManager = new UDPTransportManager(); + ASSERT_NE(spUDPTransportManager, nullptr); + // Initialize the UDPTransportManager. + ASSERT_EQ(spUDPTransportManager->Init(), CHIP_NO_ERROR); } // Performs shared teardown for all tests in the test suite static void TearDownTestSuite() { - sUDPTransportManager.Shutdown(); + // Shutdown the UDPTransportManager. + spUDPTransportManager->Shutdown(); + // Destroy the UDPTransportManager. + if (spUDPTransportManager != nullptr) + { + delete spUDPTransportManager; + spUDPTransportManager = nullptr; + } + // Shutdown memory. chip::Platform::MemoryShutdown(); } // Performs setup for each individual test in the test suite - virtual void SetUp() - { - CHIP_ERROR err = CHIP_NO_ERROR; - VerifyOrDieWithMsg((err = MessagingContext::Init(&GetTransportMgr(), &GetIOContext())) == CHIP_NO_ERROR, AppServer, - "Init MessagingContext failed: %" CHIP_ERROR_FORMAT, err.Format()); - } + virtual void SetUp() { ASSERT_EQ(MessagingContext::Init(&GetTransportMgr(), &GetIOContext()), CHIP_NO_ERROR); } // Performs teardown for each individual test in the test suite virtual void TearDown() { MessagingContext::Shutdown(); } - static UDPTransportManager sUDPTransportManager; + static UDPTransportManager * spUDPTransportManager; }; // Class that can be used to capture decrypted message traffic in tests using From d43b087f809263601e0a86c176276dda59d64ec7 Mon Sep 17 00:00:00 2001 From: Jeff Feasel Date: Thu, 20 Jun 2024 15:10:56 +0000 Subject: [PATCH 02/16] Modifed all tests that use LoopbackMessagingContext or AppContext. Moved LoopbackMessagingContext data to heap. --- docs/testing/unit_testing.md | 2 +- src/app/icd/server/tests/BUILD.gn | 2 + src/app/icd/server/tests/TestICDManager.cpp | 50 +- src/app/tests/BUILD.gn | 5 +- src/app/tests/TestAclAttribute.cpp | 47 +- src/app/tests/TestAclEvent.cpp | 56 +- src/app/tests/TestBufferedReadCallback.cpp | 35 +- src/app/tests/TestClusterStateCache.cpp | 22 +- src/app/tests/TestCommandInteraction.cpp | 322 +++-- src/app/tests/TestEventLogging.cpp | 22 +- src/app/tests/TestEventLoggingNoUTCTime.cpp | 17 +- src/app/tests/TestEventOverflow.cpp | 25 +- .../tests/TestFabricScopedEventLogging.cpp | 22 +- src/app/tests/TestInteractionModelEngine.cpp | 106 +- src/app/tests/TestReadInteraction.cpp | 1168 ++++++++--------- src/app/tests/TestReportScheduler.cpp | 56 +- src/app/tests/TestReportingEngine.cpp | 31 +- src/app/tests/TestTimedHandler.cpp | 47 +- src/app/tests/TestWriteInteraction.cpp | 336 +++-- src/controller/tests/TestEventChunking.cpp | 62 +- .../tests/TestEventNumberCaching.cpp | 54 +- src/controller/tests/TestReadChunking.cpp | 113 +- .../tests/TestServerCommandDispatch.cpp | 64 +- .../tests/data_model/TestCommands.cpp | 103 +- src/controller/tests/data_model/TestRead.cpp | 870 ++++++------ src/controller/tests/data_model/TestWrite.cpp | 94 +- src/messaging/tests/BUILD.gn | 1 + src/messaging/tests/MessagingContext.cpp | 164 +-- src/messaging/tests/MessagingContext.h | 99 +- .../tests/TestAbortExchangesForFabric.cpp | 10 +- src/messaging/tests/TestExchange.cpp | 12 +- src/messaging/tests/TestExchangeHolder.cpp | 13 +- src/messaging/tests/TestExchangeMgr.cpp | 10 +- src/messaging/tests/TestMessagingLayer.cpp | 15 +- .../tests/TestReliableMessageProtocol.cpp | 26 +- .../secure_channel/tests/TestCASESession.cpp | 6 +- .../tests/TestMessageCounterManager.cpp | 11 +- .../secure_channel/tests/TestPASESession.cpp | 10 +- .../tests/TestSessionManagerDispatch.cpp | 2 +- 39 files changed, 1705 insertions(+), 2405 deletions(-) diff --git a/docs/testing/unit_testing.md b/docs/testing/unit_testing.md index 64046a4c21a9d6..568bfbf9af3326 100644 --- a/docs/testing/unit_testing.md +++ b/docs/testing/unit_testing.md @@ -218,7 +218,7 @@ your overriding function make sure to check `HasFailure()` and return if the parent function failed. If you don't override any of the setup/teardown functions, you can simply make a -type alias: `using YourTestContext = Test::AppContextPW;` instead of defining +type alias: `using YourTestContext = Test::AppContext;` instead of defining your own text context class. ## Best practices diff --git a/src/app/icd/server/tests/BUILD.gn b/src/app/icd/server/tests/BUILD.gn index e96954a97dde58..a5d0fb83090f5f 100644 --- a/src/app/icd/server/tests/BUILD.gn +++ b/src/app/icd/server/tests/BUILD.gn @@ -31,6 +31,8 @@ chip_test_suite("tests") { public_deps = [ "${chip_root}/src/app/icd/server:manager", "${chip_root}/src/app/icd/server:monitoring-table", + "${chip_root}/src/app/tests:helpers", + "${chip_root}/src/controller/data_model", "${chip_root}/src/lib/support:test_utils", "${chip_root}/src/lib/support:testing", "${chip_root}/src/messaging/tests:helpers", diff --git a/src/app/icd/server/tests/TestICDManager.cpp b/src/app/icd/server/tests/TestICDManager.cpp index 45e781685e6d31..b2c5918ba4ee04 100644 --- a/src/app/icd/server/tests/TestICDManager.cpp +++ b/src/app/icd/server/tests/TestICDManager.cpp @@ -15,6 +15,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include + #include #include #include @@ -23,13 +25,12 @@ #include #include #include +#include #include -#include #include #include #include #include -#include #include using namespace chip; @@ -122,18 +123,16 @@ class TestSubscriptionsInfoProvider : public SubscriptionsInfoProvider bool mHasPersistedSubscription = false; }; -System::Clock::Internal::MockClock * pMockClock = nullptr; -System::Clock::ClockBase * pRealClock = nullptr; -chip::Test::LoopbackMessagingContext * pMessagingContext = nullptr; +System::Clock::Internal::MockClock * pMockClock = nullptr; +System::Clock::ClockBase * pRealClock = nullptr; } // namespace namespace chip { namespace app { -class TestICDManager : public ::testing::Test +class TestICDManager : public Test::AppContext { - public: /* * Advance the test Mock clock time by the amout passed in argument @@ -145,7 +144,7 @@ class TestICDManager : public ::testing::Test static void AdvanceClockAndRunEventLoop(Milliseconds64 time) { pMockClock->AdvanceMonotonic(time); - pMessagingContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); } // Performs shared setup for all tests in the test suite @@ -157,16 +156,10 @@ class TestICDManager : public ::testing::Test ASSERT_NE(pMockClock, nullptr); } - if (pMessagingContext == nullptr) - { - pMessagingContext = new LoopbackMessagingContext(); - ASSERT_NE(pMessagingContext, nullptr); - } - - pMessagingContext->SetUpTestSuite(); - ASSERT_EQ(chip::DeviceLayer::PlatformMgr().InitChipStack(), CHIP_NO_ERROR); + AppContext::SetUpTestSuite(); + VerifyOrReturn(!HasFailure()); - DeviceLayer::SetSystemLayerForTesting(&(pMessagingContext->GetSystemLayer())); + DeviceLayer::SetSystemLayerForTesting(&GetSystemLayer()); pRealClock = &SystemClock(); Clock::Internal::SetSystemClockForTesting(pMockClock); } @@ -177,8 +170,7 @@ class TestICDManager : public ::testing::Test Clock::Internal::SetSystemClockForTesting(pRealClock); DeviceLayer::SetSystemLayerForTesting(nullptr); - DeviceLayer::PlatformMgr().Shutdown(); - pMessagingContext->TearDownTestSuite(); + AppContext::TearDownTestSuite(); if (pMockClock != nullptr) { @@ -186,31 +178,25 @@ class TestICDManager : public ::testing::Test pMockClock = nullptr; } - if (pMessagingContext != nullptr) - { - delete pMessagingContext; - pMessagingContext = nullptr; - } - pRealClock = nullptr; } // Performs setup for each individual test in the test suite void SetUp() override { - pMessagingContext->SetUp(); + AppContext::SetUp(); + VerifyOrReturn(!HasFailure()); mICDStateObserver.ResetAll(); mICDManager.RegisterObserver(&mICDStateObserver); - mICDManager.Init(&testStorage, &(pMessagingContext->GetFabricTable()), &mKeystore, - &(pMessagingContext->GetExchangeManager()), &mSubInfoProvider); + mICDManager.Init(&testStorage, &GetFabricTable(), &mKeystore, &GetExchangeManager(), &mSubInfoProvider); } // Performs teardown for each individual test in the test suite void TearDown() override { mICDManager.Shutdown(); - pMessagingContext->TearDown(); + AppContext::TearDown(); } TestSessionKeystoreImpl mKeystore; @@ -574,8 +560,7 @@ TEST_F(TestICDManager, TestICDCounter) // Shut down and reinit ICDManager to increment counter mICDManager.Shutdown(); - mICDManager.Init(&(testStorage), &(pMessagingContext->GetFabricTable()), &(mKeystore), - &(pMessagingContext->GetExchangeManager()), &(mSubInfoProvider)); + mICDManager.Init(&(testStorage), &GetFabricTable(), &(mKeystore), &GetExchangeManager(), &(mSubInfoProvider)); mICDManager.RegisterObserver(&(mICDStateObserver)); EXPECT_EQ(counter + ICDConfigurationData::kICDCounterPersistenceIncrement, @@ -980,8 +965,7 @@ TEST_F(TestICDManager, TestICDStateObserverOnICDModeChangeOnInit) // Shut down and reinit ICDManager - We should go to LIT mode since we have a registration mICDManager.Shutdown(); mICDManager.RegisterObserver(&(mICDStateObserver)); - mICDManager.Init(&testStorage, &(pMessagingContext->GetFabricTable()), &mKeystore, &(pMessagingContext->GetExchangeManager()), - &mSubInfoProvider); + mICDManager.Init(&testStorage, &GetFabricTable(), &mKeystore, &GetExchangeManager(), &mSubInfoProvider); // We have a registration, transition to LIT mode EXPECT_TRUE(mICDStateObserver.mOnICDModeChangeCalled); diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index e8860f01565141..1c1f1bcc32c94c 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -40,7 +40,10 @@ static_library("helpers") { "${chip_root}/src/transport/raw/tests:helpers", ] - public_deps = [ "${chip_root}/src/messaging/tests:helpers" ] + public_deps = [ + "${chip_root}/src/lib/support/tests:pw-test-macros", + "${chip_root}/src/messaging/tests:helpers", + ] } source_set("binding-test-srcs") { diff --git a/src/app/tests/TestAclAttribute.cpp b/src/app/tests/TestAclAttribute.cpp index 8ff88967deb5b0..9395603218de69 100644 --- a/src/app/tests/TestAclAttribute.cpp +++ b/src/app/tests/TestAclAttribute.cpp @@ -109,50 +109,31 @@ class MockInteractionModelApp : public chip::app::ReadClient::Callback namespace chip { namespace app { -class TestAclAttribute : public ::testing::Test +class TestAclAttribute : public chip::Test::AppContext { public: - static void SetUpTestSuite() - { - - mpTestContext = new chip::Test::AppContext; - mpTestContext->SetUpTestSuite(); - } - static void TearDownTestSuite() - { - mpTestContext->TearDownTestSuite(); - delete mpTestContext; - } - void SetUp() override { - mpTestContext->SetUp(); + chip::Test::AppContext::SetUp(); Access::GetAccessControl().Finish(); Access::GetAccessControl().Init(GetTestAccessControlDelegate(), gDeviceTypeResolver); } - void TearDown() override { mpTestContext->TearDown(); } - - static chip::Test::AppContext * mpTestContext; }; -chip::Test::AppContext * TestAclAttribute::mpTestContext = nullptr; - // Read Client sends a malformed subscribe request, interaction model engine fails to parse the request and generates a status // report to client, and client is closed. TEST_F(TestAclAttribute, TestACLDeniedAttribute) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; @@ -164,13 +145,13 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) attributePathParams[1].mClusterId = chip::Test::kTestDeniedClusterId1; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); EXPECT_FALSE(delegate.mGotReport); delegate.mError = CHIP_NO_ERROR; @@ -178,7 +159,7 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) } { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; @@ -189,13 +170,13 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) attributePathParams[1].mClusterId = chip::Test::kTestDeniedClusterId2; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); EXPECT_FALSE(delegate.mGotReport); delegate.mError = CHIP_NO_ERROR; @@ -203,7 +184,7 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) } { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); chip::app::AttributePathParams attributePathParams[2]; @@ -215,13 +196,13 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) attributePathParams[1].mClusterId = chip::Test::kTestClusterId; attributePathParams[1].mAttributeId = 2; - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mError, CHIP_NO_ERROR); EXPECT_TRUE(delegate.mGotReport); EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); @@ -231,7 +212,7 @@ TEST_F(TestAclAttribute, TestACLDeniedAttribute) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } } // namespace app } // namespace chip diff --git a/src/app/tests/TestAclEvent.cpp b/src/app/tests/TestAclEvent.cpp index 014625ad628b65..32ed5fbe346f8d 100644 --- a/src/app/tests/TestAclEvent.cpp +++ b/src/app/tests/TestAclEvent.cpp @@ -172,21 +172,9 @@ class MockInteractionModelApp : public chip::app::ReadClient::Callback namespace chip { namespace app { -class TestAclEvent : public ::testing::Test +class TestAclEvent : public chip::Test::AppContext { public: - static void SetUpTestSuite() - { - - mpTestContext = new chip::Test::AppContext; - mpTestContext->SetUpTestSuite(); - } - static void TearDownTestSuite() - { - mpTestContext->TearDownTestSuite(); - delete mpTestContext; - } - // Performs setup for each individual test in the test suite void SetUp() override { @@ -196,10 +184,10 @@ class TestAclEvent : public ::testing::Test { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - mpTestContext->SetUp(); + chip::Test::AppContext::SetUp(); ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); - chip::app::EventManagement::CreateEventManagement(&mpTestContext->GetExchangeManager(), ArraySize(logStorageResources), + chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); Access::GetAccessControl().Finish(); @@ -210,21 +198,17 @@ class TestAclEvent : public ::testing::Test void TearDown() override { chip::app::EventManagement::DestroyEventManagement(); - mpTestContext->TearDown(); + chip::Test::AppContext::TearDown(); } - static chip::Test::AppContext * mpTestContext; - private: chip::MonotonicallyIncreasingCounter mEventCounter; }; -chip::Test::AppContext * TestAclEvent::mpTestContext = nullptr; - TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_FALSE(rm->TestGetCountRetransTable()); @@ -232,9 +216,7 @@ TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); // A custom AccessControl::Delegate has been installed that grants privilege to any cluster except the test cluster. // When reading events with concrete paths without enough privilege, we will get a EventStatusIB @@ -244,7 +226,7 @@ TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) eventPathParams[0].mClusterId = chip::Test::kTestDeniedClusterId2; eventPathParams[0].mEventId = kTestEventIdDebug; - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mEventPathParamsListSize = 1; readPrepareParams.mEventNumber.SetValue(1); @@ -252,12 +234,12 @@ TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) MockInteractionModelApp delegate; EXPECT_FALSE(delegate.mGotEventResponse); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotEventResponse); EXPECT_TRUE(delegate.mNumReadEventFailureStatusReceived); @@ -274,7 +256,7 @@ TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) eventPathParams[0].mEndpointId = kTestEndpointId; eventPathParams[0].mClusterId = chip::Test::kTestDeniedClusterId2; - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mEventPathParamsListSize = 1; readPrepareParams.mEventNumber.SetValue(1); @@ -282,12 +264,12 @@ TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) MockInteractionModelApp delegate; EXPECT_FALSE(delegate.mGotEventResponse); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_FALSE(delegate.mGotEventResponse); EXPECT_FALSE(delegate.mNumReadEventFailureStatusReceived); EXPECT_FALSE(delegate.mReadError); @@ -301,7 +283,7 @@ TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) chip::app::EventPathParams eventPathParams[1]; eventPathParams[0].mEndpointId = kTestEndpointId; - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mEventPathParamsListSize = 1; readPrepareParams.mEventNumber.SetValue(1); @@ -309,12 +291,12 @@ TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) MockInteractionModelApp delegate; EXPECT_FALSE(delegate.mGotEventResponse); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotEventResponse); EXPECT_FALSE(delegate.mNumReadEventFailureStatusReceived); EXPECT_FALSE(delegate.mReadError); @@ -333,7 +315,7 @@ TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) eventPathParams[1].mClusterId = kTestClusterId2; eventPathParams[1].mEventId = kTestEventIdCritical; - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mEventPathParamsListSize = 1; readPrepareParams.mEventNumber.SetValue(1); @@ -341,19 +323,19 @@ TEST_F(TestAclEvent, TestReadRoundtripWithEventStatusIBInEventReport) MockInteractionModelApp delegate; EXPECT_FALSE(delegate.mGotEventResponse); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotEventResponse); EXPECT_TRUE(delegate.mNumReadEventFailureStatusReceived); EXPECT_FALSE(delegate.mReadError); } EXPECT_FALSE(engine->GetNumActiveReadClients()); engine->Shutdown(); - EXPECT_FALSE(mpTestContext->GetExchangeManager().GetNumActiveExchanges()); + EXPECT_FALSE(GetExchangeManager().GetNumActiveExchanges()); } } // namespace app diff --git a/src/app/tests/TestBufferedReadCallback.cpp b/src/app/tests/TestBufferedReadCallback.cpp index 91836675db25f4..c16983c9c5605f 100644 --- a/src/app/tests/TestBufferedReadCallback.cpp +++ b/src/app/tests/TestBufferedReadCallback.cpp @@ -31,7 +31,6 @@ #include #include -using TestContext = chip::Test::AppContext; using namespace chip::app; using namespace chip; @@ -65,39 +64,7 @@ struct ValidationInstruction using InstructionListType = std::vector; -class TestBufferedReadCallback : public ::testing::Test -{ -public: - static void SetUpTestSuite() - { - mpTestContext = new TestContext; - mpTestContext->SetUpTestSuite(); - } - static void TearDownTestSuite() - { - mpTestContext->TearDownTestSuite(); - if (mpTestContext != nullptr) - { - delete mpTestContext; - } - } - void SetUp() override - { - if (mpTestContext != nullptr) - { - mpTestContext->SetUp(); - } - } - void TearDown() override - { - if (mpTestContext != nullptr) - { - mpTestContext->TearDown(); - } - } - static TestContext * mpTestContext; -}; -TestContext * TestBufferedReadCallback::mpTestContext = nullptr; +using TestBufferedReadCallback = chip::Test::AppContext; class DataSeriesValidator : public BufferedReadCallback::Callback { diff --git a/src/app/tests/TestClusterStateCache.cpp b/src/app/tests/TestClusterStateCache.cpp index b4f41df2278b14..a060fbd89c7b47 100644 --- a/src/app/tests/TestClusterStateCache.cpp +++ b/src/app/tests/TestClusterStateCache.cpp @@ -37,7 +37,6 @@ #include #include -using TestContext = chip::Test::AppContext; using namespace chip::app; using namespace chip; @@ -108,26 +107,7 @@ uint8_t AttributeInstruction::sInstructionId = 0; using AttributeInstructionListType = std::vector; -class TestClusterStateCache : public ::testing::Test -{ -public: - static void SetUpTestSuite() - { - mpTestContext = new TestContext; - mpTestContext->SetUpTestSuite(); - } - static void TearDownTestSuite() - { - mpTestContext->TearDownTestSuite(); - delete mpTestContext; - } - - void SetUp() override { mpTestContext->SetUp(); } - void TearDown() override { mpTestContext->TearDown(); } - - static TestContext * mpTestContext; -}; -TestContext * TestClusterStateCache::mpTestContext = nullptr; +using TestClusterStateCache = chip::Test::AppContext; class ForwardedDataCallbackValidator final { diff --git a/src/app/tests/TestCommandInteraction.cpp b/src/app/tests/TestCommandInteraction.cpp index 8c2537a925e9b1..6212d696c85c45 100644 --- a/src/app/tests/TestCommandInteraction.cpp +++ b/src/app/tests/TestCommandInteraction.cpp @@ -50,7 +50,6 @@ #include #include -using TestContext = chip::Test::AppContext; using namespace chip::Protocols; namespace { @@ -357,25 +356,9 @@ class MockCommandHandlerCallback : public CommandHandlerImpl::Callback int onFinalCalledTimes = 0; } mockCommandHandlerDelegate; -class TestCommandInteraction : public ::testing::Test +class TestCommandInteraction : public chip::Test::AppContext { public: - static void SetUpTestSuite() - { - mpTestContext = new TestContext; - mpTestContext->SetUpTestSuite(); - } - static void TearDownTestSuite() - { - mpTestContext->TearDownTestSuite(); - delete mpTestContext; - } - - void SetUp() override { mpTestContext->SetUp(); } - void TearDown() override { mpTestContext->TearDown(); } - - static TestContext * mpTestContext; - static size_t GetNumActiveCommandResponderObjects() { return chip::app::InteractionModelEngine::GetInstance()->mCommandResponderObjs.Allocated(); @@ -443,7 +426,6 @@ class TestCommandInteraction : public ::testing::Test const ConcreteCommandPath & aRequestCommandPath, uint32_t aSizeToLeaveInBuffer); static void ValidateCommandHandlerEncodeInvokeResponseMessage(bool aNeedStatusCode); }; -TestContext * TestCommandInteraction::mpTestContext = nullptr; class TestExchangeDelegate : public Messaging::ExchangeDelegate { @@ -686,19 +668,19 @@ void TestCommandInteraction::ValidateCommandHandlerEncodeInvokeResponseMessage(b TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage1) { mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); AddInvokeRequestData(&commandSender); asyncCommand = false; - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); + DrainAndServiceIO(); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 0); @@ -718,19 +700,19 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage1) PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::StatusResponse); - chip::Test::MessageCapturer messageLog(*mpTestContext); + chip::Test::MessageCapturer messageLog(*this); 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(*mpTestContext, commandSender.mExchangeCtx.Get()); + PretendWeGotReplyFromServer(*this, commandSender.mExchangeCtx.Get()); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(commandSender.OnMessageReceived(commandSender.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), CHIP_IM_GLOBAL_STATUS(Busy)); @@ -740,16 +722,16 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage1) EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 1); EXPECT_EQ(commandSender.GetInvokeResponseMessageCount(), 0u); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Client sent status report with invalid action, server's exchange has been closed, so all it sent is an MRP Ack - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); CheckForInvalidAction(messageLog); EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Command Sender sends invoke request, command handler drops invoke response, then test injects unknown message to client, @@ -757,19 +739,19 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage1) TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage2) { mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); AddInvokeRequestData(&commandSender); asyncCommand = false; - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); + DrainAndServiceIO(); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 0); @@ -788,19 +770,19 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage2) PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::ReportData); - chip::Test::MessageCapturer messageLog(*mpTestContext); + chip::Test::MessageCapturer messageLog(*this); 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(*mpTestContext, commandSender.mExchangeCtx.Get()); + PretendWeGotReplyFromServer(*this, commandSender.mExchangeCtx.Get()); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(commandSender.OnMessageReceived(commandSender.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), CHIP_ERROR_INVALID_MESSAGE_TYPE); @@ -809,16 +791,16 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage2) EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 1); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Client sent status report with invalid action, server's exchange has been closed, so all it sent is an MRP Ack - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); CheckForInvalidAction(messageLog); EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Command Sender sends invoke request, command handler drops invoke response, then test injects malformed invoke response @@ -826,19 +808,19 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage2) TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage3) { mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); AddInvokeRequestData(&commandSender); asyncCommand = false; - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); + DrainAndServiceIO(); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 0); @@ -857,18 +839,18 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage3) PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::InvokeCommandResponse); - chip::Test::MessageCapturer messageLog(*mpTestContext); + chip::Test::MessageCapturer messageLog(*this); 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(*mpTestContext, commandSender.mExchangeCtx.Get()); + PretendWeGotReplyFromServer(*this, commandSender.mExchangeCtx.Get()); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(commandSender.OnMessageReceived(commandSender.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), CHIP_ERROR_END_OF_TLV); @@ -877,16 +859,16 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage3) EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 1); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Client sent status report with invalid action, server's exchange has been closed, so all it sent is an MRP Ack - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); CheckForInvalidAction(messageLog); EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Command Sender sends invoke request, command handler drops invoke response, then test injects malformed status response to @@ -894,19 +876,19 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage3) TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage4) { mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); AddInvokeRequestData(&commandSender); asyncCommand = false; - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); + DrainAndServiceIO(); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 0); @@ -924,18 +906,18 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage4) PayloadHeader payloadHeader; payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::StatusResponse); - chip::Test::MessageCapturer messageLog(*mpTestContext); + chip::Test::MessageCapturer messageLog(*this); 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(*mpTestContext, commandSender.mExchangeCtx.Get()); + PretendWeGotReplyFromServer(*this, commandSender.mExchangeCtx.Get()); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(commandSender.OnMessageReceived(commandSender.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), CHIP_ERROR_END_OF_TLV); @@ -944,24 +926,24 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandInvalidMessage4) EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 1); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Client sent status report with invalid action, server's exchange has been closed, so all it sent is an MRP Ack - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); CheckForInvalidAction(messageLog); EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } TEST_F(TestCommandInteraction, TestCommandSender_WithWrongState) { - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_ERROR_INCORRECT_STATE); } TEST_F(TestCommandInteraction, TestCommandHandler_WithWrongState) @@ -986,14 +968,14 @@ TEST_F(TestCommandInteraction, TestCommandHandler_WithWrongState) TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandSender_WithSendCommand) { - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); AddInvokeRequestData(&commandSender); - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); GenerateInvokeResponse(buf, kTestCommandIdWithData); bool moreChunkedMessages = false; @@ -1024,7 +1006,7 @@ TEST_F(TestCommandInteraction, TestCommandHandler_WithSendEmptyCommand) TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandSender_WithProcessReceivedMsg) { - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); @@ -1040,8 +1022,8 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandSender_ExtendableApiWithP mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, - &mpTestContext->GetExchangeManager(), &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &GetExchangeManager(), + &pendingResponseTracker); uint16_t mockCommandRef = 1; pendingResponseTracker.Add(mockCommandRef); @@ -1067,8 +1049,8 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandSender_ExtendableApiWithP mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, - &mpTestContext->GetExchangeManager(), &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &GetExchangeManager(), + &pendingResponseTracker); uint16_t mockCommandRef = 1; pendingResponseTracker.Add(mockCommandRef); @@ -1096,8 +1078,8 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandSender_ValidateSecondLarg { mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, - &mpTestContext->GetExchangeManager(), &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &GetExchangeManager(), + &pendingResponseTracker); app::CommandSender::AddRequestDataParameters addRequestDataParams; @@ -1123,10 +1105,10 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandSender_ValidateSecondLarg EXPECT_EQ(commandSender.AddRequestData(commandPathParams, requestData, addRequestDataParams), CHIP_ERROR_NO_MEMORY); // Confirm that we can still send out a request with the first command. - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); EXPECT_EQ(commandSender.GetInvokeResponseMessageCount(), 0u); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(mockCommandSenderExtendedDelegate.onResponseCalledTimes, 1); EXPECT_EQ(mockCommandSenderExtendedDelegate.onFinalCalledTimes, 1); @@ -1176,13 +1158,13 @@ TEST_F(TestCommandInteraction, TestCommandHandlerInvalidMessageSync) { mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); chip::isCommandDispatched = false; AddInvalidInvokeRequestData(&commandSender); - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_FALSE(chip::isCommandDispatched); EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 0); @@ -1190,7 +1172,7 @@ TEST_F(TestCommandInteraction, TestCommandHandlerInvalidMessageSync) EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 1); EXPECT_EQ(mockCommandSenderDelegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommandInteraction, TestCommandHandlerCommandEncodeExternalFailure) @@ -1317,18 +1299,18 @@ TEST_F(TestCommandInteraction, TestCommandSenderLegacyCallbackUnsupportedCommand { mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); AddInvokeRequestData(&commandSender, kTestNonExistCommandId); - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); 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); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // Because UnsupportedCommand is a path specific error we will expect it to come via on response when using Extended Path. @@ -1336,25 +1318,25 @@ TEST_F(TestCommandInteraction, TestCommandSender_ExtendableCallbackUnsupportedCo { mockCommandSenderExtendedDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderExtendedDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderExtendedDelegate, &GetExchangeManager()); AddInvokeRequestData(&commandSender, kTestNonExistCommandId); - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(mockCommandSenderExtendedDelegate.onResponseCalledTimes, 1); EXPECT_EQ(mockCommandSenderExtendedDelegate.onFinalCalledTimes, 1); EXPECT_EQ(mockCommandSenderExtendedDelegate.onErrorCalledTimes, 0); EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommandInteraction, TestCommandSenderLegacyCallbackBuildingBatchCommandFails) { mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); app::CommandSender::PrepareCommandParameters prepareCommandParams; app::CommandSender::FinishCommandParameters finishCommandParams; prepareCommandParams.SetStartDataStruct(true).SetCommandRef(0); @@ -1376,15 +1358,15 @@ TEST_F(TestCommandInteraction, TestCommandSenderLegacyCallbackBuildingBatchComma EXPECT_EQ(commandSender.PrepareCommand(commandPathParams, prepareCommandParams), CHIP_ERROR_INCORRECT_STATE); EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommandInteraction, TestCommandSender_ExtendableCallbackBuildingBatchDuplicateCommandRefFails) { mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, - &mpTestContext->GetExchangeManager(), &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &GetExchangeManager(), + &pendingResponseTracker); app::CommandSender::PrepareCommandParameters prepareCommandParams; app::CommandSender::FinishCommandParameters finishCommandParams; @@ -1404,15 +1386,15 @@ TEST_F(TestCommandInteraction, TestCommandSender_ExtendableCallbackBuildingBatch EXPECT_EQ(commandSender.PrepareCommand(commandPathParams, prepareCommandParams), CHIP_ERROR_INVALID_ARGUMENT); EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommandInteraction, TestCommandSender_ExtendableCallbackBuildingBatchCommandSuccess) { mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, - &mpTestContext->GetExchangeManager(), &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &GetExchangeManager(), + &pendingResponseTracker); app::CommandSender::PrepareCommandParameters prepareCommandParams; app::CommandSender::FinishCommandParameters finishCommandParams; @@ -1440,20 +1422,20 @@ TEST_F(TestCommandInteraction, TestCommandSender_ExtendableCallbackBuildingBatch EXPECT_EQ(commandSender.FinishCommand(finishCommandParams), CHIP_NO_ERROR); EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommandInteraction, TestCommandSenderCommandSuccessResponseFlow) { mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); AddInvokeRequestData(&commandSender); - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); EXPECT_EQ(commandSender.GetInvokeResponseMessageCount(), 0u); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(mockCommandSenderDelegate.onResponseCalledTimes, 1); EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 1); @@ -1462,76 +1444,76 @@ TEST_F(TestCommandInteraction, TestCommandSenderCommandSuccessResponseFlow) EXPECT_EQ(commandSender.GetInvokeResponseMessageCount(), 1u); EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommandInteraction, TestCommandSenderCommandAsyncSuccessResponseFlow) { mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); AddInvokeRequestData(&commandSender); asyncCommand = true; - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); 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); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 2u); // Decrease CommandHandler refcount and send response asyncCommandHandle = nullptr; - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); 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); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommandInteraction, TestCommandSenderCommandSpecificResponseFlow) { mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); AddInvokeRequestData(&commandSender, kTestCommandIdCommandSpecificResponse); - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); 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); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommandInteraction, TestCommandSenderCommandFailureResponseFlow) { mockCommandSenderDelegate.ResetCounter(); - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); AddInvokeRequestData(&commandSender, kTestNonExistCommandId); - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); 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); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommandInteraction, TestCommandSenderAbruptDestruction) @@ -1546,13 +1528,13 @@ TEST_F(TestCommandInteraction, TestCommandSenderAbruptDestruction) mockCommandSenderDelegate.ResetCounter(); { - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); AddInvokeRequestData(&commandSender, kTestCommandIdCommandSpecificResponse); - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // // No callbacks should be invoked yet - let's validate that. @@ -1561,13 +1543,13 @@ TEST_F(TestCommandInteraction, TestCommandSenderAbruptDestruction) EXPECT_EQ(mockCommandSenderDelegate.onFinalCalledTimes, 0); EXPECT_EQ(mockCommandSenderDelegate.onErrorCalledTimes, 0); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 1u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 1u); } // // Upon the sender being destructed by the application, our exchange should get cleaned up too. // - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); } @@ -1578,8 +1560,8 @@ TEST_F(TestCommandInteraction, TestCommandHandler_RejectMultipleIdenticalCommand isCommandDispatched = false; mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, - &mpTestContext->GetExchangeManager(), &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &GetExchangeManager(), + &pendingResponseTracker); app::CommandSender::ConfigParameters configParameters; configParameters.SetRemoteMaxPathsPerInvoke(2); @@ -1602,9 +1584,9 @@ TEST_F(TestCommandInteraction, TestCommandHandler_RejectMultipleIdenticalCommand EXPECT_EQ(CHIP_NO_ERROR, commandSender.FinishCommand(finishCommandParams)); } - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(mockCommandSenderExtendedDelegate.onResponseCalledTimes, 0); EXPECT_EQ(mockCommandSenderExtendedDelegate.onFinalCalledTimes, 1); @@ -1612,7 +1594,7 @@ TEST_F(TestCommandInteraction, TestCommandHandler_RejectMultipleIdenticalCommand EXPECT_FALSE(chip::isCommandDispatched); EXPECT_EQ(GetNumActiveCommandResponderObjects(), 0u); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } #if CONFIG_BUILD_FOR_HOST_UNIT_TEST @@ -1623,8 +1605,8 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_RejectsMultipleCo isCommandDispatched = false; mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, - &mpTestContext->GetExchangeManager(), &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &GetExchangeManager(), + &pendingResponseTracker); app::CommandSender::ConfigParameters configParameters; configParameters.SetRemoteMaxPathsPerInvoke(2); @@ -1683,8 +1665,8 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_RejectMultipleCom mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, - &mpTestContext->GetExchangeManager(), &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &GetExchangeManager(), + &pendingResponseTracker); app::CommandSender::ConfigParameters configParameters; configParameters.SetRemoteMaxPathsPerInvoke(2); @@ -1735,8 +1717,8 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_AcceptMultipleCom mockCommandSenderExtendedDelegate.ResetCounter(); PendingResponseTrackerImpl pendingResponseTracker; - app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, - &mpTestContext->GetExchangeManager(), &pendingResponseTracker); + app::CommandSender commandSender(kCommandSenderTestOnlyMarker, &mockCommandSenderExtendedDelegate, &GetExchangeManager(), + &pendingResponseTracker); app::CommandSender::ConfigParameters configParameters; configParameters.SetRemoteMaxPathsPerInvoke(2); @@ -1875,15 +1857,15 @@ TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_FillUpInvokeRespo TEST_F_FROM_FIXTURE(TestCommandInteraction, TestCommandHandler_ReleaseWithExchangeClosed) { - app::CommandSender commandSender(&mockCommandSenderDelegate, &mpTestContext->GetExchangeManager()); + app::CommandSender commandSender(&mockCommandSenderDelegate, &GetExchangeManager()); AddInvokeRequestData(&commandSender); asyncCommandHandle = nullptr; asyncCommand = true; - EXPECT_EQ(commandSender.SendCommandRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(commandSender.SendCommandRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Verify that async command handle has been allocated ASSERT_NE(asyncCommandHandle.Get(), nullptr); diff --git a/src/app/tests/TestEventLogging.cpp b/src/app/tests/TestEventLogging.cpp index 931b706024c740..93e3b905670de3 100644 --- a/src/app/tests/TestEventLogging.cpp +++ b/src/app/tests/TestEventLogging.cpp @@ -53,19 +53,9 @@ static uint8_t gInfoEventBuffer[120]; static uint8_t gCritEventBuffer[120]; static chip::app::CircularEventBuffer gCircularEventBuffer[3]; -class TestEventLogging : public ::testing::Test +class TestEventLogging : public chip::Test::AppContext { public: - static void SetUpTestSuite() - { - mpTestContext = new chip::Test::AppContext; - mpTestContext->SetUpTestSuite(); - } - static void TearDownTestSuite() - { - mpTestContext->TearDownTestSuite(); - delete mpTestContext; - } // Performs setup for each individual test in the test suite void SetUp() override { @@ -75,9 +65,9 @@ class TestEventLogging : public ::testing::Test { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - mpTestContext->SetUp(); + chip::Test::AppContext::SetUp(); ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); - chip::app::EventManagement::CreateEventManagement(&mpTestContext->GetExchangeManager(), ArraySize(logStorageResources), + chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); } @@ -85,17 +75,13 @@ class TestEventLogging : public ::testing::Test void TearDown() override { chip::app::EventManagement::DestroyEventManagement(); - mpTestContext->TearDown(); + chip::Test::AppContext::TearDown(); } - static chip::Test::AppContext * mpTestContext; - private: chip::MonotonicallyIncreasingCounter mEventCounter; }; -chip::Test::AppContext * TestEventLogging::mpTestContext = nullptr; - void ENFORCE_FORMAT(1, 2) SimpleDumpWriter(const char * aFormat, ...) { va_list args; diff --git a/src/app/tests/TestEventLoggingNoUTCTime.cpp b/src/app/tests/TestEventLoggingNoUTCTime.cpp index 907a85982c1155..80176a58c8be54 100644 --- a/src/app/tests/TestEventLoggingNoUTCTime.cpp +++ b/src/app/tests/TestEventLoggingNoUTCTime.cpp @@ -73,14 +73,13 @@ class MockClock : public chip::System::Clock::ClockBase chip::System::Clock::ClockBase & mRealClock; }; -class TestEventLoggingNoUTCTime : public ::testing::Test +class TestEventLoggingNoUTCTime : public chip::Test::AppContext { public: // Performs shared setup for all tests in the test suite static void SetUpTestSuite() { - mpTestContext = new chip::Test::AppContext; - mpTestContext->SetUpTestSuite(); + chip::Test::AppContext::SetUpTestSuite(); sClock.Emplace(chip::System::SystemClock()); } @@ -88,8 +87,7 @@ class TestEventLoggingNoUTCTime : public ::testing::Test static void TearDownTestSuite() { sClock.ClearValue(); - mpTestContext->TearDownTestSuite(); - delete mpTestContext; + chip::Test::AppContext::TearDownTestSuite(); } // Performs setup for each individual test in the test suite @@ -101,9 +99,9 @@ class TestEventLoggingNoUTCTime : public ::testing::Test { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - mpTestContext->SetUp(); + chip::Test::AppContext::SetUp(); ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); - chip::app::EventManagement::CreateEventManagement(&mpTestContext->GetExchangeManager(), ArraySize(logStorageResources), + chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); } @@ -111,17 +109,14 @@ class TestEventLoggingNoUTCTime : public ::testing::Test void TearDown() override { chip::app::EventManagement::DestroyEventManagement(); - mpTestContext->TearDown(); + chip::Test::AppContext::TearDown(); } - static chip::Test::AppContext * mpTestContext; - private: chip::MonotonicallyIncreasingCounter mEventCounter; static chip::Optional sClock; }; -chip::Test::AppContext * TestEventLoggingNoUTCTime::mpTestContext = nullptr; chip::Optional TestEventLoggingNoUTCTime::sClock; void ENFORCE_FORMAT(1, 2) SimpleDumpWriter(const char * aFormat, ...) diff --git a/src/app/tests/TestEventOverflow.cpp b/src/app/tests/TestEventOverflow.cpp index 45692273c88274..4a3cc2d80c3613 100644 --- a/src/app/tests/TestEventOverflow.cpp +++ b/src/app/tests/TestEventOverflow.cpp @@ -51,20 +51,9 @@ static uint8_t gInfoEventBuffer[2048]; static uint8_t gCritEventBuffer[2048]; static chip::app::CircularEventBuffer gCircularEventBuffer[3]; -class TestEventOverflow : public ::testing::Test +class TestEventOverflow : public chip::Test::AppContext { public: - static void SetUpTestSuite() - { - mpTestContext = new chip::Test::AppContext; - mpTestContext->SetUpTestSuite(); - } - static void TearDownTestSuite() - { - mpTestContext->TearDownTestSuite(); - delete mpTestContext; - } - // Performs setup for each individual test in the test suite void SetUp() override { @@ -74,9 +63,11 @@ class TestEventOverflow : public ::testing::Test { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - mpTestContext->SetUp(); + AppContext::SetUp(); + VerifyOrReturn(!HasFailure()); + ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); - chip::app::EventManagement::CreateEventManagement(&mpTestContext->GetExchangeManager(), ArraySize(logStorageResources), + chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); } @@ -84,17 +75,13 @@ class TestEventOverflow : public ::testing::Test void TearDown() override { chip::app::EventManagement::DestroyEventManagement(); - mpTestContext->TearDown(); + AppContext::TearDown(); } - static chip::Test::AppContext * mpTestContext; - private: chip::MonotonicallyIncreasingCounter mEventCounter; }; -chip::Test::AppContext * TestEventOverflow::mpTestContext = nullptr; - class TestEventGenerator : public chip::app::EventLoggingDelegate { public: diff --git a/src/app/tests/TestFabricScopedEventLogging.cpp b/src/app/tests/TestFabricScopedEventLogging.cpp index d113bc692e069f..98132a1d990479 100644 --- a/src/app/tests/TestFabricScopedEventLogging.cpp +++ b/src/app/tests/TestFabricScopedEventLogging.cpp @@ -53,20 +53,9 @@ static uint8_t gInfoEventBuffer[128]; static uint8_t gCritEventBuffer[128]; static chip::app::CircularEventBuffer gCircularEventBuffer[3]; -class TestFabricScopedEventLogging : public ::testing::Test +class TestFabricScopedEventLogging : public chip::Test::AppContext { public: - static void SetUpTestSuite() - { - mpTestContext = new chip::Test::AppContext; - mpTestContext->SetUpTestSuite(); - } - static void TearDownTestSuite() - { - mpTestContext->TearDownTestSuite(); - delete mpTestContext; - } - // Performs setup for each individual test in the test suite void SetUp() override { @@ -76,10 +65,10 @@ class TestFabricScopedEventLogging : public ::testing::Test { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - mpTestContext->SetUp(); + chip::Test::AppContext::SetUp(); ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); - chip::app::EventManagement::CreateEventManagement(&mpTestContext->GetExchangeManager(), ArraySize(logStorageResources), + chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); } @@ -87,15 +76,12 @@ class TestFabricScopedEventLogging : public ::testing::Test void TearDown() override { chip::app::EventManagement::DestroyEventManagement(); - mpTestContext->TearDown(); + chip::Test::AppContext::TearDown(); } - static chip::Test::AppContext * mpTestContext; - private: chip::MonotonicallyIncreasingCounter mEventCounter; }; -chip::Test::AppContext * TestFabricScopedEventLogging::mpTestContext = nullptr; void ENFORCE_FORMAT(1, 2) SimpleDumpWriter(const char * aFormat, ...) { diff --git a/src/app/tests/TestInteractionModelEngine.cpp b/src/app/tests/TestInteractionModelEngine.cpp index 7817d3636d3fae..f724f1921ef81d 100644 --- a/src/app/tests/TestInteractionModelEngine.cpp +++ b/src/app/tests/TestInteractionModelEngine.cpp @@ -42,8 +42,6 @@ #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS namespace { -using TestContext = chip::Test::AppContext; - class NullReadHandlerCallback : public chip::app::ReadHandler::ManagementCallback { public: @@ -59,39 +57,9 @@ class NullReadHandlerCallback : public chip::app::ReadHandler::ManagementCallbac namespace chip { namespace app { -class TestInteractionModelEngine : public ::testing::Test +class TestInteractionModelEngine : public chip::Test::AppContext { public: - static void SetUpTestSuite() - { - mpTestContext = new chip::Test::AppContext; - mpTestContext->SetUpTestSuite(); - } - static void TearDownTestSuite() - { - mpTestContext->TearDownTestSuite(); - if (mpTestContext != nullptr) - { - delete mpTestContext; - } - } - - void SetUp() override - { - - if (mpTestContext != nullptr) - { - mpTestContext->SetUp(); - } - } - void TearDown() override - { - if (mpTestContext != nullptr) - { - mpTestContext->TearDown(); - } - } - void TestSubjectHasActiveSubscriptionSingleSubOneEntry(); void TestSubjectHasActiveSubscriptionSingleSubMultipleEntries(); void TestSubjectHasActiveSubscriptionMultipleSubsSingleEntry(); @@ -100,12 +68,8 @@ class TestInteractionModelEngine : public ::testing::Test void TestSubscriptionResumptionTimer(); void TestDecrementNumSubscriptionsToResume(); static int GetAttributePathListLength(SingleLinkedListNode * apattributePathParamsList); - - static chip::Test::AppContext * mpTestContext; }; -chip::Test::AppContext * TestInteractionModelEngine::mpTestContext = nullptr; - int TestInteractionModelEngine::GetAttributePathListLength(SingleLinkedListNode * apAttributePathParamsList) { int length = 0; @@ -123,9 +87,7 @@ TEST_F(TestInteractionModelEngine, TestAttributePathParamsPushRelease) InteractionModelEngine * engine = InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); SingleLinkedListNode * attributePathParamsList = nullptr; AttributePathParams attributePathParams1; @@ -160,9 +122,7 @@ TEST_F(TestInteractionModelEngine, TestRemoveDuplicateConcreteAttribute) InteractionModelEngine * engine = InteractionModelEngine::GetInstance(); - EXPECT_EQ(CHIP_NO_ERROR, - engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler())); + EXPECT_EQ(CHIP_NO_ERROR, engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler())); SingleLinkedListNode * attributePathParamsList = nullptr; AttributePathParams attributePathParams1; @@ -294,13 +254,11 @@ TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestSubjectHasActiveSubscription FabricIndex bobFabricIndex = 1; // Create ExchangeContext - Messaging::ExchangeContext * exchangeCtx1 = mpTestContext->NewExchangeToBob(nullptr, false); + Messaging::ExchangeContext * exchangeCtx1 = NewExchangeToBob(nullptr, false); ASSERT_TRUE(exchangeCtx1); // InteractionModelEngine init - EXPECT_EQ(CHIP_NO_ERROR, - engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - reporting::GetDefaultReportScheduler())); + EXPECT_EQ(CHIP_NO_ERROR, engine->Init(&GetExchangeManager(), &GetFabricTable(), reporting::GetDefaultReportScheduler())); // Verify that there are no active subscriptions EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); @@ -339,16 +297,14 @@ TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestSubjectHasActiveSubscription FabricIndex bobFabricIndex = 1; // Create ExchangeContexts - Messaging::ExchangeContext * exchangeCtx1 = mpTestContext->NewExchangeToBob(nullptr, false); + Messaging::ExchangeContext * exchangeCtx1 = NewExchangeToBob(nullptr, false); ASSERT_TRUE(exchangeCtx1); - Messaging::ExchangeContext * exchangeCtx2 = mpTestContext->NewExchangeToBob(nullptr, false); + Messaging::ExchangeContext * exchangeCtx2 = NewExchangeToBob(nullptr, false); ASSERT_TRUE(exchangeCtx1); // InteractionModelEngine init - EXPECT_EQ(CHIP_NO_ERROR, - engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - reporting::GetDefaultReportScheduler())); + EXPECT_EQ(CHIP_NO_ERROR, engine->Init(&GetExchangeManager(), &GetFabricTable(), reporting::GetDefaultReportScheduler())); // Verify that both Alice and Bob have no active subscriptions EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); @@ -398,16 +354,14 @@ TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestSubjectHasActiveSubscription FabricIndex aliceFabricIndex = 2; // Create ExchangeContexts - Messaging::ExchangeContext * exchangeCtx1 = mpTestContext->NewExchangeToBob(nullptr, false); + Messaging::ExchangeContext * exchangeCtx1 = NewExchangeToBob(nullptr, false); ASSERT_TRUE(exchangeCtx1); - Messaging::ExchangeContext * exchangeCtx2 = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx2 = NewExchangeToAlice(nullptr, false); ASSERT_TRUE(exchangeCtx2); // InteractionModelEngine init - EXPECT_EQ(CHIP_NO_ERROR, - engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - reporting::GetDefaultReportScheduler())); + EXPECT_EQ(CHIP_NO_ERROR, engine->Init(&GetExchangeManager(), &GetFabricTable(), reporting::GetDefaultReportScheduler())); // Verify that both Alice and Bob have no active subscriptions EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); @@ -474,22 +428,20 @@ TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestSubjectHasActiveSubscription FabricIndex aliceFabricIndex = 2; // Create ExchangeContexts - Messaging::ExchangeContext * exchangeCtx11 = mpTestContext->NewExchangeToBob(nullptr, false); + Messaging::ExchangeContext * exchangeCtx11 = NewExchangeToBob(nullptr, false); ASSERT_TRUE(exchangeCtx11); - Messaging::ExchangeContext * exchangeCtx12 = mpTestContext->NewExchangeToBob(nullptr, false); + Messaging::ExchangeContext * exchangeCtx12 = NewExchangeToBob(nullptr, false); ASSERT_TRUE(exchangeCtx12); - Messaging::ExchangeContext * exchangeCtx21 = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx21 = NewExchangeToAlice(nullptr, false); ASSERT_TRUE(exchangeCtx21); - Messaging::ExchangeContext * exchangeCtx22 = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx22 = NewExchangeToAlice(nullptr, false); ASSERT_TRUE(exchangeCtx22); // InteractionModelEngine init - EXPECT_EQ(CHIP_NO_ERROR, - engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - reporting::GetDefaultReportScheduler())); + EXPECT_EQ(CHIP_NO_ERROR, engine->Init(&GetExchangeManager(), &GetFabricTable(), reporting::GetDefaultReportScheduler())); // Verify that both Alice and Bob have no active subscriptions EXPECT_FALSE(engine->SubjectHasActiveSubscription(bobFabricIndex, bobNodeId)); @@ -566,18 +518,16 @@ TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestSubjectHasActiveSubscription FabricIndex bobFabricIndex = 1; // InteractionModelEngine init - EXPECT_EQ(CHIP_NO_ERROR, - engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - reporting::GetDefaultReportScheduler())); + EXPECT_EQ(CHIP_NO_ERROR, engine->Init(&GetExchangeManager(), &GetFabricTable(), reporting::GetDefaultReportScheduler())); // Make sure we are using CASE sessions, because there is no defunct-marking for PASE. - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->ExpireSessionAliceToBob(); - EXPECT_EQ(CHIP_NO_ERROR, mpTestContext->CreateCASESessionBobToAlice(cats)); - EXPECT_EQ(CHIP_NO_ERROR, mpTestContext->CreateCASESessionAliceToBob(cats)); + ExpireSessionBobToAlice(); + ExpireSessionAliceToBob(); + EXPECT_EQ(CHIP_NO_ERROR, CreateCASESessionBobToAlice(cats)); + EXPECT_EQ(CHIP_NO_ERROR, CreateCASESessionAliceToBob(cats)); // Create ExchangeContexts - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToBob(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToBob(nullptr, false); ASSERT_TRUE(exchangeCtx); // Create readHandler @@ -618,8 +568,8 @@ TEST_F(TestInteractionModelEngine, TestSubjectHasPersistedSubscription) EXPECT_EQ(subscriptionStorage.Init(&storage), CHIP_NO_ERROR); EXPECT_EQ(CHIP_NO_ERROR, - engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler(), nullptr, &subscriptionStorage)); + engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler(), nullptr, + &subscriptionStorage)); NodeId nodeId1 = 1; FabricIndex fabric1 = 1; @@ -672,9 +622,7 @@ TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestSubscriptionResumptionTimer) InteractionModelEngine * engine = InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); uint32_t timeTillNextResubscriptionMs; engine->mNumSubscriptionResumptionRetries = 0; @@ -705,9 +653,7 @@ TEST_F_FROM_FIXTURE(TestInteractionModelEngine, TestDecrementNumSubscriptionsToR constexpr uint8_t kNumberOfSubsToResume = 5; uint8_t numberOfSubsRemaining = kNumberOfSubsToResume; - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); #if CHIP_CONFIG_ENABLE_ICD_CIP && !CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION ICDManager manager; diff --git a/src/app/tests/TestReadInteraction.cpp b/src/app/tests/TestReadInteraction.cpp index 561a0997afa2a8..ab7440b6bec767 100644 --- a/src/app/tests/TestReadInteraction.cpp +++ b/src/app/tests/TestReadInteraction.cpp @@ -230,14 +230,13 @@ using Seconds16 = System::Clock::Seconds16; using Milliseconds32 = System::Clock::Milliseconds32; // TODO: Add support for a 2nd Test Context by making sSyncScheduler = true (this was not ported from NL Tests yet) -class TestReadInteraction : public ::testing::Test +class TestReadInteraction : public chip::Test::AppContext { public: static void SetUpTestSuite() { - mpTestContext = new chip::Test::AppContext; - mpTestContext->SetUpTestSuite(); + chip::Test::AppContext::SetUpTestSuite(); gRealClock = &chip::System::SystemClock(); chip::System::Clock::Internal::SetSystemClockForTesting(&gMockClock); @@ -256,8 +255,7 @@ class TestReadInteraction : public ::testing::Test { chip::System::Clock::Internal::SetSystemClockForTesting(gRealClock); - mpTestContext->TearDownTestSuite(); - delete mpTestContext; + chip::Test::AppContext::TearDownTestSuite(); } void SetUp() @@ -268,20 +266,18 @@ class TestReadInteraction : public ::testing::Test { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - mpTestContext->SetUp(); + chip::Test::AppContext::SetUp(); ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); - chip::app::EventManagement::CreateEventManagement(&mpTestContext->GetExchangeManager(), ArraySize(logStorageResources), + chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); } void TearDown() { chip::app::EventManagement::DestroyEventManagement(); - mpTestContext->TearDown(); + chip::Test::AppContext::TearDown(); } - static chip::Test::AppContext * mpTestContext; - void TestReadClient(); void TestReadUnexpectedSubscriptionId(); void TestReadHandler(); @@ -334,8 +330,7 @@ class TestReadInteraction : public ::testing::Test static bool sSyncScheduler; }; -chip::Test::AppContext * TestReadInteraction::mpTestContext = nullptr; -bool TestReadInteraction::sSyncScheduler = false; +bool TestReadInteraction::sSyncScheduler = false; void TestReadInteraction::GenerateReportData(System::PacketBufferHandle & aPayload, ReportType aReportType, bool aSuppressResponse, bool aHasSubscriptionId = false) @@ -420,19 +415,19 @@ void TestReadInteraction::GenerateReportData(System::PacketBufferHandle & aPaylo TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClient) { MockInteractionModelApp delegate; - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); // We don't actually want to deliver that message, because we want to // synthesize the read response. But we don't want it hanging around // forever either. - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->DrainAndServiceIO(); + GetLoopback().mNumMessagesToDrop = 1; + DrainAndServiceIO(); GenerateReportData(buf, ReportType::kValid, true /* aSuppressResponse*/); EXPECT_EQ(readClient.ProcessReportData(std::move(buf), ReadClient::ReportType::kContinuingTransaction), CHIP_NO_ERROR); @@ -441,19 +436,19 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClient) TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadUnexpectedSubscriptionId) { MockInteractionModelApp delegate; - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); // We don't actually want to deliver that message, because we want to // synthesize the read response. But we don't want it hanging around // forever either. - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->DrainAndServiceIO(); + GetLoopback().mNumMessagesToDrop = 1; + DrainAndServiceIO(); // For read, we don't expect there is subscription id in report data. GenerateReportData(buf, ReportType::kValid, true /* aSuppressResponse*/, true /*aHasSubscriptionId*/); @@ -470,11 +465,10 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandler) NullReadHandlerCallback nullCallback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); { - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToAlice(nullptr, false); ReadHandler readHandler(nullCallback, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); GenerateReportData(reportDatabuf, ReportType::kValid, false /* aSuppressResponse*/); @@ -507,7 +501,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandler) engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateAttributePathList) @@ -521,7 +515,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateAttributePathList writer.Init(std::move(msgBuf)); EXPECT_EQ(request.Init(&writer), CHIP_NO_ERROR); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); AttributePathParams attributePathParams[2]; @@ -545,7 +539,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateInvalidAttributeP EXPECT_FALSE(msgBuf.IsNull()); writer.Init(std::move(msgBuf)); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(request.Init(&writer), CHIP_NO_ERROR); @@ -567,17 +561,17 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientInvalidReport) System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); // We don't actually want to deliver that message, because we want to // synthesize the read response. But we don't want it hanging around // forever either. - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->DrainAndServiceIO(); + GetLoopback().mNumMessagesToDrop = 1; + DrainAndServiceIO(); GenerateReportData(buf, ReportType::kInvalidNoAttributeId, true /* aSuppressResponse*/); @@ -591,17 +585,17 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientInvalidAttributeId) System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); // We don't actually want to deliver that message, because we want to // synthesize the read response. But we don't want it hanging around // forever either. - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->DrainAndServiceIO(); + GetLoopback().mNumMessagesToDrop = 1; + DrainAndServiceIO(); GenerateReportData(buf, ReportType::kInvalidOutOfRangeAttributeId, true /* aSuppressResponse*/); @@ -626,11 +620,10 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerInvalidAttributePath) NullReadHandlerCallback nullCallback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); { - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToAlice(nullptr, false); ReadHandler readHandler(nullCallback, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); GenerateReportData(reportDatabuf, ReportType::kValid, false /* aSuppressResponse*/); @@ -669,7 +662,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerInvalidAttributePath) } engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateOneEventPaths) @@ -683,7 +676,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateOneEventPaths) writer.Init(std::move(msgBuf)); EXPECT_EQ(request.Init(&writer), CHIP_NO_ERROR); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); chip::app::EventPathParams eventPathParams[1]; @@ -710,7 +703,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateOneEventPaths) readRequestParser.PrettyPrint(); #endif - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateTwoEventPaths) @@ -724,7 +717,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateTwoEventPaths) writer.Init(std::move(msgBuf)); EXPECT_EQ(request.Init(&writer), CHIP_NO_ERROR); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); chip::app::EventPathParams eventPathParams[2]; @@ -755,13 +748,13 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateTwoEventPaths) readRequestParser.PrettyPrint(); #endif - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestReadInteraction, TestReadRoundtrip) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -769,8 +762,7 @@ TEST_F(TestReadInteraction, TestReadRoundtrip) MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); chip::app::EventPathParams eventPathParams[1]; @@ -787,7 +779,7 @@ TEST_F(TestReadInteraction, TestReadRoundtrip) attributePathParams[1].mAttributeId = 2; attributePathParams[1].mListIndex = 1; - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mEventPathParamsListSize = 1; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -795,12 +787,12 @@ TEST_F(TestReadInteraction, TestReadRoundtrip) readPrepareParams.mEventNumber.SetValue(1); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumDataElementIndex, 1); EXPECT_TRUE(delegate.mGotEventResponse); @@ -814,12 +806,12 @@ TEST_F(TestReadInteraction, TestReadRoundtrip) } { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotEventResponse); EXPECT_EQ(delegate.mNumAttributeResponse, 2); @@ -833,13 +825,13 @@ TEST_F(TestReadInteraction, TestReadRoundtrip) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestReadInteraction, TestReadRoundtripWithDataVersionFilter) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -847,8 +839,7 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithDataVersionFilter) MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[2]; @@ -866,19 +857,19 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithDataVersionFilter) dataVersionFilters[0].mClusterId = kTestClusterId; dataVersionFilters[0].mDataVersion.SetValue(kTestDataVersion1); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; readPrepareParams.mpDataVersionFilterList = dataVersionFilters; readPrepareParams.mDataVersionFilterListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 0); delegate.mNumAttributeResponse = 0; @@ -886,13 +877,13 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithDataVersionFilter) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestReadInteraction, TestReadRoundtripWithNoMatchPathDataVersionFilter) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -900,8 +891,7 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithNoMatchPathDataVersionFilter) MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); chip::app::AttributePathParams attributePathParams[2]; attributePathParams[0].mEndpointId = kTestEndpointId; @@ -922,19 +912,19 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithNoMatchPathDataVersionFilter) dataVersionFilters[1].mClusterId = kTestClusterId; dataVersionFilters[1].mDataVersion.SetValue(kTestDataVersion2); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; readPrepareParams.mpDataVersionFilterList = dataVersionFilters; readPrepareParams.mDataVersionFilterListSize = 2; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 2); EXPECT_FALSE(delegate.mReadError); @@ -943,13 +933,13 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithNoMatchPathDataVersionFilter) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestReadInteraction, TestReadRoundtripWithMultiSamePathDifferentDataVersionFilter) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -957,8 +947,7 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithMultiSamePathDifferentDataVersi MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[2]; @@ -980,19 +969,19 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithMultiSamePathDifferentDataVersi dataVersionFilters[1].mClusterId = kTestClusterId; dataVersionFilters[1].mDataVersion.SetValue(kTestDataVersion2); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; readPrepareParams.mpDataVersionFilterList = dataVersionFilters; readPrepareParams.mDataVersionFilterListSize = 2; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 2); EXPECT_FALSE(delegate.mReadError); @@ -1001,13 +990,13 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithMultiSamePathDifferentDataVersi EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestReadInteraction, TestReadRoundtripWithSameDifferentPathsDataVersionFilter) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -1015,8 +1004,7 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithSameDifferentPathsDataVersionFi MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[2]; @@ -1038,19 +1026,19 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithSameDifferentPathsDataVersionFi dataVersionFilters[1].mClusterId = kTestClusterId; dataVersionFilters[1].mDataVersion.SetValue(kTestDataVersion2); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 2; readPrepareParams.mpDataVersionFilterList = dataVersionFilters; readPrepareParams.mDataVersionFilterListSize = 2; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 0); EXPECT_FALSE(delegate.mReadError); @@ -1059,13 +1047,13 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithSameDifferentPathsDataVersionFi EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestReadInteraction, TestReadWildcard) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -1073,15 +1061,14 @@ TEST_F(TestReadInteraction, TestReadWildcard) MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[1]; attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint2; attributePathParams[0].mClusterId = chip::Test::MockClusterId(3); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -1089,12 +1076,12 @@ TEST_F(TestReadInteraction, TestReadWildcard) { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 5); EXPECT_TRUE(delegate.mGotReport); EXPECT_FALSE(delegate.mReadError); @@ -1105,14 +1092,14 @@ TEST_F(TestReadInteraction, TestReadWildcard) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // TestReadChunking will try to read a few large attributes, the report won't fit into the MTU and result in chunking. TEST_F(TestReadInteraction, TestReadChunking) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -1120,8 +1107,7 @@ TEST_F(TestReadInteraction, TestReadChunking) MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[1]; @@ -1131,19 +1117,19 @@ TEST_F(TestReadInteraction, TestReadChunking) attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // We get one chunk with 4 array elements, and then one chunk per // element, and the total size of the array is @@ -1159,21 +1145,20 @@ TEST_F(TestReadInteraction, TestReadChunking) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestReadInteraction, TestSetDirtyBetweenChunks) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); GenerateEvents(); auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); chip::app::AttributePathParams attributePathParams[2]; for (auto & attributePathParam : attributePathParams) @@ -1183,7 +1168,7 @@ TEST_F(TestReadInteraction, TestSetDirtyBetweenChunks) attributePathParam.mAttributeId = chip::Test::MockAttributeId(4); } - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -1283,12 +1268,12 @@ TEST_F(TestReadInteraction, TestSetDirtyBetweenChunks) DirtyingMockDelegate delegate(attributePathParams, currentAttributeResponsesWhenSetDirty, currentArrayItemsWhenSetDirty); EXPECT_FALSE(delegate.mGotEventResponse); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Our list has length kMockAttribute4ListLength. Since the underlying // path iterator should be reset to the beginning of the cluster it is @@ -1309,13 +1294,13 @@ TEST_F(TestReadInteraction, TestSetDirtyBetweenChunks) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestReadInteraction, TestReadInvalidAttributePathRoundtrip) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -1323,8 +1308,7 @@ TEST_F(TestReadInteraction, TestReadInvalidAttributePathRoundtrip) MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[2]; @@ -1332,17 +1316,17 @@ TEST_F(TestReadInteraction, TestReadInvalidAttributePathRoundtrip) attributePathParams[0].mClusterId = kInvalidTestClusterId; attributePathParams[0].mAttributeId = 1; - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 0); // By now we should have closed all exchanges and sent all pending acks, so @@ -1351,7 +1335,7 @@ TEST_F(TestReadInteraction, TestReadInvalidAttributePathRoundtrip) } engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F_FROM_FIXTURE(TestReadInteraction, TestProcessSubscribeRequest) @@ -1360,10 +1344,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestProcessSubscribeRequest) System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); SubscribeRequestMessage::Builder subscribeRequestBuilder; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToAlice(nullptr, false); { ReadHandler readHandler(*engine, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); @@ -1403,7 +1386,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestProcessSubscribeRequest) engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } #if CHIP_CONFIG_ENABLE_ICD_SERVER @@ -1417,13 +1400,12 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestSupMaxInt System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); SubscribeRequestMessage::Builder subscribeRequestBuilder; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); uint16_t kMinInterval = 0; uint16_t kMaxIntervalCeiling = 1; - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToAlice(nullptr, false); { ReadHandler readHandler(*engine, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); @@ -1471,7 +1453,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestSupMaxInt } engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } /** @@ -1484,13 +1466,12 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestInfMaxInt System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); SubscribeRequestMessage::Builder subscribeRequestBuilder; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); uint16_t kMinInterval = 0; uint16_t kMaxIntervalCeiling = 1; - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToAlice(nullptr, false); { ReadHandler readHandler(*engine, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); @@ -1538,7 +1519,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestInfMaxInt } engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } /** @@ -1551,13 +1532,12 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestSupMinInt System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); SubscribeRequestMessage::Builder subscribeRequestBuilder; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); uint16_t kMinInterval = 305; // Default IdleModeDuration is 300 uint16_t kMaxIntervalCeiling = 605; - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToAlice(nullptr, false); { ReadHandler readHandler(*engine, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); @@ -1605,7 +1585,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestSupMinInt } engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } /** @@ -1618,13 +1598,12 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestMaxMinInt System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); SubscribeRequestMessage::Builder subscribeRequestBuilder; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); uint16_t kMinInterval = System::Clock::Seconds16::max().count(); uint16_t kMaxIntervalCeiling = System::Clock::Seconds16::max().count(); - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToAlice(nullptr, false); { ReadHandler readHandler(*engine, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); @@ -1670,7 +1649,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestMaxMinInt } engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } /** @@ -1683,13 +1662,12 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestInvalidId System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); SubscribeRequestMessage::Builder subscribeRequestBuilder; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); uint16_t kMinInterval = 400; uint16_t kMaxIntervalCeiling = 400; - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToAlice(nullptr, false); { ReadHandler readHandler(*engine, exchangeCtx, chip::app::ReadHandler::InteractionType::Read, gReportScheduler); @@ -1735,7 +1713,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestInvalidId } engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } #endif // CHIP_CONFIG_ENABLE_ICD_SERVER @@ -1743,18 +1721,17 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestInvalidId TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -1784,12 +1761,12 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); } @@ -1798,12 +1775,12 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); @@ -1844,7 +1821,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); delegate.mGotReport = false; delegate.mGotEventResponse = false; @@ -1854,7 +1831,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath2), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); EXPECT_TRUE(delegate.mGotEventResponse); @@ -1863,7 +1840,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) // Test report with 2 different path, and 1 same path // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; @@ -1871,7 +1848,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath2), CHIP_NO_ERROR); EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath2), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); EXPECT_EQ(delegate.mNumAttributeResponse, 2); @@ -1879,7 +1856,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) // Test report with 3 different path, and one path is overlapped with another // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; @@ -1887,7 +1864,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath2), CHIP_NO_ERROR); EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath3), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); EXPECT_EQ(delegate.mNumAttributeResponse, 2); @@ -1895,7 +1872,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) // Test report with 3 different path, all are not overlapped, one path is not interested for current subscription // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; @@ -1903,7 +1880,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath2), CHIP_NO_ERROR); EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath4), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); EXPECT_EQ(delegate.mNumAttributeResponse, 2); @@ -1915,13 +1892,13 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) // Test empty report // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(maxInterval)); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); EXPECT_TRUE(engine->GetReportingEngine().IsRunScheduled()); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 0); } @@ -1932,23 +1909,22 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeEarlyReport) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[1]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -1965,13 +1941,13 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeEarlyReport) readPrepareParams.mKeepSubscriptions = true; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); readPrepareParams.mpEventPathParamsList[0].mIsUrgentEvent = true; delegate.mGotEventResponse = false; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); System::Clock::Timestamp startTime = gMockClock.GetMonotonicTimestamp(); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); @@ -2009,7 +1985,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeEarlyReport) gMockClock.AdvanceMonotonic(Seconds16(readPrepareParams.mMinIntervalFloorSeconds)); EXPECT_FALSE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); // Service Timer expired event - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); EXPECT_GT(gReportScheduler->GetMinTimestampForHandler(delegate.mpReadHandler), gMockClock.GetMonotonicTimestamp()); @@ -2021,10 +1997,10 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeEarlyReport) EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); // Service Engine Run - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); // Service EventManagement event - mpTestContext->GetIOContext().DriveIO(); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); + GetIOContext().DriveIO(); EXPECT_TRUE(delegate.mGotEventResponse); } else @@ -2040,14 +2016,14 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeEarlyReport) gMockClock.AdvanceMonotonic(Milliseconds32(50)); // Service Timer expired event - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); // Service Engine Run - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); // Service EventManagement event - mpTestContext->GetIOContext().DriveIO(); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); + GetIOContext().DriveIO(); EXPECT_TRUE(delegate.mGotEventResponse); } @@ -2074,7 +2050,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeEarlyReport) EXPECT_FALSE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); // Service Timer expired event - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); // Verify the ReadHandler is considered as reportable even if its node's min timestamp has not expired EXPECT_GT(gReportScheduler->GetMaxTimestampForHandler(delegate.mpReadHandler), gMockClock.GetMonotonicTimestamp()); @@ -2083,35 +2059,34 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeEarlyReport) EXPECT_FALSE(delegate.mpReadHandler->IsDirty()); EXPECT_TRUE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); // Service Engine Run - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); // Service EventManagement event - mpTestContext->GetIOContext().DriveIO(); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); + GetIOContext().DriveIO(); EXPECT_TRUE(gReportScheduler->IsReportScheduled(delegate.mpReadHandler)); EXPECT_FALSE(InteractionModelEngine::GetInstance()->GetReportingEngine().IsRunScheduled()); } - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeUrgentWildcardEvent) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; MockInteractionModelApp nonUrgentDelegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); EXPECT_FALSE(nonUrgentDelegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -2134,18 +2109,18 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeUrgentWildcardEvent) readPrepareParams.mKeepSubscriptions = true; { - app::ReadClient nonUrgentReadClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), + app::ReadClient nonUrgentReadClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), nonUrgentDelegate, chip::app::ReadClient::InteractionType::Subscribe); nonUrgentDelegate.mGotReport = false; EXPECT_EQ(nonUrgentReadClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); readPrepareParams.mpEventPathParamsList[0].mIsUrgentEvent = true; delegate.mGotReport = false; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); System::Clock::Timestamp startTime = gMockClock.GetMonotonicTimestamp(); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 2u); @@ -2178,7 +2153,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeUrgentWildcardEvent) // Advance monotonic looping to allow events to trigger gMockClock.AdvanceMonotonic(System::Clock::Milliseconds32(600)); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); EXPECT_FALSE(delegate.mGotEventResponse); EXPECT_FALSE(nonUrgentDelegate.mGotEventResponse); @@ -2187,13 +2162,13 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeUrgentWildcardEvent) gMockClock.AdvanceMonotonic(System::Clock::Milliseconds32(800)); // Service Timer expired event - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); // Service Engine Run - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); // Service EventManagement event - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); EXPECT_TRUE(delegate.mGotEventResponse); @@ -2217,7 +2192,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeUrgentWildcardEvent) // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Milliseconds32(2100)); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); // No reporting should have happened. EXPECT_FALSE(delegate.mGotEventResponse); @@ -2260,7 +2235,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeUrgentWildcardEvent) EXPECT_FALSE(delegate.mGotEventResponse); EXPECT_FALSE(nonUrgentDelegate.mGotEventResponse); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Should get those urgent events reported. EXPECT_TRUE(delegate.mGotEventResponse); @@ -2286,7 +2261,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeUrgentWildcardEvent) // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Milliseconds32(2100)); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); // No reporting should have happened. EXPECT_FALSE(delegate.mGotEventResponse); @@ -2324,7 +2299,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeUrgentWildcardEvent) EXPECT_FALSE(delegate.mGotEventResponse); EXPECT_FALSE(nonUrgentDelegate.mGotEventResponse); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Should get those urgent events reported and the non urgent reported for synchronisation EXPECT_TRUE(delegate.mGotEventResponse); @@ -2338,13 +2313,13 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeUrgentWildcardEvent) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestReadInteraction, TestSubscribeWildcard) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -2352,11 +2327,10 @@ TEST_F(TestReadInteraction, TestSubscribeWildcard) MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mEventPathParamsListSize = 0; std::unique_ptr attributePathParams(new chip::app::AttributePathParams[2]); @@ -2369,7 +2343,7 @@ TEST_F(TestReadInteraction, TestSubscribeWildcard) printf("\nSend subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; @@ -2377,7 +2351,7 @@ TEST_F(TestReadInteraction, TestSubscribeWildcard) attributePathParams.release(); EXPECT_EQ(readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); @@ -2439,7 +2413,7 @@ TEST_F(TestReadInteraction, TestSubscribeWildcard) EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); // We subscribed wildcard path twice, so we will receive two reports here. @@ -2465,7 +2439,7 @@ TEST_F(TestReadInteraction, TestSubscribeWildcard) do { last = delegate.mNumAttributeResponse; - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); } while (last != delegate.mNumAttributeResponse); // Mock endpoint3 has 13 attributes in total, and we subscribed twice. @@ -2484,24 +2458,23 @@ TEST_F(TestReadInteraction, TestSubscribeWildcard) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // Subscribe (wildcard, C3, A1), then setDirty (E2, C3, wildcard), receive one attribute after setDirty TEST_F(TestReadInteraction, TestSubscribePartialOverlap) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mEventPathParamsListSize = 0; std::unique_ptr attributePathParams(new chip::app::AttributePathParams[2]); @@ -2515,7 +2488,7 @@ TEST_F(TestReadInteraction, TestSubscribePartialOverlap) printf("\nSend subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; @@ -2523,7 +2496,7 @@ TEST_F(TestReadInteraction, TestSubscribePartialOverlap) attributePathParams.release(); EXPECT_EQ(readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); @@ -2543,7 +2516,7 @@ TEST_F(TestReadInteraction, TestSubscribePartialOverlap) EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); EXPECT_EQ(delegate.mNumAttributeResponse, 1); @@ -2555,24 +2528,23 @@ TEST_F(TestReadInteraction, TestSubscribePartialOverlap) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // Subscribe (E2, C3, A1), then setDirty (wildcard, wildcard, wildcard), receive one attribute after setDirty TEST_F(TestReadInteraction, TestSubscribeSetDirtyFullyOverlap) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mEventPathParamsListSize = 0; std::unique_ptr attributePathParams(new chip::app::AttributePathParams[1]); @@ -2587,7 +2559,7 @@ TEST_F(TestReadInteraction, TestSubscribeSetDirtyFullyOverlap) printf("\nSend subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; @@ -2595,7 +2567,7 @@ TEST_F(TestReadInteraction, TestSubscribeSetDirtyFullyOverlap) attributePathParams.release(); EXPECT_EQ(readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); @@ -2612,7 +2584,7 @@ TEST_F(TestReadInteraction, TestSubscribeSetDirtyFullyOverlap) AttributePathParams dirtyPath; EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); EXPECT_EQ(delegate.mNumAttributeResponse, 1); @@ -2624,20 +2596,20 @@ TEST_F(TestReadInteraction, TestSubscribeSetDirtyFullyOverlap) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // Verify that subscription can be shut down just after receiving SUBSCRIBE RESPONSE, // before receiving any subsequent REPORT DATA. TEST_F(TestReadInteraction, TestSubscribeEarlyShutdown) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); InteractionModelEngine & engine = *InteractionModelEngine::GetInstance(); MockInteractionModelApp delegate; // Initialize Interaction Model Engine EXPECT_EQ(rm->TestGetCountRetransTable(), 0); - EXPECT_EQ(engine.Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); + EXPECT_EQ(engine.Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); // Subscribe to the attribute AttributePathParams attributePathParams; @@ -2645,7 +2617,7 @@ TEST_F(TestReadInteraction, TestSubscribeEarlyShutdown) attributePathParams.mClusterId = kTestClusterId; attributePathParams.mAttributeId = 1; - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = &attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; readPrepareParams.mMinIntervalFloorSeconds = 2; @@ -2655,12 +2627,12 @@ TEST_F(TestReadInteraction, TestSubscribeEarlyShutdown) printf("Send subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); EXPECT_EQ(delegate.mNumAttributeResponse, 1); @@ -2675,13 +2647,13 @@ TEST_F(TestReadInteraction, TestSubscribeEarlyShutdown) EXPECT_EQ(rm->TestGetCountRetransTable(), 0); engine.Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeInvalidAttributePathRoundtrip) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -2690,11 +2662,10 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeInvalidAttributePathRoundt MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[1]; readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mpAttributePathParamsList[0].mEndpointId = kTestEndpointId; @@ -2703,20 +2674,20 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeInvalidAttributePathRoundt readPrepareParams.mAttributePathParamsListSize = 1; - readPrepareParams.mSessionHolder.Grab(mpTestContext->GetSessionBobToAlice()); + readPrepareParams.mSessionHolder.Grab(GetSessionBobToAlice()); readPrepareParams.mMinIntervalFloorSeconds = 0; readPrepareParams.mMaxIntervalCeilingSeconds = 1; printf("\nSend subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); delegate.mNumAttributeResponse = 0; - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 0); @@ -2729,19 +2700,19 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeInvalidAttributePathRoundt // Advance monotonic timestamp for min interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(maxInterval)); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); EXPECT_TRUE(engine->GetReportingEngine().IsRunScheduled()); EXPECT_TRUE(engine->GetReportingEngine().IsRunScheduled()); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 0); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestReadInteraction, TestReadShutdown) @@ -2755,7 +2726,7 @@ TEST_F(TestReadInteraction, TestReadShutdown) // for (auto & client : pClients) { - client = Platform::New(engine, &mpTestContext->GetExchangeManager(), delegate, + client = Platform::New(engine, &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); } @@ -2784,7 +2755,7 @@ TEST_F(TestReadInteraction, TestReadShutdown) TEST_F(TestReadInteraction, TestSubscribeInvalidInterval) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -2792,11 +2763,10 @@ TEST_F(TestReadInteraction, TestSubscribeInvalidInterval) MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[1]; readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mpAttributePathParamsList[0].mEndpointId = kTestEndpointId; @@ -2805,41 +2775,40 @@ TEST_F(TestReadInteraction, TestSubscribeInvalidInterval) readPrepareParams.mAttributePathParamsListSize = 1; - readPrepareParams.mSessionHolder.Grab(mpTestContext->GetSessionBobToAlice()); + readPrepareParams.mSessionHolder.Grab(GetSessionBobToAlice()); readPrepareParams.mMinIntervalFloorSeconds = 6; readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_ERROR_INVALID_ARGUMENT); printf("\nSend subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F_FROM_FIXTURE(TestReadInteraction, TestPostSubscribeRoundtripStatusReportTimeout) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -2871,14 +2840,14 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestPostSubscribeRoundtripStatusReportT readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); delegate.mGotReport = false; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); @@ -2907,18 +2876,18 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestPostSubscribeRoundtripStatusReportT EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath2), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); EXPECT_EQ(delegate.mNumAttributeResponse, 2); // Wait for max interval to elapse gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMaxIntervalCeilingSeconds)); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; - mpTestContext->ExpireSessionBobToAlice(); + ExpireSessionBobToAlice(); EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath1), CHIP_NO_ERROR); @@ -2926,9 +2895,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestPostSubscribeRoundtripStatusReportT EXPECT_TRUE(engine->GetReportingEngine().IsRunScheduled()); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); - mpTestContext->ExpireSessionAliceToBob(); + ExpireSessionAliceToBob(); EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 0u); EXPECT_EQ(delegate.mNumAttributeResponse, 0); } @@ -2939,25 +2908,24 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestPostSubscribeRoundtripStatusReportT EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } TEST_F(TestReadInteraction, TestSubscribeRoundtripStatusReportTimeout) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -2989,18 +2957,18 @@ TEST_F(TestReadInteraction, TestSubscribeRoundtripStatusReportTimeout) readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); delegate.mGotReport = false; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->ExpireSessionAliceToBob(); + ExpireSessionAliceToBob(); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); - mpTestContext->ExpireSessionBobToAlice(); + ExpireSessionBobToAlice(); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 0u); @@ -3013,15 +2981,15 @@ TEST_F(TestReadInteraction, TestSubscribeRoundtripStatusReportTimeout) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } TEST_F(TestReadInteraction, TestReadChunkingStatusReportTimeout) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -3029,8 +2997,7 @@ TEST_F(TestReadInteraction, TestReadChunkingStatusReportTimeout) MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[1]; @@ -3039,21 +3006,21 @@ TEST_F(TestReadInteraction, TestReadChunkingStatusReportTimeout) attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->DrainAndServiceIO(); - mpTestContext->ExpireSessionBobToAlice(); + ExpireSessionAliceToBob(); + DrainAndServiceIO(); + ExpireSessionBobToAlice(); EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 0u); // By now we should have closed all exchanges and sent all pending acks, so @@ -3063,9 +3030,9 @@ TEST_F(TestReadInteraction, TestReadChunkingStatusReportTimeout) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // ReadClient sends the read request, but handler fails to send the one report (SendMessage returns an error). @@ -3074,14 +3041,13 @@ TEST_F(TestReadInteraction, TestReadChunkingStatusReportTimeout) TEST_F(TestReadInteraction, TestReadReportFailure) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[1]; @@ -3089,47 +3055,46 @@ TEST_F(TestReadInteraction, TestReadReportFailure) attributePathParams[0].mClusterId = chip::Test::MockClusterId(3); attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(1); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeError = 1; - mpTestContext->GetLoopback().mMessageSendError = CHIP_ERROR_INCORRECT_STATE; + GetLoopback().mNumMessagesToAllowBeforeError = 1; + GetLoopback().mMessageSendError = CHIP_ERROR_INCORRECT_STATE; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 0u); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeError = 0; - mpTestContext->GetLoopback().mMessageSendError = CHIP_NO_ERROR; + GetLoopback().mNumMessagesToAllowBeforeError = 0; + GetLoopback().mMessageSendError = CHIP_NO_ERROR; } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestReadInteraction, TestSubscribeRoundtripChunkStatusReportTimeout) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -3158,16 +3123,16 @@ TEST_F(TestReadInteraction, TestSubscribeRoundtripChunkStatusReportTimeout) readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); delegate.mGotReport = false; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->DrainAndServiceIO(); - mpTestContext->ExpireSessionBobToAlice(); + ExpireSessionAliceToBob(); + DrainAndServiceIO(); + ExpireSessionBobToAlice(); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 0u); @@ -3180,25 +3145,24 @@ TEST_F(TestReadInteraction, TestSubscribeRoundtripChunkStatusReportTimeout) EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkStatusReportTimeout) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -3227,14 +3191,14 @@ TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkStatusReportTimeout) readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); delegate.mGotReport = false; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); @@ -3250,55 +3214,54 @@ TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkStatusReportTimeout) dirtyPath1.mAttributeId = chip::Test::MockAttributeId(4); gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMaxIntervalCeilingSeconds)); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath1), CHIP_NO_ERROR); delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + GetLoopback().mDroppedMessageCount = 0; - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Drop status report for the first chunked report, then expire session, handler would be timeout EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 1u); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkReportTimeout) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -3327,14 +3290,14 @@ TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkReportTimeout) readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); delegate.mGotReport = false; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); @@ -3350,7 +3313,7 @@ TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkReportTimeout) dirtyPath1.mAttributeId = chip::Test::MockAttributeId(4); gMockClock.AdvanceMonotonic(System::Clock::Seconds16(readPrepareParams.mMaxIntervalCeilingSeconds)); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); EXPECT_EQ(engine->GetReportingEngine().SetDirty(dirtyPath1), CHIP_NO_ERROR); @@ -3358,46 +3321,45 @@ TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkReportTimeout) delegate.mNumAttributeResponse = 0; // Drop second chunked report then expire session, client would be timeout - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 2; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 2; + GetLoopback().mDroppedMessageCount = 0; - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(engine->GetReportingEngine().GetNumReportsInFlight(), 1u); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 3u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 3u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); EXPECT_EQ(delegate.mError, CHIP_ERROR_TIMEOUT); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkReport) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::EventPathParams eventPathParams[2]; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mpEventPathParamsList[0].mEndpointId = kTestEventEndpointId; @@ -3426,14 +3388,14 @@ TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkReport) readPrepareParams.mKeepSubscriptions = false; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); printf("\nSend first subscribe request message to Node: 0x" ChipLogFormatX64 "\n", ChipLogValueX64(chip::kTestDeviceNodeId)); delegate.mGotReport = false; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); @@ -3456,7 +3418,7 @@ TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkReport) // wait for min interval 1 seconds(in test, we use 0.9second considering the time variation), expect no event is // received, then wait for 0.5 seconds, then all chunked dirty reports are sent out, which would not honor minInterval gMockClock.AdvanceMonotonic(System::Clock::Milliseconds32(900)); - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 0); System::Clock::Timestamp startTime = gMockClock.GetMonotonicTimestamp(); @@ -3465,7 +3427,7 @@ TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkReport) // be rescheduled accordingly while (true) { - mpTestContext->GetIOContext().DriveIO(); + GetIOContext().DriveIO(); if ((gMockClock.GetMonotonicTimestamp() - startTime) >= System::Clock::Milliseconds32(500)) { break; @@ -3501,16 +3463,15 @@ void CheckForInvalidAction(Test::MessageCapturer & messageLog) TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientReceiveInvalidMessage) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -3525,20 +3486,19 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientReceiveInvalidMessage) readPrepareParams.mAttributePathParamsListSize = 2; { - app::ReadClient readClient(engine, &mpTestContext->GetExchangeManager(), delegate, - chip::app::ReadClient::InteractionType::Read); + app::ReadClient readClient(engine, &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); EXPECT_FALSE(msgBuf.IsNull()); @@ -3552,21 +3512,21 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientReceiveInvalidMessage) payloadHeader.SetExchangeID(0); payloadHeader.SetMessageType(chip::Protocols::InteractionModel::MsgType::StatusResponse); - chip::Test::MessageCapturer messageLog(*mpTestContext); + chip::Test::MessageCapturer messageLog(*this); 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(*mpTestContext, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*this, readClient.mExchange.Get()); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; readClient.OnMessageReceived(readClient.mExchange.Get(), payloadHeader, std::move(msgBuf)); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // The ReadHandler closed its exchange when it sent the Report Data (which we dropped). // Since we synthesized the StatusResponse to the ReadClient, instead of sending it from the ReadHandler, @@ -3577,10 +3537,10 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientReceiveInvalidMessage) } engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Read Client sends the subscribe request, Read Handler drops the response, then test injects unknown status response message @@ -3588,16 +3548,15 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientReceiveInvalidMessage) TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidStatusResponse) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -3615,17 +3574,17 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidStatus readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); EXPECT_FALSE(msgBuf.IsNull()); @@ -3642,37 +3601,37 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidStatus // 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(*mpTestContext, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*this, readClient.mExchange.Get()); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; readClient.OnMessageReceived(readClient.mExchange.Get(), payloadHeader, std::move(msgBuf)); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // TODO: Need to validate what status is being sent to the ReadHandler // The ReadHandler's exchange is closed when we synthesize the subscribe response, since it sent the // Subscribe Response as the last message in the transaction. // Since we synthesized the subscribe response to the ReadClient, instead of sending it from the ReadHandler, // the only messages here are the ReadClient's StatusResponse to the unexpected message and an MRP ack. - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(Busy)); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Read Client sends the subscribe request, Read Handler drops the response, then test injects well-formed status response @@ -3680,16 +3639,15 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidStatus TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveWellFormedStatusResponse) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -3707,17 +3665,17 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveWellFormedSta readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); EXPECT_FALSE(msgBuf.IsNull()); @@ -3734,36 +3692,36 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveWellFormedSta // 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(*mpTestContext, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*this, readClient.mExchange.Get()); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; readClient.OnMessageReceived(readClient.mExchange.Get(), payloadHeader, std::move(msgBuf)); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // TODO: Need to validate what status is being sent to the ReadHandler // The ReadHandler's exchange is still open when we synthesize the StatusResponse. // Since we synthesized the StatusResponse to the ReadClient, instead of sending it from the ReadHandler, // the only messages here are the ReadClient's StatusResponse to the unexpected message and an MRP ack. - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); EXPECT_EQ(delegate.mError, CHIP_ERROR_INVALID_MESSAGE_TYPE); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Read Client sends the subscribe request, Read Handler drops the response, then test injects invalid report message for Read @@ -3771,16 +3729,15 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveWellFormedSta TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidReportMessage) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -3798,17 +3755,17 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidReport readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); EXPECT_FALSE(msgBuf.IsNull()); @@ -3824,26 +3781,26 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidReport // 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(*mpTestContext, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*this, readClient.mExchange.Get()); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; readClient.OnMessageReceived(readClient.mExchange.Get(), payloadHeader, std::move(msgBuf)); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // TODO: Need to validate what status is being sent to the ReadHandler // The ReadHandler's exchange is still open when we synthesize the ReportData. // Since we synthesized the ReportData to the ReadClient, instead of sending it from the ReadHandler, // the only messages here are the ReadClient's StatusResponse to the unexpected message and an MRP ack. - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); EXPECT_EQ(delegate.mError, CHIP_ERROR_END_OF_TLV); @@ -3851,10 +3808,10 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidReport } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Read Client create the subscription, handler sends unsolicited malformed report to client, @@ -3862,16 +3819,15 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidReport TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedInvalidReportMessage) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -3889,13 +3845,13 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedIn readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - mpTestContext->GetLoopback().mSentMessageCount = 0; - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + GetLoopback().mSentMessageCount = 0; + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 5u); + DrainAndServiceIO(); + EXPECT_EQ(GetLoopback().mSentMessageCount, 5u); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); @@ -3908,8 +3864,8 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedIn response.Init(&writer); EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); - mpTestContext->GetLoopback().mSentMessageCount = 0; - auto exchange = InteractionModelEngine::GetInstance()->GetExchangeManager()->NewContext( + GetLoopback().mSentMessageCount = 0; + auto exchange = InteractionModelEngine::GetInstance()->GetExchangeManager()->NewContext( delegate.mpReadHandler->mSessionHandle.Get().Value(), delegate.mpReadHandler); delegate.mpReadHandler->mExchangeCtx.Grab(exchange); @@ -3918,12 +3874,12 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedIn std::move(msgBuf), Messaging::SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // The server sends a data report. // The client receives the data report data and sends out status report with invalid action. // The server acks the status report. - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 3u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 3u); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); @@ -3934,16 +3890,15 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedIn TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidSubscribeResponseMessage) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -3961,17 +3916,17 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidSubscr readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 3; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 3; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); EXPECT_FALSE(msgBuf.IsNull()); @@ -3990,35 +3945,35 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidSubscr // 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(*mpTestContext, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*this, readClient.mExchange.Get()); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 4u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 4u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; readClient.OnMessageReceived(readClient.mExchange.Get(), payloadHeader, std::move(msgBuf)); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // TODO: Need to validate what status is being sent to the ReadHandler // The ReadHandler's exchange is still open when we synthesize the subscribe response. // Since we synthesized the subscribe response to the ReadClient, instead of sending it from the ReadHandler, // the only messages here are the ReadClient's StatusResponse to the unexpected message and an MRP ack. - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); EXPECT_EQ(delegate.mError, CHIP_ERROR_INVALID_SUBSCRIPTION); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Read Client create the subscription, handler sends unsolicited malformed report with invalid subscription id to client, @@ -4026,16 +3981,15 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidSubscr TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedReportMessageWithInvalidSubscriptionId) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); chip::app::AttributePathParams attributePathParams[2]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -4053,13 +4007,13 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedRe readPrepareParams.mMaxIntervalCeilingSeconds = 5; { - mpTestContext->GetLoopback().mSentMessageCount = 0; - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + GetLoopback().mSentMessageCount = 0; + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 5u); + DrainAndServiceIO(); + EXPECT_EQ(GetLoopback().mSentMessageCount, 5u); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); @@ -4075,8 +4029,8 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedRe EXPECT_EQ(writer.Finalize(&msgBuf), CHIP_NO_ERROR); - mpTestContext->GetLoopback().mSentMessageCount = 0; - auto exchange = InteractionModelEngine::GetInstance()->GetExchangeManager()->NewContext( + GetLoopback().mSentMessageCount = 0; + auto exchange = InteractionModelEngine::GetInstance()->GetExchangeManager()->NewContext( delegate.mpReadHandler->mSessionHandle.Get().Value(), delegate.mpReadHandler); delegate.mpReadHandler->mExchangeCtx.Grab(exchange); @@ -4085,13 +4039,13 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedRe std::move(msgBuf), Messaging::SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // The server sends a data report. // The client receives the data report data and sends out status report with invalid subsciption. // The server should respond with a status report of its own, leading to 4 messages (because // the client would ack the server's status report), just sends an ack to the status report it got. - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 3u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 3u); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); @@ -4103,7 +4057,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedRe TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadChunkingInvalidSubscriptionId) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -4111,8 +4065,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadChunkingInvalidSubscriptionId) MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); EXPECT_FALSE(delegate.mGotEventResponse); chip::app::AttributePathParams attributePathParams[1]; @@ -4121,24 +4074,24 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadChunkingInvalidSubscriptionId) attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 3; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 3; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); EXPECT_FALSE(msgBuf.IsNull()); @@ -4157,36 +4110,36 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadChunkingInvalidSubscriptionId) // 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(*mpTestContext, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*this, readClient.mExchange.Get()); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 4u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 4u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; readClient.OnMessageReceived(readClient.mExchange.Get(), payloadHeader, std::move(msgBuf)); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // TODO: Need to validate what status is being sent to the ReadHandler // The ReadHandler's exchange is still open when we synthesize the report data message. // Since we synthesized the second report data message to the ReadClient with invalid subscription id, instead of // sending it from the ReadHandler, the only messages here are the ReadClient's StatusResponse to the unexpected message // and an MRP ack. - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); EXPECT_EQ(delegate.mError, CHIP_ERROR_INVALID_SUBSCRIPTION); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Read Client sends a malformed subscribe request, interaction model engine fails to parse the request and generates a status @@ -4194,19 +4147,18 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadChunkingInvalidSubscriptionId) TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedSubscribeRequest) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); System::PacketBufferHandle msgBuf; @@ -4226,12 +4178,12 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedSubscribeReques Messaging::SendFlags(Messaging::SendMessageFlags::kExpectResponse)), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // Read Client sends a malformed read request, interaction model engine fails to parse the request and generates a status report @@ -4239,19 +4191,18 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedSubscribeReques TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedReadRequest1) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); System::PacketBufferHandle msgBuf; @@ -4269,12 +4220,12 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedReadRequest1) EXPECT_EQ(readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::ReadRequest, std::move(msgBuf), Messaging::SendFlags(Messaging::SendMessageFlags::kExpectResponse)), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // Read Client sends a malformed read request, read handler fails to parse the request and generates a status report to client, @@ -4282,19 +4233,18 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedReadRequest1) TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedReadRequest2) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Read); System::PacketBufferHandle msgBuf; @@ -4312,13 +4262,13 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedReadRequest2) EXPECT_EQ(readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::ReadRequest, std::move(msgBuf), Messaging::SendFlags(Messaging::SendMessageFlags::kExpectResponse)), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); ChipLogError(DataManagement, "The error is %s", ErrorStr(delegate.mError)); EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // Read Client creates a subscription with the server, server sends chunked reports, after the handler sends out the first @@ -4326,14 +4276,13 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedReadRequest2) TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendUnknownMessage) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); chip::app::AttributePathParams attributePathParams[1]; // Mock Attribute 4 is a big attribute, with 6 large OCTET_STRING @@ -4341,34 +4290,34 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendUnknownMessage) attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(*mpTestContext, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*this, readClient.mExchange.Get()); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); - mpTestContext->GetLoopback().mSentMessageCount = 0; + GetLoopback().mSentMessageCount = 0; // Server sends out status report, client should send status report along with Piggybacking ack, but we don't do that // Instead, we send out unknown message to server @@ -4381,19 +4330,19 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendUnknownMessage) writer.Finalize(&msgBuf); readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::WriteRequest, std::move(msgBuf)); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // client sends invalid write request, server sends out status report with invalid action and closes, client replies // with status report server replies with MRP Ack - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 4u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 4u); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Read Client creates a subscription with the server, server sends chunked reports, after the handler sends out invalid status @@ -4401,14 +4350,13 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendUnknownMessage) TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendInvalidStatusReport) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); chip::app::AttributePathParams attributePathParams[1]; // Mock Attribute 4 is a big attribute, with 6 large OCTET_STRING @@ -4416,30 +4364,30 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendInvalidStatusReport) attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(4); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = attributePathParams; readPrepareParams.mAttributePathParamsListSize = 1; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(readClient.SendRequest(readPrepareParams), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Since we are dropping packets, things are not getting acked. Set up // our MRP state to look like what it would have looked like if the // packet had not gotten dropped. - PretendWeGotReplyFromServer(*mpTestContext, readClient.mExchange.Get()); + PretendWeGotReplyFromServer(*this, readClient.mExchange.Get()); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); - mpTestContext->GetLoopback().mSentMessageCount = 0; + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); + GetLoopback().mSentMessageCount = 0; EXPECT_EQ(engine->GetNumActiveReadHandlers(), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); @@ -4452,20 +4400,20 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendInvalidStatusReport) writer.Finalize(&msgBuf); readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::StatusResponse, std::move(msgBuf)); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // client sends malformed status response, server sends out status report with invalid action and close, client replies // with status report server replies with MRP Ack - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 4u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 4u); EXPECT_EQ(engine->GetNumActiveReadHandlers(), 0u); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Read Client sends a malformed subscribe request, the server fails to parse the request and generates a status report to the @@ -4473,19 +4421,18 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendInvalidStatusReport) TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerInvalidSubscribeRequest) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); System::PacketBufferHandle msgBuf; @@ -4503,12 +4450,12 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerInvalidSubscribeRequest) EXPECT_EQ(readClient.mExchange->SendMessage(Protocols::InteractionModel::MsgType::SubscribeRequest, std::move(msgBuf), Messaging::SendFlags(Messaging::SendMessageFlags::kExpectResponse)), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // Create the subscription, then remove the corresponding fabric in client and handler, the corresponding @@ -4516,7 +4463,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerInvalidSubscribeRequest) TEST_F(TestReadInteraction, TestSubscribeInvalidateFabric) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -4524,10 +4471,9 @@ TEST_F(TestReadInteraction, TestSubscribeInvalidateFabric) MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = new chip::app::AttributePathParams[1]; readPrepareParams.mAttributePathParamsListSize = 1; @@ -4539,40 +4485,40 @@ TEST_F(TestReadInteraction, TestSubscribeInvalidateFabric) readPrepareParams.mMaxIntervalCeilingSeconds = 0; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; EXPECT_EQ(readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); ASSERT_NE(engine->ActiveHandlerAt(0), nullptr); delegate.mpReadHandler = engine->ActiveHandlerAt(0); - mpTestContext->GetFabricTable().Delete(mpTestContext->GetAliceFabricIndex()); + GetFabricTable().Delete(GetAliceFabricIndex()); EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 0u); - mpTestContext->GetFabricTable().Delete(mpTestContext->GetBobFabricIndex()); + GetFabricTable().Delete(GetBobFabricIndex()); EXPECT_EQ(delegate.mError, CHIP_ERROR_IM_FABRIC_DELETED); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateAliceFabric(); - mpTestContext->CreateBobFabric(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateAliceFabric(); + CreateBobFabric(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); engine->Shutdown(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F_FROM_FIXTURE(TestReadInteraction, TestShutdownSubscription) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -4580,10 +4526,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestShutdownSubscription) MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = new chip::app::AttributePathParams[1]; readPrepareParams.mAttributePathParamsListSize = 1; @@ -4595,14 +4540,14 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestShutdownSubscription) readPrepareParams.mMaxIntervalCeilingSeconds = 0; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; EXPECT_EQ(readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); EXPECT_EQ(engine->GetNumActiveReadHandlers(ReadHandler::InteractionType::Subscribe), 1u); @@ -4613,7 +4558,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestShutdownSubscription) } engine->Shutdown(); EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } /** @@ -4624,18 +4569,17 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestShutdownSubscription) TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscriptionReportWithDefunctSession) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); MockInteractionModelApp delegate; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), gReportScheduler), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); AttributePathParams subscribePath(chip::Test::kMockEndpoint3, chip::Test::MockClusterId(2), chip::Test::MockAttributeId(1)); - ReadPrepareParams readPrepareParams(mpTestContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mpAttributePathParamsList = &subscribePath; readPrepareParams.mAttributePathParamsListSize = 1; @@ -4643,14 +4587,14 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscriptionReportWithDefunctSessio readPrepareParams.mMaxIntervalCeilingSeconds = 0; { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpTestContext->GetExchangeManager(), delegate, + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, chip::app::ReadClient::InteractionType::Subscribe); delegate.mGotReport = false; EXPECT_EQ(readClient.SendSubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); EXPECT_EQ(delegate.mNumAttributeResponse, 1); @@ -4663,13 +4607,13 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscriptionReportWithDefunctSessio // Verify that the session we will reset later is the one we will mess // with now. - EXPECT_EQ(SessionHandle(*readHandler->GetSession()), mpTestContext->GetSessionAliceToBob()); + EXPECT_EQ(SessionHandle(*readHandler->GetSession()), GetSessionAliceToBob()); // Test that we send reports as needed. delegate.mGotReport = false; delegate.mNumAttributeResponse = 0; engine->GetReportingEngine().SetDirty(subscribePath); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mGotReport); EXPECT_EQ(delegate.mNumAttributeResponse, 1); @@ -4684,7 +4628,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscriptionReportWithDefunctSessio delegate.mNumAttributeResponse = 0; engine->GetReportingEngine().SetDirty(subscribePath); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_FALSE(delegate.mGotReport); EXPECT_EQ(delegate.mNumAttributeResponse, 0); @@ -4694,11 +4638,11 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscriptionReportWithDefunctSessio } engine->Shutdown(); EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); // Get rid of our defunct session. - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->CreateSessionAliceToBob(); + ExpireSessionAliceToBob(); + CreateSessionAliceToBob(); } } // namespace app diff --git a/src/app/tests/TestReportScheduler.cpp b/src/app/tests/TestReportScheduler.cpp index dc54395149bbe4..bd8cd11041dacf 100644 --- a/src/app/tests/TestReportScheduler.cpp +++ b/src/app/tests/TestReportScheduler.cpp @@ -26,8 +26,6 @@ #include namespace { -using TestContext = chip::Test::AppContext; - class NullReadHandlerCallback : public chip::app::ReadHandler::ManagementCallback { public: @@ -52,39 +50,9 @@ using Milliseconds64 = System::Clock::Milliseconds64; static const size_t kNumMaxReadHandlers = 16; -class TestReportScheduler : public ::testing::Test +class TestReportScheduler : public chip::Test::AppContext { public: - static void SetUpTestSuite() - { - mpTestContext = new chip::Test::AppContext; - mpTestContext->SetUpTestSuite(); - } - static void TearDownTestSuite() - { - mpTestContext->TearDownTestSuite(); - if (mpTestContext != nullptr) - { - delete mpTestContext; - } - } - - void SetUp() override - { - - if (mpTestContext != nullptr) - { - mpTestContext->SetUp(); - } - } - void TearDown() override - { - if (mpTestContext != nullptr) - { - mpTestContext->TearDown(); - } - } - void TestReadHandlerList(); void TestReportTiming(); void TestObserverCallbacks(); @@ -125,12 +93,8 @@ class TestReportScheduler : public ::testing::Test return ret; } - - static chip::Test::AppContext * mpTestContext; }; -chip::Test::AppContext * TestReportScheduler::mpTestContext = nullptr; - class TestTimerDelegate : public ReportScheduler::TimerDelegate { public: @@ -300,7 +264,7 @@ TEST_F_FROM_FIXTURE(TestReportScheduler, TestReadHandlerList) NullReadHandlerCallback nullCallback; // exchange context - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToAlice(nullptr, false); // Read handler pool ObjectPool readHandlerPool; @@ -319,7 +283,7 @@ TEST_F_FROM_FIXTURE(TestReportScheduler, TestReadHandlerList) EXPECT_EQ(readHandlerPool.Allocated(), kNumMaxReadHandlers); EXPECT_EQ(sScheduler.GetNumReadHandlers(), kNumMaxReadHandlers); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 1u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 1u); // Test unregister first ReadHandler uint32_t target = 0; @@ -356,7 +320,7 @@ TEST_F_FROM_FIXTURE(TestReportScheduler, TestReadHandlerList) readHandlerPool.ReleaseAll(); exchangeCtx->Close(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F_FROM_FIXTURE(TestReportScheduler, TestReportTiming) @@ -364,7 +328,7 @@ TEST_F_FROM_FIXTURE(TestReportScheduler, TestReportTiming) NullReadHandlerCallback nullCallback; // exchange context - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToAlice(nullptr, false); // Read handler pool ObjectPool readHandlerPool; @@ -424,7 +388,7 @@ TEST_F_FROM_FIXTURE(TestReportScheduler, TestReportTiming) sScheduler.UnregisterAllHandlers(); readHandlerPool.ReleaseAll(); exchangeCtx->Close(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F_FROM_FIXTURE(TestReportScheduler, TestObserverCallbacks) @@ -432,7 +396,7 @@ TEST_F_FROM_FIXTURE(TestReportScheduler, TestObserverCallbacks) NullReadHandlerCallback nullCallback; // exchange context - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToAlice(nullptr, false); // Read handler pool ObjectPool readHandlerPool; @@ -499,7 +463,7 @@ TEST_F_FROM_FIXTURE(TestReportScheduler, TestObserverCallbacks) readHandlerPool.ReleaseAll(); exchangeCtx->Close(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F_FROM_FIXTURE(TestReportScheduler, TestSynchronizedScheduler) @@ -507,7 +471,7 @@ TEST_F_FROM_FIXTURE(TestReportScheduler, TestSynchronizedScheduler) NullReadHandlerCallback nullCallback; // exchange context - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(nullptr, false); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToAlice(nullptr, false); // First test: ReadHandler 2 merge on ReadHandler 1 max interval // Read handler pool @@ -839,7 +803,7 @@ TEST_F_FROM_FIXTURE(TestReportScheduler, TestSynchronizedScheduler) syncScheduler.UnregisterAllHandlers(); readHandlerPool.ReleaseAll(); exchangeCtx->Close(); - EXPECT_EQ(mpTestContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } } // namespace reporting diff --git a/src/app/tests/TestReportingEngine.cpp b/src/app/tests/TestReportingEngine.cpp index 97d179b4e72dcc..341428fb7118d9 100644 --- a/src/app/tests/TestReportingEngine.cpp +++ b/src/app/tests/TestReportingEngine.cpp @@ -39,8 +39,6 @@ #include #include -using TestContext = chip::Test::AppContext; - namespace chip { constexpr ClusterId kTestClusterId = 6; @@ -51,26 +49,9 @@ constexpr chip::AttributeId kTestFieldId2 = 2; namespace app { namespace reporting { -std::unique_ptr mpTestContext; - -class TestReportingEngine : public ::testing::Test +class TestReportingEngine : public chip::Test::AppContext { public: - static void SetUpTestSuite() - { - - mpTestContext = std::make_unique(); - ASSERT_NE(mpTestContext, nullptr); - mpTestContext->SetUpTestSuite(); - } - static void TearDownTestSuite() - { - mpTestContext->TearDownTestSuite(); - mpTestContext.reset(); - } - void SetUp() { mpTestContext->SetUp(); } - void TearDown() { mpTestContext->TearDown(); } - template static bool VerifyDirtySetContent(const Args &... args); static bool InsertToDirtySet(const AttributePathParams & aPath); @@ -161,11 +142,11 @@ TEST_F_FROM_FIXTURE(TestReportingEngine, TestBuildAndSendSingleReportData) ReadRequestMessage::Builder readRequestBuilder; DummyDelegate dummy; - EXPECT_EQ(InteractionModelEngine::GetInstance()->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + EXPECT_EQ(InteractionModelEngine::GetInstance()->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); TestExchangeDelegate delegate; - Messaging::ExchangeContext * exchangeCtx = mpTestContext->NewExchangeToAlice(&delegate); + Messaging::ExchangeContext * exchangeCtx = NewExchangeToAlice(&delegate); writer.Init(std::move(readRequestbuf)); EXPECT_EQ(readRequestBuilder.Init(&writer), CHIP_NO_ERROR); @@ -193,12 +174,12 @@ TEST_F_FROM_FIXTURE(TestReportingEngine, TestBuildAndSendSingleReportData) EXPECT_EQ(InteractionModelEngine::GetInstance()->GetReportingEngine().BuildAndSendSingleReportData(&readHandler), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); } TEST_F_FROM_FIXTURE(TestReportingEngine, TestMergeOverlappedAttributePath) { - EXPECT_EQ(InteractionModelEngine::GetInstance()->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + EXPECT_EQ(InteractionModelEngine::GetInstance()->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); @@ -253,7 +234,7 @@ TEST_F_FROM_FIXTURE(TestReportingEngine, TestMergeOverlappedAttributePath) TEST_F_FROM_FIXTURE(TestReportingEngine, TestMergeAttributePathWhenDirtySetPoolExhausted) { - EXPECT_EQ(InteractionModelEngine::GetInstance()->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), + EXPECT_EQ(InteractionModelEngine::GetInstance()->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); diff --git a/src/app/tests/TestTimedHandler.cpp b/src/app/tests/TestTimedHandler.cpp index 2625257781d314..30bf31e3ceb58a 100644 --- a/src/app/tests/TestTimedHandler.cpp +++ b/src/app/tests/TestTimedHandler.cpp @@ -29,8 +29,6 @@ #include #include -using TestContext = chip::Test::AppContext; - namespace chip { namespace app { @@ -39,33 +37,14 @@ using namespace Protocols::InteractionModel; namespace { -class TestTimedHandler : public ::testing::Test +class TestTimedHandler : public chip::Test::AppContext { public: - static void SetUpTestSuite() - { - - mpTestContext = new TestContext; - mpTestContext->SetUpTestSuite(); - } - static void TearDownTestSuite() - { - mpTestContext->TearDownTestSuite(); - delete mpTestContext; - } - - void SetUp() override { mpTestContext->SetUp(); } - void TearDown() override { mpTestContext->TearDown(); } - - static TestContext * mpTestContext; - - static void TestFollowingMessageFastEnough(MsgType aMsgType); - static void TestFollowingMessageTooSlow(MsgType aMsgType); - static void GenerateTimedRequest(uint16_t aTimeoutValue, System::PacketBufferHandle & aPayload); + void TestFollowingMessageFastEnough(MsgType aMsgType); + void TestFollowingMessageTooSlow(MsgType aMsgType); + void GenerateTimedRequest(uint16_t aTimeoutValue, System::PacketBufferHandle & aPayload); }; -TestContext * TestTimedHandler::mpTestContext = nullptr; - class TestExchangeDelegate : public Messaging::ExchangeDelegate { CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * aExchangeContext, const PayloadHeader & aPayloadHeader, @@ -124,7 +103,7 @@ void TestTimedHandler::TestFollowingMessageFastEnough(MsgType aMsgType) GenerateTimedRequest(500, payload); TestExchangeDelegate delegate; - ExchangeContext * exchange = mpTestContext->NewExchangeToAlice(&delegate); + ExchangeContext * exchange = NewExchangeToAlice(&delegate); ASSERT_NE(exchange, nullptr); EXPECT_FALSE(delegate.mNewMessageReceived); @@ -133,7 +112,7 @@ void TestTimedHandler::TestFollowingMessageFastEnough(MsgType aMsgType) EXPECT_EQ(exchange->SendMessage(MsgType::TimedRequest, std::move(payload), SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mNewMessageReceived); EXPECT_TRUE(delegate.mLastMessageWasStatus); EXPECT_EQ(delegate.mError, CHIP_NO_ERROR); @@ -148,7 +127,7 @@ void TestTimedHandler::TestFollowingMessageFastEnough(MsgType aMsgType) EXPECT_EQ(exchange->SendMessage(aMsgType, std::move(payload), SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mNewMessageReceived); EXPECT_TRUE(delegate.mLastMessageWasStatus); EXPECT_NE(StatusIB(delegate.mError).mStatus, Status::UnsupportedAccess); @@ -156,7 +135,7 @@ void TestTimedHandler::TestFollowingMessageFastEnough(MsgType aMsgType) TEST_F(TestTimedHandler, TestInvokeFastEnough) { - TestTimedHandler::TestFollowingMessageFastEnough(MsgType::InvokeCommandRequest); + TestFollowingMessageFastEnough(MsgType::InvokeCommandRequest); } TEST_F(TestTimedHandler, TestWriteFastEnough) @@ -171,7 +150,7 @@ void TestTimedHandler::TestFollowingMessageTooSlow(MsgType aMsgType) GenerateTimedRequest(50, payload); TestExchangeDelegate delegate; - ExchangeContext * exchange = mpTestContext->NewExchangeToAlice(&delegate); + ExchangeContext * exchange = NewExchangeToAlice(&delegate); ASSERT_NE(exchange, nullptr); EXPECT_FALSE(delegate.mNewMessageReceived); @@ -180,7 +159,7 @@ void TestTimedHandler::TestFollowingMessageTooSlow(MsgType aMsgType) EXPECT_EQ(exchange->SendMessage(MsgType::TimedRequest, std::move(payload), SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mNewMessageReceived); EXPECT_TRUE(delegate.mLastMessageWasStatus); EXPECT_EQ(delegate.mError, CHIP_NO_ERROR); @@ -198,7 +177,7 @@ void TestTimedHandler::TestFollowingMessageTooSlow(MsgType aMsgType) EXPECT_EQ(exchange->SendMessage(aMsgType, std::move(payload), SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mNewMessageReceived); EXPECT_TRUE(delegate.mLastMessageWasStatus); EXPECT_EQ(StatusIB(delegate.mError).mStatus, Status::UnsupportedAccess); @@ -222,14 +201,14 @@ TEST_F(TestTimedHandler, TestInvokeNeverComes) GenerateTimedRequest(50, payload); TestExchangeDelegate delegate; - ExchangeContext * exchange = mpTestContext->NewExchangeToAlice(&delegate); + ExchangeContext * exchange = NewExchangeToAlice(&delegate); ASSERT_NE(exchange, nullptr); EXPECT_FALSE(delegate.mNewMessageReceived); EXPECT_EQ(exchange->SendMessage(MsgType::TimedRequest, std::move(payload), SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(delegate.mNewMessageReceived); EXPECT_TRUE(delegate.mLastMessageWasStatus); EXPECT_EQ(delegate.mError, CHIP_NO_ERROR); diff --git a/src/app/tests/TestWriteInteraction.cpp b/src/app/tests/TestWriteInteraction.cpp index 3f03b976e2937f..896f29870b28ab 100644 --- a/src/app/tests/TestWriteInteraction.cpp +++ b/src/app/tests/TestWriteInteraction.cpp @@ -49,30 +49,16 @@ chip::TestPersistentStorageDelegate gTestStorage; chip::Crypto::DefaultSessionKeystore gSessionKeystore; chip::Credentials::GroupDataProviderImpl gGroupsProvider(kMaxGroupsPerFabric, kMaxGroupKeysPerFabric); -using TestContext = chip::Test::AppContext; - } // namespace namespace chip { namespace app { -class TestWriteInteraction : public ::testing::Test +class TestWriteInteraction : public chip::Test::AppContext { public: - static void SetUpTestSuite() - { - mpTestContext = new TestContext; - mpTestContext->SetUpTestSuite(); - } - - static void TearDownTestSuite() - { - mpTestContext->TearDownTestSuite(); - delete mpTestContext; - } void SetUp() override { - - mpTestContext->SetUp(); + chip::Test::AppContext::SetUp(); gTestStorage.ClearStorage(); gGroupsProvider.SetStorageDelegate(&gTestStorage); @@ -82,8 +68,8 @@ class TestWriteInteraction : public ::testing::Test uint8_t buf[sizeof(chip::CompressedFabricId)]; chip::MutableByteSpan span(buf); - ASSERT_EQ(mpTestContext->GetBobFabric()->GetCompressedFabricIdBytes(span), CHIP_NO_ERROR); - ASSERT_EQ(chip::GroupTesting::InitData(&gGroupsProvider, mpTestContext->GetBobFabricIndex(), span), CHIP_NO_ERROR); + ASSERT_EQ(GetBobFabric()->GetCompressedFabricIdBytes(span), CHIP_NO_ERROR); + ASSERT_EQ(chip::GroupTesting::InitData(&gGroupsProvider, GetBobFabricIndex(), span), CHIP_NO_ERROR); } void TearDown() override { @@ -92,11 +78,9 @@ class TestWriteInteraction : public ::testing::Test { provider->Finish(); } - mpTestContext->TearDown(); + chip::Test::AppContext::TearDown(); } - static TestContext * mpTestContext; - void TestWriteClient(); void TestWriteClientGroup(); void TestWriteHandlerReceiveInvalidMessage(); @@ -111,8 +95,6 @@ class TestWriteInteraction : public ::testing::Test static void GenerateWriteResponse(System::PacketBufferHandle & aPayload); }; -TestContext * TestWriteInteraction::mpTestContext = nullptr; - class TestExchangeDelegate : public Messaging::ExchangeDelegate { CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * ec, const PayloadHeader & payloadHeader, @@ -261,14 +243,14 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteClient) { TestWriteClientCallback callback; - app::WriteClient writeClient(&mpTestContext->GetExchangeManager(), &callback, /* aTimedWriteTimeoutMs = */ NullOptional); + app::WriteClient writeClient(&GetExchangeManager(), &callback, /* aTimedWriteTimeoutMs = */ NullOptional); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); AddAttributeDataIB(writeClient); - EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(writeClient.SendWriteRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); GenerateWriteResponse(buf); @@ -276,7 +258,7 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteClient) writeClient.Close(); - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); EXPECT_EQ(rm->TestGetCountRetransTable(), 0); } @@ -284,17 +266,17 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteClientGroup) { TestWriteClientCallback callback; - app::WriteClient writeClient(&mpTestContext->GetExchangeManager(), &callback, /* aTimedWriteTimeoutMs = */ NullOptional); + app::WriteClient writeClient(&GetExchangeManager(), &callback, /* aTimedWriteTimeoutMs = */ NullOptional); System::PacketBufferHandle buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); AddAttributeDataIB(writeClient); - SessionHandle groupSession = mpTestContext->GetSessionBobToFriends(); + SessionHandle groupSession = GetSessionBobToFriends(); EXPECT_TRUE(groupSession->IsGroupSession()); EXPECT_EQ(writeClient.SendWriteRequest(groupSession), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); // The WriteClient should be shutdown once we SendWriteRequest for group. EXPECT_EQ(writeClient.mState, WriteClient::State::AwaitingDestruction); @@ -319,7 +301,7 @@ TEST_F(TestWriteInteraction, TestWriteHandler) GenerateWriteRequest(messageIsTimed, buf); TestExchangeDelegate delegate; - Messaging::ExchangeContext * exchange = mpTestContext->NewExchangeToBob(&delegate); + Messaging::ExchangeContext * exchange = NewExchangeToBob(&delegate); Status status = writeHandler.OnWriteRequest(exchange, std::move(buf), transactionIsTimed); if (messageIsTimed == transactionIsTimed) @@ -331,9 +313,9 @@ TEST_F(TestWriteInteraction, TestWriteHandler) EXPECT_EQ(status, Status::UnsupportedAccess); } - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); EXPECT_EQ(rm->TestGetCountRetransTable(), 0); } } @@ -342,15 +324,13 @@ TEST_F(TestWriteInteraction, TestWriteHandler) TEST_F(TestWriteInteraction, TestWriteRoundtripWithClusterObjects) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -375,9 +355,9 @@ TEST_F(TestWriteInteraction, TestWriteRoundtripWithClusterObjects) EXPECT_EQ(callback.mOnSuccessCalled, 0); - EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(writeClient.SendWriteRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(callback.mOnSuccessCalled, 1); @@ -408,15 +388,13 @@ TEST_F(TestWriteInteraction, TestWriteRoundtripWithClusterObjects) TEST_F(TestWriteInteraction, TestWriteRoundtripWithClusterObjectsVersionMatch) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -435,9 +413,9 @@ TEST_F(TestWriteInteraction, TestWriteRoundtripWithClusterObjectsVersionMatch) EXPECT_EQ(callback.mOnSuccessCalled, 0); - EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(writeClient.SendWriteRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(callback.mOnSuccessCalled, 1); EXPECT_EQ(callback.mOnErrorCalled, 0); @@ -454,15 +432,13 @@ TEST_F(TestWriteInteraction, TestWriteRoundtripWithClusterObjectsVersionMatch) TEST_F(TestWriteInteraction, TestWriteRoundtripWithClusterObjectsVersionMismatch) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -484,9 +460,9 @@ TEST_F(TestWriteInteraction, TestWriteRoundtripWithClusterObjectsVersionMismatch EXPECT_EQ(callback.mOnSuccessCalled, 0); - EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(writeClient.SendWriteRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(callback.mOnSuccessCalled, 1); EXPECT_EQ(callback.mOnErrorCalled, 0); @@ -503,15 +479,13 @@ TEST_F(TestWriteInteraction, TestWriteRoundtripWithClusterObjectsVersionMismatch TEST_F(TestWriteInteraction, TestWriteRoundtrip) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -522,9 +496,9 @@ TEST_F(TestWriteInteraction, TestWriteRoundtrip) EXPECT_EQ(callback.mOnErrorCalled, 0); EXPECT_EQ(callback.mOnDoneCalled, 0); - EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); + EXPECT_EQ(writeClient.SendWriteRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(callback.mOnSuccessCalled, 1); EXPECT_EQ(callback.mOnErrorCalled, 0); @@ -541,37 +515,35 @@ TEST_F(TestWriteInteraction, TestWriteRoundtrip) #if CONFIG_BUILD_FOR_HOST_UNIT_TEST TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteHandlerReceiveInvalidMessage) { - auto sessionHandle = mpTestContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); app::AttributePathParams attributePath(2, 3, 4); - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback writeCallback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); // Reserve all except the last 128 bytes, so that we make sure to chunk. - app::WriteClient writeClient(&mpTestContext->GetExchangeManager(), &writeCallback, Optional::Missing(), + app::WriteClient writeClient(&GetExchangeManager(), &writeCallback, Optional::Missing(), static_cast(kMaxSecureSduLengthBytes - 128) /* reserved buffer size */); ByteSpan list[5]; EXPECT_EQ(writeClient.EncodeAttribute(attributePath, app::DataModel::List(list, 5)), CHIP_NO_ERROR); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 2; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 2; EXPECT_EQ(writeClient.SendWriteRequest(sessionHandle), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 1u); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 3u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 3u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); EXPECT_FALSE(msgBuf.IsNull()); @@ -590,65 +562,63 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteHandlerReceiveInvalidMessage) rm->ClearRetransTable(writeClient.mExchangeCtx.Get()); rm->ClearRetransTable(writeHandler->mExchangeCtx.Get()); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; writeHandler->OnMessageReceived(writeHandler->mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(writeCallback.mLastErrorReason.mStatus, Protocols::InteractionModel::Status::InvalidAction); EXPECT_EQ(InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 0u); engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + 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. TEST_F(TestWriteInteraction, TestWriteHandlerInvalidateFabric) { - auto sessionHandle = mpTestContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); app::AttributePathParams attributePath(2, 3, 4); - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback writeCallback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); // Reserve all except the last 128 bytes, so that we make sure to chunk. - app::WriteClient writeClient(&mpTestContext->GetExchangeManager(), &writeCallback, Optional::Missing(), + app::WriteClient writeClient(&GetExchangeManager(), &writeCallback, Optional::Missing(), static_cast(kMaxSecureSduLengthBytes - 128) /* reserved buffer size */); ByteSpan list[5]; EXPECT_EQ(writeClient.EncodeAttribute(attributePath, app::DataModel::List(list, 5)), CHIP_NO_ERROR); - mpTestContext->GetLoopback().mDroppedMessageCount = 0; - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 2; + GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 2; EXPECT_EQ(writeClient.SendWriteRequest(sessionHandle), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 1u); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 3u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 3u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); - mpTestContext->GetFabricTable().Delete(mpTestContext->GetAliceFabricIndex()); + GetFabricTable().Delete(GetAliceFabricIndex()); EXPECT_EQ(InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 0u); engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateAliceFabric(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateAliceFabric(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } #endif @@ -657,15 +627,13 @@ TEST_F(TestWriteInteraction, TestWriteHandlerInvalidateFabric) TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage1) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -676,15 +644,15 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage1) EXPECT_EQ(callback.mOnErrorCalled, 0); EXPECT_EQ(callback.mOnDoneCalled, 0); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; - EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + GetLoopback().mDroppedMessageCount = 0; + EXPECT_EQ(writeClient.SendWriteRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); + DrainAndServiceIO(); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); EXPECT_FALSE(msgBuf.IsNull()); @@ -700,15 +668,15 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage1) // 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(*mpTestContext, writeClient.mExchangeCtx.Get()); + PretendWeGotReplyFromServer(*this, writeClient.mExchangeCtx.Get()); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(writeClient.OnMessageReceived(writeClient.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), CHIP_ERROR_INVALID_MESSAGE_TYPE); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(callback.mError, CHIP_ERROR_INVALID_MESSAGE_TYPE); EXPECT_EQ(callback.mOnSuccessCalled, 0); @@ -717,28 +685,26 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage1) // 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 - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Write Client sends a write request, receives a malformed write response message, sends a Status Report. TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage2) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -749,15 +715,15 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage2) EXPECT_EQ(callback.mOnErrorCalled, 0); EXPECT_EQ(callback.mOnDoneCalled, 0); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; - EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + GetLoopback().mDroppedMessageCount = 0; + EXPECT_EQ(writeClient.SendWriteRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); + DrainAndServiceIO(); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); EXPECT_FALSE(msgBuf.IsNull()); @@ -773,15 +739,15 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage2) // 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(*mpTestContext, writeClient.mExchangeCtx.Get()); + PretendWeGotReplyFromServer(*this, writeClient.mExchangeCtx.Get()); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(writeClient.OnMessageReceived(writeClient.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), CHIP_ERROR_END_OF_TLV); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(callback.mError, CHIP_ERROR_END_OF_TLV); EXPECT_EQ(callback.mOnSuccessCalled, 0); @@ -789,28 +755,26 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage2) 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 - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Write Client sends a write request, receives a malformed status response message. TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage3) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -821,15 +785,15 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage3) EXPECT_EQ(callback.mOnErrorCalled, 0); EXPECT_EQ(callback.mOnDoneCalled, 0); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; - EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + GetLoopback().mDroppedMessageCount = 0; + EXPECT_EQ(writeClient.SendWriteRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); + DrainAndServiceIO(); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); EXPECT_FALSE(msgBuf.IsNull()); @@ -845,15 +809,15 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage3) // 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(*mpTestContext, writeClient.mExchangeCtx.Get()); + PretendWeGotReplyFromServer(*this, writeClient.mExchangeCtx.Get()); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(writeClient.OnMessageReceived(writeClient.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), CHIP_ERROR_END_OF_TLV); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(callback.mError, CHIP_ERROR_END_OF_TLV); EXPECT_EQ(callback.mOnSuccessCalled, 0); @@ -862,28 +826,26 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage3) // 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. - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } // Write Client sends a write request, receives a busy status response message. TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage4) { - Messaging::ReliableMessageMgr * rm = mpTestContext->GetExchangeManager().GetReliableMessageMgr(); + Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); TestWriteClientCallback callback; auto * engine = chip::app::InteractionModelEngine::GetInstance(); - EXPECT_EQ(engine->Init(&mpTestContext->GetExchangeManager(), &mpTestContext->GetFabricTable(), - app::reporting::GetDefaultReportScheduler()), - CHIP_NO_ERROR); + EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), app::reporting::GetDefaultReportScheduler()), CHIP_NO_ERROR); app::WriteClient writeClient(engine->GetExchangeManager(), &callback, Optional::Missing()); @@ -894,15 +856,15 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage4) EXPECT_EQ(callback.mOnErrorCalled, 0); EXPECT_EQ(callback.mOnDoneCalled, 0); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 1; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 1; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; - EXPECT_EQ(writeClient.SendWriteRequest(mpTestContext->GetSessionBobToAlice()), CHIP_NO_ERROR); - mpTestContext->DrainAndServiceIO(); + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 1; + GetLoopback().mNumMessagesToAllowBeforeDropping = 1; + GetLoopback().mDroppedMessageCount = 0; + EXPECT_EQ(writeClient.SendWriteRequest(GetSessionBobToAlice()), CHIP_NO_ERROR); + DrainAndServiceIO(); - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); - EXPECT_EQ(mpTestContext->GetLoopback().mDroppedMessageCount, 1u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mDroppedMessageCount, 1u); System::PacketBufferHandle msgBuf = System::PacketBufferHandle::New(kMaxSecureSduLengthBytes); EXPECT_FALSE(msgBuf.IsNull()); @@ -919,15 +881,15 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage4) // 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(*mpTestContext, writeClient.mExchangeCtx.Get()); + PretendWeGotReplyFromServer(*this, writeClient.mExchangeCtx.Get()); - mpTestContext->GetLoopback().mSentMessageCount = 0; - mpTestContext->GetLoopback().mNumMessagesToDrop = 0; - mpTestContext->GetLoopback().mNumMessagesToAllowBeforeDropping = 0; - mpTestContext->GetLoopback().mDroppedMessageCount = 0; + GetLoopback().mSentMessageCount = 0; + GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToAllowBeforeDropping = 0; + GetLoopback().mDroppedMessageCount = 0; EXPECT_EQ(writeClient.OnMessageReceived(writeClient.mExchangeCtx.Get(), payloadHeader, std::move(msgBuf)), CHIP_IM_GLOBAL_STATUS(Busy)); - mpTestContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(callback.mError, CHIP_IM_GLOBAL_STATUS(Busy)); EXPECT_EQ(callback.mOnSuccessCalled, 0); @@ -936,13 +898,13 @@ TEST_F_FROM_FIXTURE(TestWriteInteraction, TestWriteInvalidMessage4) // 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. - EXPECT_EQ(mpTestContext->GetLoopback().mSentMessageCount, 2u); + EXPECT_EQ(GetLoopback().mSentMessageCount, 2u); engine->Shutdown(); - mpTestContext->ExpireSessionAliceToBob(); - mpTestContext->ExpireSessionBobToAlice(); - mpTestContext->CreateSessionAliceToBob(); - mpTestContext->CreateSessionBobToAlice(); + ExpireSessionAliceToBob(); + ExpireSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); } } // namespace app diff --git a/src/controller/tests/TestEventChunking.cpp b/src/controller/tests/TestEventChunking.cpp index c7790959e6866e..641c5b4470400f 100644 --- a/src/controller/tests/TestEventChunking.cpp +++ b/src/controller/tests/TestEventChunking.cpp @@ -16,7 +16,7 @@ * limitations under the License. */ -#include +#include #include "app-common/zap-generated/ids/Attributes.h" #include "app-common/zap-generated/ids/Clusters.h" @@ -54,8 +54,6 @@ static uint8_t gInfoEventBuffer[4096]; static uint8_t gCritEventBuffer[4096]; static chip::app::CircularEventBuffer gCircularEventBuffer[3]; -using TestContext = chip::Test::AppContext; - uint32_t gIterationCount = 0; // @@ -69,31 +67,8 @@ constexpr AttributeId kTestListLargeAttribute = 8; // This attribute will be lar // The size of the attribute which is a bit larger than the size of event used in the test. constexpr size_t kSizeOfLargeAttribute = 60; -class TestEventChunking : public ::testing::Test +class TestEventChunking : public chip::Test::AppContext { -public: - // Performs shared setup for all tests in the test suite - static void SetUpTestSuite() - { - if (mpContext == nullptr) - { - mpContext = new TestContext(); - ASSERT_NE(mpContext, nullptr); - } - mpContext->SetUpTestSuite(); - } - - // Performs shared teardown for all tests in the test suite - static void TearDownTestSuite() - { - mpContext->TearDownTestSuite(); - if (mpContext != nullptr) - { - delete mpContext; - mpContext = nullptr; - } - } - protected: // Performs setup for each test in the suite void SetUp() @@ -104,13 +79,13 @@ class TestEventChunking : public ::testing::Test { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - mpContext->SetUp(); + 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(&mpContext->GetExchangeManager(), ArraySize(logStorageResources), + chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); } @@ -118,15 +93,12 @@ class TestEventChunking : public ::testing::Test void TearDown() { chip::app::EventManagement::DestroyEventManagement(); - mpContext->TearDown(); + chip::Test::AppContext::TearDown(); } - static TestContext * mpContext; - private: MonotonicallyIncreasingCounter mEventCounter; }; -TestContext * TestEventChunking::mpContext = nullptr; //clang-format off DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(testClusterAttrs) @@ -317,7 +289,7 @@ void GenerateEvents(chip::EventNumber & firstEventNumber, chip::EventNumber & la */ TEST_F(TestEventChunking, TestEventChunking) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance(); // Initialize the ember side server logic @@ -358,15 +330,15 @@ TEST_F(TestEventChunking, TestEventChunking) app::InteractionModelEngine::GetInstance()->GetReportingEngine().SetWriterReserved(static_cast(800 + i)); - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), readCallback.mBufferedCallback, + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mBufferedCallback, app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(readCallback.mEventCount, static_cast((lastEventNumber - firstEventNumber) + 1)); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); // // Stop the test if we detected an error. Otherwise, it'll be difficult to read the logs. @@ -383,7 +355,7 @@ TEST_F(TestEventChunking, TestEventChunking) // Similar to the tests above, but it will read attributes AND events TEST_F(TestEventChunking, TestMixedEventsAndAttributesChunking) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance(); // Initialize the ember side server logic @@ -426,12 +398,12 @@ TEST_F(TestEventChunking, TestMixedEventsAndAttributesChunking) app::InteractionModelEngine::GetInstance()->GetReportingEngine().SetWriterReserved(static_cast(800 + i)); - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), readCallback.mBufferedCallback, + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mBufferedCallback, app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // // Always returns the same number of attributes read (5 + revision + GlobalAttributesNotInMetadata). @@ -440,7 +412,7 @@ TEST_F(TestEventChunking, TestMixedEventsAndAttributesChunking) EXPECT_EQ(readCallback.mAttributeCount, 6 + ArraySize(GlobalAttributesNotInMetadata)); EXPECT_EQ(readCallback.mEventCount, static_cast(lastEventNumber - firstEventNumber + 1)); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); // // Stop the test if we detected an error. Otherwise, it'll be difficult to read the logs. @@ -459,7 +431,7 @@ TEST_F(TestEventChunking, TestMixedEventsAndAttributesChunking) // can be encoded in to one chunk in the tests above. This test will force it by reading only one attribtue and read many events. TEST_F(TestEventChunking, TestMixedEventsAndLargeAttributesChunking) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance(); // Initialize the ember side server logic @@ -502,18 +474,18 @@ TEST_F(TestEventChunking, TestMixedEventsAndLargeAttributesChunking) app::InteractionModelEngine::GetInstance()->GetReportingEngine().SetWriterReserved(static_cast(800 + i)); - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), readCallback.mBufferedCallback, + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mBufferedCallback, app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(readCallback.mOnReportEnd); EXPECT_EQ(readCallback.mAttributeCount, 1u); EXPECT_EQ(readCallback.mEventCount, static_cast(lastEventNumber - firstEventNumber + 1)); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); // // Stop the test if we detected an error. Otherwise, it'll be difficult to read the logs. diff --git a/src/controller/tests/TestEventNumberCaching.cpp b/src/controller/tests/TestEventNumberCaching.cpp index 4d77813262a691..f44f7ed5af78ad 100644 --- a/src/controller/tests/TestEventNumberCaching.cpp +++ b/src/controller/tests/TestEventNumberCaching.cpp @@ -16,7 +16,7 @@ * limitations under the License. */ -#include +#include #include "app-common/zap-generated/ids/Clusters.h" #include "app/ClusterStateCache.h" @@ -46,8 +46,6 @@ static uint8_t gInfoEventBuffer[4096]; static uint8_t gCritEventBuffer[4096]; static chip::app::CircularEventBuffer gCircularEventBuffer[3]; -using TestContext = chip::Test::AppContext; - // // The generated endpoint_config for the controller app has Endpoint 1 // already used in the fixed endpoint set of size 1. Consequently, let's use the next @@ -55,31 +53,8 @@ using TestContext = chip::Test::AppContext; // constexpr EndpointId kTestEndpointId = 2; -class TestEventNumberCaching : public ::testing::Test +class TestEventNumberCaching : public chip::Test::AppContext { -public: - // Performs shared setup for all tests in the test suite - static void SetUpTestSuite() - { - if (mpContext == nullptr) - { - mpContext = new TestContext(); - ASSERT_NE(mpContext, nullptr); - } - mpContext->SetUpTestSuite(); - } - - // Performs shared teardown for all tests in the test suite - static void TearDownTestSuite() - { - mpContext->TearDownTestSuite(); - if (mpContext != nullptr) - { - delete mpContext; - mpContext = nullptr; - } - } - protected: // Performs setup for each test in the suite void SetUp() @@ -90,13 +65,13 @@ class TestEventNumberCaching : public ::testing::Test { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - mpContext->SetUp(); + 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(&mpContext->GetExchangeManager(), ArraySize(logStorageResources), + chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); } @@ -104,15 +79,12 @@ class TestEventNumberCaching : public ::testing::Test void TearDown() { chip::app::EventManagement::DestroyEventManagement(); - mpContext->TearDown(); + chip::Test::AppContext::TearDown(); } - static TestContext * mpContext; - private: MonotonicallyIncreasingCounter mEventCounter; }; -TestContext * TestEventNumberCaching::mpContext = nullptr; //clang-format off DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(testClusterAttrs) @@ -168,7 +140,7 @@ void GenerateEvents(chip::EventNumber & firstEventNumber, chip::EventNumber & la */ TEST_F(TestEventNumberCaching, TestEventNumberCaching) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance(); // Initialize the ember side server logic @@ -199,12 +171,12 @@ TEST_F(TestEventNumberCaching, TestEventNumberCaching) Optional highestEventNumber; readCallback.mClusterCacheAdapter.GetHighestReceivedEventNumber(highestEventNumber); EXPECT_FALSE(highestEventNumber.HasValue()); - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), - readCallback.mClusterCacheAdapter.GetBufferedCallback(), app::ReadClient::InteractionType::Read); + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mClusterCacheAdapter.GetBufferedCallback(), + app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(readCallback.mEventsSeen, lastEventNumber - firstEventNumber + 1); @@ -223,8 +195,8 @@ TEST_F(TestEventNumberCaching, TestEventNumberCaching) // we don't receive events except ones larger than that value. // { - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), - readCallback.mClusterCacheAdapter.GetBufferedCallback(), app::ReadClient::InteractionType::Read); + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mClusterCacheAdapter.GetBufferedCallback(), + app::ReadClient::InteractionType::Read); readCallback.mClusterCacheAdapter.ClearEventCache(true); Optional highestEventNumber; @@ -242,7 +214,7 @@ TEST_F(TestEventNumberCaching, TestEventNumberCaching) EXPECT_FALSE(readParams.mEventNumber.HasValue()); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // We should only get events with event numbers larger than kHighestEventNumberSeen. EXPECT_EQ(readCallback.mEventsSeen, lastEventNumber - kHighestEventNumberSeen); @@ -256,7 +228,7 @@ TEST_F(TestEventNumberCaching, TestEventNumberCaching) readCallback.mClusterCacheAdapter.GetHighestReceivedEventNumber(highestEventNumber); EXPECT_TRUE(highestEventNumber.HasValue() && highestEventNumber.Value() == lastEventNumber); } - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); emberAfClearDynamicEndpoint(0); } diff --git a/src/controller/tests/TestReadChunking.cpp b/src/controller/tests/TestReadChunking.cpp index 8fe5e51c2b097f..97acb81bd11d20 100644 --- a/src/controller/tests/TestReadChunking.cpp +++ b/src/controller/tests/TestReadChunking.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #include "app-common/zap-generated/ids/Attributes.h" #include "app-common/zap-generated/ids/Clusters.h" @@ -46,7 +46,6 @@ #include #include -using TestContext = chip::Test::AppContext; using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; @@ -72,41 +71,7 @@ constexpr AttributeId kTestBadAttribute = constexpr int kListAttributeItems = 5; -class TestReadChunking : public ::testing::Test -{ -public: - // Performs shared setup for all tests in the test suite - static void SetUpTestSuite() - { - if (mpContext == nullptr) - { - mpContext = new TestContext(); - ASSERT_NE(mpContext, nullptr); - } - mpContext->SetUpTestSuite(); - } - - // Performs shared teardown for all tests in the test suite - static void TearDownTestSuite() - { - mpContext->TearDownTestSuite(); - if (mpContext != nullptr) - { - delete mpContext; - mpContext = nullptr; - } - } - -protected: - // Performs setup for each test in the suite - void SetUp() { mpContext->SetUp(); } - - // Performs teardown for each test in the suite - void TearDown() { mpContext->TearDown(); } - - static TestContext * mpContext; -}; -TestContext * TestReadChunking::mpContext = nullptr; +using TestReadChunking = chip::Test::AppContext; //clang-format off DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(testClusterAttrs) @@ -511,7 +476,7 @@ void TestMutableReadCallback::OnAttributeData(const app::ConcreteDataAttributePa */ TEST_F(TestReadChunking, TestChunking) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance(); // Initialize the ember side server logic @@ -542,12 +507,12 @@ TEST_F(TestReadChunking, TestChunking) app::InteractionModelEngine::GetInstance()->GetReportingEngine().SetWriterReserved(static_cast(850 + i)); - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), readCallback.mBufferedCallback, + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mBufferedCallback, app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(readCallback.mOnReportEnd); // @@ -556,7 +521,7 @@ TEST_F(TestReadChunking, TestChunking) EXPECT_EQ(readCallback.mAttributeCount, 6 + ArraySize(GlobalAttributesNotInMetadata)); readCallback.mAttributeCount = 0; - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); // // Stop the test if we detected an error. Otherwise, it'll be difficult to read the logs. @@ -573,7 +538,7 @@ TEST_F(TestReadChunking, TestChunking) // Similar to the test above, but for the list chunking feature. TEST_F(TestReadChunking, TestListChunking) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance(); // Initialize the ember side server logic @@ -617,12 +582,12 @@ TEST_F(TestReadChunking, TestListChunking) app::InteractionModelEngine::GetInstance()->GetReportingEngine().SetWriterReserved( static_cast(maxPacketSize - packetSize)); - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), readCallback.mBufferedCallback, + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mBufferedCallback, app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Up until our packets are big enough, we might just keep getting // errors due to the inability to encode even a single IB in a packet. @@ -654,7 +619,7 @@ TEST_F(TestReadChunking, TestListChunking) EXPECT_FALSE(readCallback.mBufferedCallback.mSawEmptyList); } - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); // // Stop the test if we detected an error. Otherwise, it'll be difficult to read the logs. @@ -674,7 +639,7 @@ TEST_F(TestReadChunking, TestListChunking) // Read an attribute that can never fit into the buffer. Result in an empty report, server should shutdown the transaction. TEST_F(TestReadChunking, TestBadChunking) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance(); // Initialize the ember side server logic @@ -695,12 +660,12 @@ TEST_F(TestReadChunking, TestBadChunking) TestReadCallback readCallback; { - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), readCallback.mBufferedCallback, + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mBufferedCallback, app::ReadClient::InteractionType::Read); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // The server should return an empty list as attribute data for the first report (for list chunking), and encodes nothing // (then shuts down the read handler) for the second report. @@ -711,11 +676,11 @@ TEST_F(TestReadChunking, TestBadChunking) EXPECT_FALSE(readCallback.mOnReportEnd); // The server should shutted down, while the client is still alive (pending for the attribute data.) - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // Sanity check - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); emberAfClearDynamicEndpoint(0); } @@ -725,7 +690,7 @@ TEST_F(TestReadChunking, TestBadChunking) */ TEST_F(TestReadChunking, TestDynamicEndpoint) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance(); // Initialize the ember side server logic @@ -745,21 +710,21 @@ TEST_F(TestReadChunking, TestDynamicEndpoint) { - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), readCallback.mBufferedCallback, + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mBufferedCallback, app::ReadClient::InteractionType::Subscribe); // Enable the new endpoint emberAfSetDynamicEndpoint(0, kTestEndpointId, &testEndpoint, Span(dataVersionStorage)); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(readCallback.mOnSubscriptionEstablished); readCallback.mAttributeCount = 0; emberAfSetDynamicEndpoint(0, kTestEndpointId4, &testEndpoint4, Span(dataVersionStorage)); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Ensure we have received the report, we do not care about the initial report here. // GlobalAttributesNotInMetadata attributes are not included in testClusterAttrsOnEndpoint4. @@ -774,7 +739,7 @@ TEST_F(TestReadChunking, TestDynamicEndpoint) // Disable the new endpoint emberAfEndpointEnableDisable(kTestEndpointId4, false); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // We may receive some attribute reports for descriptor cluster, but we do not care about it for now. @@ -784,7 +749,7 @@ TEST_F(TestReadChunking, TestDynamicEndpoint) readCallback.mOnReportEnd = false; emberAfEndpointEnableDisable(kTestEndpointId4, true); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Ensure we have received the report, we do not care about the initial report here. // GlobalAttributesNotInMetadata attributes are not included in testClusterAttrsOnEndpoint4. @@ -797,9 +762,9 @@ TEST_F(TestReadChunking, TestDynamicEndpoint) chip::test_utils::SleepMillis(SecondsToMilliseconds(2)); // Destroying the read client will terminate the subscription transaction. - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); emberAfClearDynamicEndpoint(0); } @@ -857,7 +822,7 @@ struct Instruction std::vector attributesWithSameDataVersion; }; -void DriveIOUntilSubscriptionEstablished(TestContext * pContext, TestMutableReadCallback * callback) +void DriveIOUntilSubscriptionEstablished(TestReadChunking * pContext, TestMutableReadCallback * callback) { callback->mOnReportEnd = false; pContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return callback->mOnSubscriptionEstablished; }); @@ -866,7 +831,7 @@ void DriveIOUntilSubscriptionEstablished(TestContext * pContext, TestMutableRead callback->mActionOn.clear(); } -void DriveIOUntilEndOfReport(TestContext * pContext, TestMutableReadCallback * callback) +void DriveIOUntilEndOfReport(TestReadChunking * pContext, TestMutableReadCallback * callback) { callback->mOnReportEnd = false; pContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return callback->mOnReportEnd; }); @@ -895,7 +860,7 @@ void ExpectSameDataVersions(TestMutableReadCallback * callback, AttributesList a } } -void DoTest(TestContext * pContext, TestMutableReadCallback * callback, Instruction instruction) +void DoTest(TestReadChunking * pContext, TestMutableReadCallback * callback, Instruction instruction) { app::InteractionModelEngine::GetInstance()->GetReportingEngine().SetMaxAttributesPerChunk(instruction.chunksize); @@ -919,7 +884,7 @@ void DoTest(TestContext * pContext, TestMutableReadCallback * callback, Instruct TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) { using namespace TestSetDirtyBetweenChunksUtil; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance(); // Initialize the ember side server logic @@ -953,7 +918,7 @@ TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) gIterationCount = 1; - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), readCallback.mBufferedCallback, + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mBufferedCallback, app::ReadClient::InteractionType::Subscribe); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); @@ -965,11 +930,11 @@ TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) // We are expected to miss attributes on kTestEndpointId during initial reports. ChipLogProgress(DataManagement, "Case 1-1: Set dirty during priming report."); readCallback.mActionOn[AttrOnEp5] = TouchAttrOp(AttrOnEp1); - DriveIOUntilSubscriptionEstablished(mpContext, &readCallback); + DriveIOUntilSubscriptionEstablished(this, &readCallback); CheckValues(&readCallback, { { AttrOnEp1, 1 } }); ChipLogProgress(DataManagement, "Case 1-2: Check for attributes missed last report."); - DoTest(mpContext, &readCallback, Instruction{ .chunksize = 2, .expectedValues = { { AttrOnEp1, 2 } } }); + DoTest(this, &readCallback, Instruction{ .chunksize = 2, .expectedValues = { { AttrOnEp1, 2 } } }); } // CASE 2 -- Set dirty during chunked report, the attribute is already dirty. @@ -977,7 +942,7 @@ TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) ChipLogProgress(DataManagement, "Case 2: Set dirty during chunked report by wildcard path."); readCallback.mActionOn[AttrOnEp5] = WriteAttrOp(AttrOnEp5, 3); DoTest( - mpContext, &readCallback, + this, &readCallback, Instruction{ .chunksize = 2, .preworks = { WriteAttrOp(AttrOnEp5, 2), WriteAttrOp(AttrOnEp5, 2), WriteAttrOp(AttrOnEp5, 2) }, @@ -991,7 +956,7 @@ TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) "Case 3-1: Set dirty during chunked report by wildcard path -- new dirty attribute."); readCallback.mActionOn[AttrOnEp5] = WriteAttrOp(AttrOnEp5, 4); DoTest( - mpContext, &readCallback, + this, &readCallback, Instruction{ .chunksize = 1, .preworks = { WriteAttrOp(AttrOnEp5, 4), WriteAttrOp(AttrOnEp5, 4) }, .expectedValues = { { AttrOnEp5, 4 }, { AttrOnEp5, 4 }, { AttrOnEp5, 4 } }, @@ -1002,7 +967,7 @@ TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) app::InteractionModelEngine::GetInstance()->GetReportingEngine().SetMaxAttributesPerChunk(1); readCallback.mActionOn[AttrOnEp5] = WriteAttrOp(AttrOnEp5, 5); DoTest( - mpContext, &readCallback, + this, &readCallback, Instruction{ .chunksize = 1, .preworks = { WriteAttrOp(AttrOnEp5, 5), WriteAttrOp(AttrOnEp5, 5) }, .expectedValues = { { AttrOnEp5, 5 }, { AttrOnEp5, 5 }, { AttrOnEp5, 5 } }, @@ -1032,18 +997,18 @@ TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) { TestMutableReadCallback readCallback; - app::ReadClient readClient(engine, &mpContext->GetExchangeManager(), readCallback.mBufferedCallback, + app::ReadClient readClient(engine, &GetExchangeManager(), readCallback.mBufferedCallback, app::ReadClient::InteractionType::Subscribe); EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - DriveIOUntilSubscriptionEstablished(mpContext, &readCallback); + DriveIOUntilSubscriptionEstablished(this, &readCallback); // Note, although the two attributes comes from the same cluster, they are generated by different interested paths. // In this case, we won't reset the path iterator. ChipLogProgress(DataManagement, "Case 1-1: Test set dirty during reports generated by concrete paths."); readCallback.mActionOn[AttrOnEp5] = WriteAttrOp(AttrOnEp5, 4); - DoTest(mpContext, &readCallback, + DoTest(this, &readCallback, Instruction{ .chunksize = 1, .preworks = { WriteAttrOp(AttrOnEp5, 3), WriteAttrOp(AttrOnEp5, 3), WriteAttrOp(AttrOnEp5, 3) }, @@ -1051,16 +1016,16 @@ TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) // The attribute failed to catch last report will be picked by this report. ChipLogProgress(DataManagement, "Case 1-2: Check for attributes missed last report."); - DoTest(mpContext, &readCallback, { .chunksize = 1, .expectedValues = { { AttrOnEp5, 4 } } }); + DoTest(this, &readCallback, { .chunksize = 1, .expectedValues = { { AttrOnEp5, 4 } } }); } } chip::test_utils::SleepMillis(SecondsToMilliseconds(3)); // Destroying the read client will terminate the subscription transaction. - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); emberAfClearDynamicEndpoint(1); emberAfClearDynamicEndpoint(0); diff --git a/src/controller/tests/TestServerCommandDispatch.cpp b/src/controller/tests/TestServerCommandDispatch.cpp index 41fab0ae0e3802..1536d0ccc4c2d5 100644 --- a/src/controller/tests/TestServerCommandDispatch.cpp +++ b/src/controller/tests/TestServerCommandDispatch.cpp @@ -22,7 +22,7 @@ * */ -#include +#include #include "app-common/zap-generated/ids/Attributes.h" #include "app-common/zap-generated/ids/Clusters.h" @@ -38,8 +38,6 @@ #include #include -using TestContext = chip::Test::AppContext; - using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; @@ -130,45 +128,11 @@ CHIP_ERROR TestClusterCommandHandler::EnumerateAcceptedCommands(const ConcreteCl namespace { -class TestServerCommandDispatch : public ::testing::Test +class TestServerCommandDispatch : public chip::Test::AppContext { -public: - // Performs shared setup for all tests in the test suite - static void SetUpTestSuite() - { - if (mpContext == nullptr) - { - mpContext = new TestContext(); - ASSERT_NE(mpContext, nullptr); - } - mpContext->SetUpTestSuite(); - } - - // Performs shared teardown for all tests in the test suite - static void TearDownTestSuite() - { - mpContext->TearDownTestSuite(); - if (mpContext != nullptr) - { - delete mpContext; - mpContext = nullptr; - } - } - protected: - // Performs setup for each test in the suite - void SetUp() { mpContext->SetUp(); } - - // Performs teardown for each test in the suite - void TearDown() { mpContext->TearDown(); } - - static TestContext * mpContext; - - // Helpers - - static void TestDataResponseHelper(const EmberAfEndpointType * aEndpoint, bool aExpectSuccess); + void TestDataResponseHelper(const EmberAfEndpointType * aEndpoint, bool aExpectSuccess); }; -TestContext * TestServerCommandDispatch::mpContext = nullptr; // We want to send a TestSimpleArgumentRequest::Type, but get a // TestStructArrayArgumentResponse in return, so need to shadow the actual @@ -181,7 +145,7 @@ struct FakeRequest : public Clusters::UnitTesting::Commands::TestSimpleArgumentR TEST_F(TestServerCommandDispatch, TestNoHandler) { FakeRequest request; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); request.arg1 = true; @@ -203,12 +167,12 @@ TEST_F(TestServerCommandDispatch, TestNoHandler) responseDirective = kSendDataResponse; - chip::Controller::InvokeCommandRequest(&mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, + chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } static const int kDescriptorAttributeArraySize = 254; @@ -261,7 +225,7 @@ DECLARE_DYNAMIC_ENDPOINT(testEndpoint3, testEndpointClusters3); void TestServerCommandDispatch::TestDataResponseHelper(const EmberAfEndpointType * aEndpoint, bool aExpectSuccess) { FakeRequest request; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessWasCalled = false; bool onFailureWasCalled = false; @@ -307,13 +271,13 @@ void TestServerCommandDispatch::TestDataResponseHelper(const EmberAfEndpointType responseDirective = kSendDataResponse; - chip::Controller::InvokeCommandRequest(&mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, + chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(onSuccessWasCalled == aExpectSuccess && onFailureWasCalled != aExpectSuccess); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); onSuccessWasCalled = false; onFailureWasCalled = false; @@ -346,12 +310,12 @@ void TestServerCommandDispatch::TestDataResponseHelper(const EmberAfEndpointType }; chip::Controller::ReadAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, readSuccessCb, readFailureCb); + &GetExchangeManager(), sessionHandle, kTestEndpointId, readSuccessCb, readFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(onSuccessWasCalled && !onFailureWasCalled); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); emberAfClearDynamicEndpoint(0); } diff --git a/src/controller/tests/data_model/TestCommands.cpp b/src/controller/tests/data_model/TestCommands.cpp index b6d39ae41978bc..9ebb4d39a4c524 100644 --- a/src/controller/tests/data_model/TestCommands.cpp +++ b/src/controller/tests/data_model/TestCommands.cpp @@ -22,7 +22,7 @@ * */ -#include +#include #include "app/data-model/NullObject.h" #include @@ -39,8 +39,6 @@ #include #include -using TestContext = chip::Test::AppContext; - using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; @@ -182,34 +180,7 @@ InteractionModel::Status ServerClusterCommandExists(const ConcreteCommandPath & namespace { -class TestCommands : public ::testing::Test -{ -public: - // Performs shared setup for all tests in the test suite - static void SetUpTestSuite() - { - mpContext = new TestContext(); - ASSERT_NE(mpContext, nullptr); - mpContext->SetUpTestSuite(); - } - - // Performs shared teardown for all tests in the test suite - static void TearDownTestSuite() - { - mpContext->TearDownTestSuite(); - delete mpContext; - } - -protected: - // Performs setup for each individual test in the test suite - void SetUp() { mpContext->SetUp(); } - - // Performs teardown for each individual test in the test suite - void TearDown() { mpContext->TearDown(); } - - static TestContext * mpContext; -}; -TestContext * TestCommands::mpContext = nullptr; +using TestCommands = chip::Test::AppContext; TEST_F(TestCommands, TestDataResponse) { @@ -222,7 +193,7 @@ TEST_F(TestCommands, TestDataResponse) }; FakeRequest request; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessWasCalled = false; bool onFailureWasCalled = false; @@ -258,13 +229,13 @@ TEST_F(TestCommands, TestDataResponse) responseDirective = kSendDataResponse; - chip::Controller::InvokeCommandRequest(&mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, + chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(onSuccessWasCalled && !onFailureWasCalled); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommands, TestSuccessNoDataResponse) @@ -275,7 +246,7 @@ TEST_F(TestCommands, TestSuccessNoDataResponse) }; FakeRequest request; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessWasCalled = false; bool onFailureWasCalled = false; @@ -296,13 +267,13 @@ TEST_F(TestCommands, TestSuccessNoDataResponse) responseDirective = kSendSuccessStatusCode; - chip::Controller::InvokeCommandRequest(&mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, + chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(onSuccessWasCalled && !onFailureWasCalled && statusCheck); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommands, TestMultipleSuccessNoDataResponses) @@ -313,7 +284,7 @@ TEST_F(TestCommands, TestMultipleSuccessNoDataResponses) }; FakeRequest request; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); size_t successCalls = 0; size_t failureCalls = 0; @@ -334,14 +305,13 @@ TEST_F(TestCommands, TestMultipleSuccessNoDataResponses) responseDirective = kSendMultipleSuccessStatusCodes; - Controller::InvokeCommandRequest(&mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, - onFailureCb); + Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(successCalls == 1 && statusCheck); EXPECT_EQ(failureCalls, 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommands, TestAsyncResponse) @@ -352,7 +322,7 @@ TEST_F(TestCommands, TestAsyncResponse) }; FakeRequest request; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessWasCalled = false; bool onFailureWasCalled = false; @@ -373,13 +343,13 @@ TEST_F(TestCommands, TestAsyncResponse) responseDirective = kAsync; - chip::Controller::InvokeCommandRequest(&mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, + chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(!onSuccessWasCalled && !onFailureWasCalled && !statusCheck); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 2u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 2u); CommandHandler * commandHandle = asyncHandle.Get(); ASSERT_NE(commandHandle, nullptr); @@ -388,16 +358,16 @@ TEST_F(TestCommands, TestAsyncResponse) Protocols::InteractionModel::Status::Success); asyncHandle.Release(); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(onSuccessWasCalled && !onFailureWasCalled && statusCheck); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommands, TestFailure) { Clusters::UnitTesting::Commands::TestSimpleArgumentRequest::Type request; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessWasCalled = false; bool onFailureWasCalled = false; @@ -418,13 +388,13 @@ TEST_F(TestCommands, TestFailure) responseDirective = kSendError; - chip::Controller::InvokeCommandRequest(&mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, + chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(!onSuccessWasCalled && onFailureWasCalled && statusCheck); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommands, TestMultipleFailures) @@ -435,7 +405,7 @@ TEST_F(TestCommands, TestMultipleFailures) }; FakeRequest request; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); size_t successCalls = 0; size_t failureCalls = 0; @@ -456,14 +426,13 @@ TEST_F(TestCommands, TestMultipleFailures) responseDirective = kSendMultipleErrors; - Controller::InvokeCommandRequest(&mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, - onFailureCb); + Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(successCalls, 0u); EXPECT_TRUE(failureCalls == 1 && statusCheck); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommands, TestSuccessNoDataResponseWithClusterStatus) @@ -474,7 +443,7 @@ TEST_F(TestCommands, TestSuccessNoDataResponseWithClusterStatus) }; FakeRequest request; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessWasCalled = false; bool onFailureWasCalled = false; @@ -496,19 +465,19 @@ TEST_F(TestCommands, TestSuccessNoDataResponseWithClusterStatus) responseDirective = kSendSuccessStatusCodeWithClusterStatus; - chip::Controller::InvokeCommandRequest(&mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, + chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(onSuccessWasCalled && !onFailureWasCalled && statusCheck); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestCommands, TestFailureWithClusterStatus) { Clusters::UnitTesting::Commands::TestSimpleArgumentRequest::Type request; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessWasCalled = false; bool onFailureWasCalled = false; @@ -535,13 +504,13 @@ TEST_F(TestCommands, TestFailureWithClusterStatus) responseDirective = kSendErrorWithClusterStatus; - chip::Controller::InvokeCommandRequest(&mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, + chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(!onSuccessWasCalled && onFailureWasCalled && statusCheck); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } } // namespace diff --git a/src/controller/tests/data_model/TestRead.cpp b/src/controller/tests/data_model/TestRead.cpp index a27eb61fcb2901..7e31d255ae2390 100644 --- a/src/controller/tests/data_model/TestRead.cpp +++ b/src/controller/tests/data_model/TestRead.cpp @@ -16,7 +16,7 @@ * limitations under the License. */ -#include +#include #include "system/SystemClock.h" #include "transport/SecureSession.h" @@ -34,8 +34,6 @@ #include #include -using TestContext = chip::Test::AppContext; - using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; @@ -258,40 +256,9 @@ Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventP namespace { -class TestRead : public ::testing::Test, public app::ReadHandler::ApplicationCallback +class TestRead : public chip::Test::AppContext, public app::ReadHandler::ApplicationCallback { -public: - // Performs shared setup for all tests in the test suite - static void SetUpTestSuite() - { - if (mpContext == nullptr) - { - mpContext = new TestContext(); - ASSERT_NE(mpContext, nullptr); - } - mpContext->SetUpTestSuite(); - } - - // Performs shared teardown for all tests in the test suite - static void TearDownTestSuite() - { - mpContext->TearDownTestSuite(); - if (mpContext != nullptr) - { - delete mpContext; - mpContext = nullptr; - } - } - protected: - // Performs setup for each individual test in the test suite - void SetUp() { mpContext->SetUp(); } - - // Performs teardown for each individual test in the test suite - void TearDown() { mpContext->TearDown(); } - - static TestContext * mpContext; - static uint16_t mMaxInterval; CHIP_ERROR OnSubscriptionRequested(app::ReadHandler & aReadHandler, Transport::SecureSession & aSecureSession) @@ -311,16 +278,15 @@ class TestRead : public ::testing::Test, public app::ReadHandler::ApplicationCal // Issue the given number of reads in parallel and wait for them all to // succeed. - static void MultipleReadHelper(TestContext * apCtx, size_t aReadCount); + void MultipleReadHelper(size_t aReadCount); // Helper for MultipleReadHelper that does not spin the event loop, so we // don't end up with nested event loops. - static void MultipleReadHelperInternal(TestContext * apCtx, size_t aReadCount, uint32_t & aNumSuccessCalls, - uint32_t & aNumFailureCalls); + void MultipleReadHelperInternal(size_t aReadCount, uint32_t & aNumSuccessCalls, uint32_t & aNumFailureCalls); // Establish the given number of subscriptions, then issue the given number // of reads in parallel and wait for them all to succeed. - static void SubscribeThenReadHelper(TestContext * apCtx, size_t aSubscribeCount, size_t aReadCount); + void SubscribeThenReadHelper(size_t aSubscribeCount, size_t aReadCount); // Compute the amount of time it would take a subscription with a given // max-interval to time out. @@ -331,8 +297,7 @@ class TestRead : public ::testing::Test, public app::ReadHandler::ApplicationCal bool mAlterSubscriptionIntervals = false; }; -TestContext * TestRead::mpContext = nullptr; -uint16_t TestRead::mMaxInterval = 66; +uint16_t TestRead::mMaxInterval = 66; class MockInteractionModelApp : public chip::app::ClusterStateCache::Callback { @@ -385,7 +350,7 @@ class MockInteractionModelApp : public chip::app::ClusterStateCache::Callback TEST_F(TestRead, TestReadAttributeResponse) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; responseDirective = kSendDataResponse; @@ -414,14 +379,14 @@ TEST_F(TestRead, TestReadAttributeResponse) }; Controller::ReadAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb); + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(onSuccessCbInvoked && !onFailureCbInvoked); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients(), 0u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // NOTE: This test must execute before TestReadSubscribeAttributeResponseWithCache or else it will fail on @@ -434,7 +399,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithVersionOnlyCache) MockInteractionModelApp delegate; chip::app::ClusterStateCache cache(delegate, Optional::Missing(), false /*cachedData*/); - chip::app::ReadPrepareParams readPrepareParams(mpContext->GetSessionBobToAlice()); + chip::app::ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); // // Test the application callback as well to ensure we get the right number of SubscriptionEstablishment/Termination // callbacks. @@ -443,7 +408,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithVersionOnlyCache) // read of E2C2A* and E3C2A2. Expect cache E2C2 version { - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams2[2]; attributePathParams2[0].mEndpointId = chip::Test::kMockEndpoint2; @@ -458,7 +423,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithVersionOnlyCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // There are supported 2 global and 3 non-global attributes in E2C2A* and 1 E3C2A2 EXPECT_EQ(delegate.mNumAttributeResponse, 6); EXPECT_FALSE(delegate.mReadError); @@ -495,7 +460,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithVersionOnlyCache) } EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) @@ -514,7 +479,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) eventPathParam.mEventId = 0; } - chip::app::ReadPrepareParams readPrepareParams(mpContext->GetSessionBobToAlice()); + chip::app::ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mMinIntervalFloorSeconds = 0; readPrepareParams.mMaxIntervalCeilingSeconds = 4; // @@ -530,7 +495,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams1[3]; attributePathParams1[0].mEndpointId = chip::Test::kMockEndpoint2; @@ -550,7 +515,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 6); EXPECT_FALSE(delegate.mReadError); Optional version1; @@ -565,7 +530,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams1[3]; attributePathParams1[0].mEndpointId = chip::Test::kMockEndpoint2; @@ -585,7 +550,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 3); EXPECT_FALSE(delegate.mReadError); Optional version1; @@ -636,7 +601,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams1[3]; attributePathParams1[0].mEndpointId = kInvalidEndpointId; @@ -656,7 +621,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 2); EXPECT_FALSE(delegate.mReadError); Optional version1; @@ -702,7 +667,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams2[2]; attributePathParams2[0].mEndpointId = chip::Test::kMockEndpoint2; @@ -717,7 +682,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // There are supported 2 global and 3 non-global attributes in E2C2A* and 1 E3C2A2 EXPECT_EQ(delegate.mNumAttributeResponse, 6); EXPECT_FALSE(delegate.mReadError); @@ -777,7 +742,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams1[3]; attributePathParams1[0].mEndpointId = chip::Test::kMockEndpoint2; @@ -797,7 +762,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 1); EXPECT_FALSE(delegate.mReadError); Optional version1; @@ -846,7 +811,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams2[2]; attributePathParams2[0].mEndpointId = chip::Test::kMockEndpoint2; @@ -861,7 +826,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 1); EXPECT_FALSE(delegate.mReadError); Optional version1; @@ -923,7 +888,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams1[3]; attributePathParams1[0].mEndpointId = chip::Test::kMockEndpoint2; @@ -943,7 +908,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 3); EXPECT_FALSE(delegate.mReadError); Optional version1; @@ -992,7 +957,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams1[3]; attributePathParams1[0].mEndpointId = chip::Test::kMockEndpoint2; @@ -1012,7 +977,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 3); EXPECT_FALSE(delegate.mReadError); Optional version1; @@ -1061,7 +1026,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams2[2]; attributePathParams2[0].mEndpointId = chip::Test::kMockEndpoint2; @@ -1076,7 +1041,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 6); EXPECT_FALSE(delegate.mReadError); Optional version1; @@ -1136,7 +1101,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams2[2]; attributePathParams2[0].mEndpointId = chip::Test::kMockEndpoint2; @@ -1159,7 +1124,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 6); EXPECT_FALSE(delegate.mReadError); Optional version1; @@ -1222,7 +1187,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams3[3]; @@ -1243,7 +1208,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // E1C2A* has 3 attributes and E2C3A* has 5 attributes and E2C2A* has 4 attributes EXPECT_EQ(delegate.mNumAttributeResponse, 12); EXPECT_FALSE(delegate.mReadError); @@ -1329,7 +1294,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams3[3]; @@ -1355,7 +1320,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 7); EXPECT_FALSE(delegate.mReadError); Optional version1; @@ -1440,7 +1405,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); - app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), + app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams1[1]; attributePathParams1[0].mEndpointId = chip::Test::kMockEndpoint3; @@ -1451,7 +1416,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 6); EXPECT_FALSE(delegate.mReadError); Optional version1; @@ -1503,12 +1468,12 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) } EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestRead, TestReadEventResponse) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false, onDoneCbInvoked = false; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's @@ -1527,21 +1492,21 @@ TEST_F(TestRead, TestReadEventResponse) auto onDoneCb = [&onDoneCbInvoked](app::ReadClient * apReadClient) { onDoneCbInvoked = true; }; Controller::ReadEvent( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, onDoneCb); + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, onDoneCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_FALSE(onFailureCbInvoked); EXPECT_TRUE(onDoneCbInvoked); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients(), 0u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestRead, TestReadAttributeError) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; responseDirective = kSendDataError; @@ -1560,19 +1525,19 @@ TEST_F(TestRead, TestReadAttributeError) }; Controller::ReadAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb); + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(!onSuccessCbInvoked && onFailureCbInvoked); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients(), 0u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestRead, TestReadAttributeTimeout) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; responseDirective = kSendDataError; @@ -1591,21 +1556,21 @@ TEST_F(TestRead, TestReadAttributeTimeout) }; Controller::ReadAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb); + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb); - mpContext->ExpireSessionAliceToBob(); + ExpireSessionAliceToBob(); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 1u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 1u); - mpContext->ExpireSessionBobToAlice(); + ExpireSessionBobToAlice(); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(!onSuccessCbInvoked && onFailureCbInvoked); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 0u); @@ -1613,10 +1578,10 @@ TEST_F(TestRead, TestReadAttributeTimeout) // Let's put back the sessions so that the next tests (which assume a valid initialized set of sessions) // can function correctly. // - mpContext->CreateSessionAliceToBob(); - mpContext->CreateSessionBobToAlice(); + CreateSessionAliceToBob(); + CreateSessionBobToAlice(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } class TestResubscriptionCallback : public app::ReadClient::Callback @@ -1677,18 +1642,18 @@ class TestResubscriptionCallback : public app::ReadClient::Callback // TEST_F(TestRead, TestResubscribeAttributeTimeout) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); - mpContext->SetMRPMode(chip::Test::MessagingContext::MRPMode::kResponsive); + SetMRPMode(chip::Test::MessagingContext::MRPMode::kResponsive); { TestResubscriptionCallback callback; - app::ReadClient readClient(app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), callback, + app::ReadClient readClient(app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), callback, app::ReadClient::InteractionType::Subscribe); callback.SetReadClient(&readClient); - app::ReadPrepareParams readPrepareParams(mpContext->GetSessionBobToAlice()); + app::ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); // Read full wildcard paths, repeat twice to ensure chunking. app::AttributePathParams attributePathParams[1]; @@ -1708,8 +1673,8 @@ TEST_F(TestRead, TestResubscribeAttributeTimeout) // // Drive servicing IO till we have established a subscription. // - mpContext->GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); EXPECT_EQ(callback.mOnError, 0); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 0); @@ -1724,21 +1689,21 @@ TEST_F(TestRead, TestResubscribeAttributeTimeout) // Disable packet transmission, and drive IO till we have reported a re-subscription attempt. // // - mpContext->GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; - mpContext->GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return callback.mOnResubscriptionsAttempted > 0; }); + GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; + GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), + [&]() { return callback.mOnResubscriptionsAttempted > 0; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_TIMEOUT); - mpContext->GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToDrop = 0; callback.ClearCounters(); // // Drive servicing IO till we have established a subscription. // - mpContext->GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); + GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), + [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -1748,10 +1713,10 @@ TEST_F(TestRead, TestResubscribeAttributeTimeout) EXPECT_EQ(callback.mOnDone, 0); } - mpContext->SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); + SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // @@ -1760,18 +1725,18 @@ TEST_F(TestRead, TestResubscribeAttributeTimeout) // TEST_F(TestRead, TestSubscribeAttributeTimeout) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); - mpContext->SetMRPMode(chip::Test::MessagingContext::MRPMode::kResponsive); + SetMRPMode(chip::Test::MessagingContext::MRPMode::kResponsive); { TestResubscriptionCallback callback; - app::ReadClient readClient(app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), callback, + app::ReadClient readClient(app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), callback, app::ReadClient::InteractionType::Subscribe); callback.SetReadClient(&readClient); - app::ReadPrepareParams readPrepareParams(mpContext->GetSessionBobToAlice()); + app::ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); app::AttributePathParams attributePathParams[1]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -1792,14 +1757,14 @@ TEST_F(TestRead, TestSubscribeAttributeTimeout) // // Drive servicing IO till we have established a subscription. // - mpContext->GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // // Request we drop all further messages. // - mpContext->GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; + GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; chip::app::ReadHandler * readHandler = app::InteractionModelEngine::GetInstance()->ActiveHandlerAt(0); @@ -1812,8 +1777,8 @@ TEST_F(TestRead, TestSubscribeAttributeTimeout) // by the liveness timer firing once we hit our max-interval plus // retransmit timeouts. // - mpContext->GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return callback.mOnError >= 1; }); + GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), + [&]() { return callback.mOnError >= 1; }); EXPECT_EQ(callback.mOnError, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_TIMEOUT); @@ -1821,16 +1786,16 @@ TEST_F(TestRead, TestSubscribeAttributeTimeout) EXPECT_EQ(callback.mOnResubscriptionsAttempted, 0); } - mpContext->SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); + SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); - mpContext->GetLoopback().mNumMessagesToDrop = 0; + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); + GetLoopback().mNumMessagesToDrop = 0; } TEST_F(TestRead, TestReadHandler_MultipleSubscriptions) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; @@ -1870,14 +1835,14 @@ TEST_F(TestRead, TestReadHandler_MultipleSubscriptions) for (size_t i = 0; i < (app::InteractionModelEngine::kReadHandlerPoolSize + 1); i++) { EXPECT_EQ(Controller::SubscribeAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 20, + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 20, onSubscriptionEstablishedCb, nullptr, false, true), CHIP_NO_ERROR); } // There are too many messages and the test (gcc_debug, which includes many sanity checks) will be quite slow. Note: report // engine is using ScheduleWork which cannot be handled by DrainAndServiceIO correctly. - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), [&]() { return numSuccessCalls == (app::InteractionModelEngine::kReadHandlerPoolSize + 1) && numSubscriptionEstablishedCalls == (app::InteractionModelEngine::kReadHandlerPoolSize + 1); }); @@ -1889,15 +1854,15 @@ TEST_F(TestRead, TestReadHandler_MultipleSubscriptions) app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); EXPECT_EQ(mNumActiveSubscriptions, 0); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); - mpContext->SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); + SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); } TEST_F(TestRead, TestReadHandler_SubscriptionAppRejection) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; @@ -1933,11 +1898,11 @@ TEST_F(TestRead, TestReadHandler_SubscriptionAppRejection) mEmitSubscriptionError = true; EXPECT_EQ(Controller::SubscribeAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, onSubscriptionEstablishedCb, nullptr, false, true), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(numSuccessCalls, 0u); @@ -1951,7 +1916,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionAppRejection) app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); mEmitSubscriptionError = false; @@ -1963,7 +1928,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionAppRejection) // Max interval equal to client-requested min-interval. TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest1) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; @@ -2008,11 +1973,11 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest1) mAlterSubscriptionIntervals = false; EXPECT_EQ(Controller::SubscribeAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 5, 5, + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 5, 5, onSubscriptionEstablishedCb, nullptr, true), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // // Failures won't get routed to us here since re-subscriptions are enabled by default in the Controller::SubscribeAttribute @@ -2027,7 +1992,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest1) EXPECT_EQ(mNumActiveSubscriptions, 0); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); mAlterSubscriptionIntervals = false; @@ -2038,7 +2003,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest1) // With no server adjustment. TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest2) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; @@ -2083,11 +2048,11 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest2) mAlterSubscriptionIntervals = false; EXPECT_EQ(Controller::SubscribeAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, onSubscriptionEstablishedCb, nullptr, true), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // // Failures won't get routed to us here since re-subscriptions are enabled by default in the Controller::SubscribeAttribute @@ -2102,7 +2067,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest2) EXPECT_EQ(mNumActiveSubscriptions, 0); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); mAlterSubscriptionIntervals = false; @@ -2113,7 +2078,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest2) // With server adjustment to a value greater than client-requested, but less than 60m (allowed). TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest3) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; @@ -2158,11 +2123,11 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest3) mAlterSubscriptionIntervals = true; mMaxInterval = 3000; EXPECT_EQ(Controller::SubscribeAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, onSubscriptionEstablishedCb, nullptr, true), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // // Failures won't get routed to us here since re-subscriptions are enabled by default in the Controller::SubscribeAttribute @@ -2177,7 +2142,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest3) EXPECT_EQ(mNumActiveSubscriptions, 0); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); mAlterSubscriptionIntervals = false; @@ -2190,7 +2155,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest3) // server adjustment to a value greater than client-requested, but greater than 60 (not allowed). TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest4) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; @@ -2226,11 +2191,11 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest4) mAlterSubscriptionIntervals = true; mMaxInterval = 3700; EXPECT_EQ(Controller::SubscribeAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, onSubscriptionEstablishedCb, nullptr, true), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // // Failures won't get routed to us here since re-subscriptions are enabled by default in the Controller::SubscribeAttribute @@ -2244,7 +2209,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest4) EXPECT_EQ(mNumActiveSubscriptions, 0); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); mAlterSubscriptionIntervals = false; @@ -2257,7 +2222,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest4) // With no server adjustment. TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest5) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; @@ -2302,11 +2267,11 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest5) mAlterSubscriptionIntervals = false; EXPECT_EQ(Controller::SubscribeAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 4000, + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 4000, onSubscriptionEstablishedCb, nullptr, true), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // // Failures won't get routed to us here since re-subscriptions are enabled by default in the Controller::SubscribeAttribute @@ -2321,7 +2286,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest5) EXPECT_EQ(mNumActiveSubscriptions, 0); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); mAlterSubscriptionIntervals = false; @@ -2332,7 +2297,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest5) // With server adjustment to a value lower than 60m. Allowed TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest6) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; @@ -2377,11 +2342,11 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest6) mAlterSubscriptionIntervals = true; mMaxInterval = 3000; EXPECT_EQ(Controller::SubscribeAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 4000, + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 4000, onSubscriptionEstablishedCb, nullptr, true), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // // Failures won't get routed to us here since re-subscriptions are enabled by default in the Controller::SubscribeAttribute @@ -2396,7 +2361,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest6) EXPECT_EQ(mNumActiveSubscriptions, 0); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); mAlterSubscriptionIntervals = false; @@ -2407,7 +2372,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest6) // With server adjustment to a value larger than 60m, but less than max interval. Allowed TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest7) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; @@ -2451,11 +2416,11 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest7) mAlterSubscriptionIntervals = true; mMaxInterval = 3700; EXPECT_EQ(Controller::SubscribeAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 4000, + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 4000, onSubscriptionEstablishedCb, nullptr, true), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // // Failures won't get routed to us here since re-subscriptions are enabled by default in the Controller::SubscribeAttribute @@ -2470,7 +2435,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest7) EXPECT_EQ(mNumActiveSubscriptions, 0); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); mAlterSubscriptionIntervals = false; @@ -2483,7 +2448,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest7) // With server adjustment to a value larger than 60m, but larger than max interval. Disallowed TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest8) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; @@ -2518,11 +2483,11 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest8) mAlterSubscriptionIntervals = true; mMaxInterval = 4100; EXPECT_EQ(Controller::SubscribeAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 4000, + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 4000, onSubscriptionEstablishedCb, nullptr, true), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // // Failures won't get routed to us here since re-subscriptions are enabled by default in the Controller::SubscribeAttribute @@ -2536,7 +2501,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest8) EXPECT_EQ(mNumActiveSubscriptions, 0); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); mAlterSubscriptionIntervals = false; @@ -2546,7 +2511,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest8) // Validate client is not requesting max-interval < min-interval. TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest9) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; @@ -2582,7 +2547,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest9) mAlterSubscriptionIntervals = false; EXPECT_EQ(Controller::SubscribeAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 5, 4, + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 5, 4, onSubscriptionEstablishedCb, nullptr, true), CHIP_ERROR_INVALID_ARGUMENT); @@ -2598,7 +2563,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest9) EXPECT_EQ(mNumActiveSubscriptions, 0); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); mAlterSubscriptionIntervals = false; @@ -2610,19 +2575,19 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest9) */ TEST_F(TestRead, TestSubscribe_OnActiveModeNotification) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); - mpContext->SetMRPMode(chip::Test::MessagingContext::MRPMode::kResponsive); + SetMRPMode(chip::Test::MessagingContext::MRPMode::kResponsive); { TestResubscriptionCallback callback; - app::ReadClient readClient(app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), callback, + app::ReadClient readClient(app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), callback, app::ReadClient::InteractionType::Subscribe); callback.mScheduleLITResubscribeImmediately = false; callback.SetReadClient(&readClient); - app::ReadPrepareParams readPrepareParams(mpContext->GetSessionBobToAlice()); + app::ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); // Read full wildcard paths, repeat twice to ensure chunking. app::AttributePathParams attributePathParams[1]; @@ -2643,8 +2608,8 @@ TEST_F(TestRead, TestSubscribe_OnActiveModeNotification) // // Drive servicing IO till we have established a subscription. // - mpContext->GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); EXPECT_EQ(callback.mOnError, 0); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 0); @@ -2660,13 +2625,12 @@ TEST_F(TestRead, TestSubscribe_OnActiveModeNotification) // WakeUp() is called. // // - mpContext->GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; - mpContext->GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return false; }); + GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; + GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), [&]() { return false; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT); - mpContext->GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToDrop = 0; callback.ClearCounters(); app::InteractionModelEngine::GetInstance()->OnActiveModeNotification( ScopedNodeId(readClient.GetPeerNodeId(), readClient.GetFabricIndex())); @@ -2676,8 +2640,8 @@ TEST_F(TestRead, TestSubscribe_OnActiveModeNotification) // // Drive servicing IO till we have established a subscription. // - mpContext->GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); + GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), + [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -2687,10 +2651,10 @@ TEST_F(TestRead, TestSubscribe_OnActiveModeNotification) EXPECT_EQ(callback.mOnDone, 0); } - mpContext->SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); + SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } /** @@ -2699,13 +2663,13 @@ TEST_F(TestRead, TestSubscribe_OnActiveModeNotification) */ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); - mpContext->SetMRPMode(chip::Test::MessagingContext::MRPMode::kResponsive); + SetMRPMode(chip::Test::MessagingContext::MRPMode::kResponsive); { TestResubscriptionCallback callback; - app::ReadClient readClient(app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), callback, + app::ReadClient readClient(app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), callback, app::ReadClient::InteractionType::Subscribe); responseDirective = kSendDataResponse; @@ -2713,7 +2677,7 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) callback.SetReadClient(&readClient); isLitIcd = false; - app::ReadPrepareParams readPrepareParams(mpContext->GetSessionBobToAlice()); + app::ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); // Read full wildcard paths, repeat twice to ensure chunking. app::AttributePathParams attributePathParams[1]; @@ -2734,8 +2698,8 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) // // Drive servicing IO till we have established a subscription. // - mpContext->GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); EXPECT_EQ(callback.mOnError, 0); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 0); @@ -2754,20 +2718,20 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) // // Even if we set the peer type to LIT before, the report indicates that the peer is a SIT now, it will just bahve as // normal, non-LIT subscriptions. - mpContext->GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; - mpContext->GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return callback.mOnResubscriptionsAttempted != 0; }); + GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; + GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), + [&]() { return callback.mOnResubscriptionsAttempted != 0; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_TIMEOUT); - mpContext->GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToDrop = 0; callback.ClearCounters(); // // Drive servicing IO till we have established a subscription. // - mpContext->GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); + GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), + [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -2787,25 +2751,23 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) app::InteractionModelEngine::GetInstance()->GetReportingEngine().SetDirty(path); } callback.ClearCounters(); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), [&]() { - return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; - }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), + [&]() { return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; }); // When we received the update that OperatingMode becomes LIT, we automatically set the inner peer type to LIT ICD. - mpContext->GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; - mpContext->GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return false; }); + GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; + GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), [&]() { return false; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT); - mpContext->GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToDrop = 0; callback.ClearCounters(); } - mpContext->SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); + SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); isLitIcd = false; } @@ -2816,19 +2778,19 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) */ TEST_F(TestRead, TestSubscribe_ImmediatelyResubscriptionForLIT) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); - mpContext->SetMRPMode(chip::Test::MessagingContext::MRPMode::kResponsive); + SetMRPMode(chip::Test::MessagingContext::MRPMode::kResponsive); { TestResubscriptionCallback callback; - app::ReadClient readClient(app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), callback, + app::ReadClient readClient(app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), callback, app::ReadClient::InteractionType::Subscribe); callback.mScheduleLITResubscribeImmediately = true; callback.SetReadClient(&readClient); - app::ReadPrepareParams readPrepareParams(mpContext->GetSessionBobToAlice()); + app::ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); // Read full wildcard paths, repeat twice to ensure chunking. app::AttributePathParams attributePathParams[1]; @@ -2849,8 +2811,8 @@ TEST_F(TestRead, TestSubscribe_ImmediatelyResubscriptionForLIT) // // Drive servicing IO till we have established a subscription. // - mpContext->GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); EXPECT_EQ(callback.mOnError, 0); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 0); @@ -2866,20 +2828,20 @@ TEST_F(TestRead, TestSubscribe_ImmediatelyResubscriptionForLIT) // WakeUp() is called. // // - mpContext->GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; - mpContext->GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return callback.mLastError == CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT; }); + GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; + GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), + [&]() { return callback.mLastError == CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT); - mpContext->GetLoopback().mNumMessagesToDrop = 0; + GetLoopback().mNumMessagesToDrop = 0; callback.ClearCounters(); // // Drive servicing IO till we have established a subscription. // - mpContext->GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); + GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), + [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -2889,10 +2851,10 @@ TEST_F(TestRead, TestSubscribe_ImmediatelyResubscriptionForLIT) EXPECT_EQ(callback.mOnDone, 0); } - mpContext->SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); + SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestRead, TestReadHandler_MultipleReads) @@ -2900,9 +2862,9 @@ TEST_F(TestRead, TestReadHandler_MultipleReads) static_assert(CHIP_IM_MAX_REPORTS_IN_FLIGHT <= app::InteractionModelEngine::kReadHandlerPoolSize, "How can we have more reports in flight than read handlers?"); - MultipleReadHelper(mpContext, CHIP_IM_MAX_REPORTS_IN_FLIGHT); + MultipleReadHelper(CHIP_IM_MAX_REPORTS_IN_FLIGHT); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); } @@ -2913,9 +2875,9 @@ TEST_F(TestRead, TestReadHandler_OneSubscribeMultipleReads) "How can we have more reports in flight than read handlers?"); static_assert(CHIP_IM_MAX_REPORTS_IN_FLIGHT > 1, "We won't do any reads"); - SubscribeThenReadHelper(mpContext, 1, CHIP_IM_MAX_REPORTS_IN_FLIGHT - 1); + SubscribeThenReadHelper(1, CHIP_IM_MAX_REPORTS_IN_FLIGHT - 1); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); } @@ -2926,16 +2888,16 @@ TEST_F(TestRead, TestReadHandler_TwoSubscribesMultipleReads) "How can we have more reports in flight than read handlers?"); static_assert(CHIP_IM_MAX_REPORTS_IN_FLIGHT > 2, "We won't do any reads"); - SubscribeThenReadHelper(mpContext, 2, CHIP_IM_MAX_REPORTS_IN_FLIGHT - 2); + SubscribeThenReadHelper(2, CHIP_IM_MAX_REPORTS_IN_FLIGHT - 2); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); } -void TestRead::SubscribeThenReadHelper(TestContext * apCtx, size_t aSubscribeCount, size_t aReadCount) +void TestRead::SubscribeThenReadHelper(size_t aSubscribeCount, size_t aReadCount) { - auto sessionHandle = apCtx->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; @@ -2959,25 +2921,25 @@ void TestRead::SubscribeThenReadHelper(TestContext * apCtx, size_t aSubscribeCou EXPECT_TRUE(false); }; - auto onSubscriptionEstablishedCb = [&numSubscriptionEstablishedCalls, &apCtx, aSubscribeCount, aReadCount, &numReadSuccessCalls, + auto onSubscriptionEstablishedCb = [&numSubscriptionEstablishedCalls, this, aSubscribeCount, aReadCount, &numReadSuccessCalls, &numReadFailureCalls](const app::ReadClient & readClient, chip::SubscriptionId aSubscriptionId) { numSubscriptionEstablishedCalls++; if (numSubscriptionEstablishedCalls == aSubscribeCount) { - MultipleReadHelperInternal(apCtx, aReadCount, numReadSuccessCalls, numReadFailureCalls); + MultipleReadHelperInternal(aReadCount, numReadSuccessCalls, numReadFailureCalls); } }; for (size_t i = 0; i < aSubscribeCount; ++i) { EXPECT_EQ(Controller::SubscribeAttribute( - &apCtx->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, onSubscriptionEstablishedCb, nullptr, false, true), CHIP_NO_ERROR); } - apCtx->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(numSuccessCalls, aSubscribeCount); EXPECT_EQ(numSubscriptionEstablishedCalls, aSubscribeCount); @@ -2987,13 +2949,12 @@ void TestRead::SubscribeThenReadHelper(TestContext * apCtx, size_t aSubscribeCou // The guts of MultipleReadHelper which take references to the success/failure // counts to modify and assume the consumer will be spinning the event loop. -void TestRead::MultipleReadHelperInternal(TestContext * apCtx, size_t aReadCount, uint32_t & aNumSuccessCalls, - uint32_t & aNumFailureCalls) +void TestRead::MultipleReadHelperInternal(size_t aReadCount, uint32_t & aNumSuccessCalls, uint32_t & aNumFailureCalls) { EXPECT_EQ(aNumSuccessCalls, 0u); EXPECT_EQ(aNumFailureCalls, 0u); - auto sessionHandle = apCtx->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); responseDirective = kSendDataResponse; @@ -3014,19 +2975,19 @@ void TestRead::MultipleReadHelperInternal(TestContext * apCtx, size_t aReadCount }; EXPECT_EQ(Controller::ReadAttribute( - &apCtx->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb), + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb), CHIP_NO_ERROR); } } -void TestRead::MultipleReadHelper(TestContext * apCtx, size_t aReadCount) +void TestRead::MultipleReadHelper(size_t aReadCount) { uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; - MultipleReadHelperInternal(apCtx, aReadCount, numSuccessCalls, numFailureCalls); + MultipleReadHelperInternal(aReadCount, numSuccessCalls, numFailureCalls); - apCtx->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(numSuccessCalls, aReadCount); EXPECT_EQ(numFailureCalls, 0u); @@ -3034,7 +2995,7 @@ void TestRead::MultipleReadHelper(TestContext * apCtx, size_t aReadCount) TEST_F(TestRead, TestReadHandler_MultipleSubscriptionsWithDataVersionFilter) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; @@ -3070,14 +3031,14 @@ TEST_F(TestRead, TestReadHandler_MultipleSubscriptionsWithDataVersionFilter) for (size_t i = 0; i < (app::InteractionModelEngine::kReadHandlerPoolSize + 1); i++) { EXPECT_EQ(Controller::SubscribeAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, onSubscriptionEstablishedCb, nullptr, false, true, dataVersion), CHIP_NO_ERROR); } // There are too many messages and the test (gcc_debug, which includes many sanity checks) will be quite slow. Note: report // engine is using ScheduleWork which cannot be handled by DrainAndServiceIO correctly. - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(30), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(30), [&]() { return numSubscriptionEstablishedCalls == (app::InteractionModelEngine::kReadHandlerPoolSize + 1) && numSuccessCalls == (app::InteractionModelEngine::kReadHandlerPoolSize + 1); }); @@ -3090,12 +3051,12 @@ TEST_F(TestRead, TestReadHandler_MultipleSubscriptionsWithDataVersionFilter) EXPECT_EQ(numSubscriptionEstablishedCalls, (app::InteractionModelEngine::kReadHandlerPoolSize + 1)); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestRead, TestReadHandlerResourceExhaustion_MultipleReads) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; @@ -3120,10 +3081,10 @@ TEST_F(TestRead, TestReadHandlerResourceExhaustion_MultipleReads) app::InteractionModelEngine::GetInstance()->SetForceHandlerQuota(true); EXPECT_EQ(Controller::ReadAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb), + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); app::InteractionModelEngine::GetInstance()->SetHandlerCapacityForReads(-1); app::InteractionModelEngine::GetInstance()->SetForceHandlerQuota(false); @@ -3132,7 +3093,7 @@ TEST_F(TestRead, TestReadHandlerResourceExhaustion_MultipleReads) EXPECT_EQ(numSuccessCalls, 0u); EXPECT_EQ(numFailureCalls, 1u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestRead, TestReadFabricScopedWithoutFabricFilter) @@ -3147,7 +3108,7 @@ TEST_F(TestRead, TestReadFabricScopedWithoutFabricFilter) * encoder. * - When a fabric filtered read request is received, the response encoder is able to encode the attribute correctly. */ - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; responseDirective = kSendDataResponse; @@ -3170,14 +3131,14 @@ TEST_F(TestRead, TestReadFabricScopedWithoutFabricFilter) }; Controller::ReadAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, false /* fabric filtered */); + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, false /* fabric filtered */); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(onSuccessCbInvoked && !onFailureCbInvoked); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients(), 0u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestRead, TestReadFabricScopedWithFabricFilter) @@ -3192,7 +3153,7 @@ TEST_F(TestRead, TestReadFabricScopedWithFabricFilter) * encoder. * - When a fabric filtered read request is received, the response encoder is able to encode the attribute correctly. */ - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; responseDirective = kSendDataResponse; @@ -3224,14 +3185,14 @@ TEST_F(TestRead, TestReadFabricScopedWithFabricFilter) }; Controller::ReadAttribute( - &mpContext->GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, true /* fabric filtered */); + &GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, true /* fabric filtered */); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(onSuccessCbInvoked && !onFailureCbInvoked); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients(), 0u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } namespace SubscriptionPathQuotaHelpers { @@ -3332,16 +3293,16 @@ void EstablishReadOrSubscriptions(const SessionHandle & sessionHandle, size_t nu TEST_F(TestRead, TestSubscribeAttributeDeniedNotExistPath) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); - mpContext->SetMRPMode(chip::Test::MessagingContext::MRPMode::kResponsive); + SetMRPMode(chip::Test::MessagingContext::MRPMode::kResponsive); { SubscriptionPathQuotaHelpers::TestReadCallback callback; - app::ReadClient readClient(app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), callback, + app::ReadClient readClient(app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), callback, app::ReadClient::InteractionType::Subscribe); - app::ReadPrepareParams readPrepareParams(mpContext->GetSessionBobToAlice()); + app::ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); app::AttributePathParams attributePathParams[1]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -3357,27 +3318,27 @@ TEST_F(TestRead, TestSubscribeAttributeDeniedNotExistPath) auto err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(callback.mOnError, 1u); EXPECT_EQ(callback.mLastError, CHIP_IM_GLOBAL_STATUS(InvalidAction)); EXPECT_EQ(callback.mOnDone, 1u); } - mpContext->SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); + SetMRPMode(chip::Test::MessagingContext::MRPMode::kDefault); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) { - // Note: We cannot use mpContext->DrainAndServiceIO() since the perpetual read will make DrainAndServiceIO never return. + // Note: We cannot use DrainAndServiceIO() since the perpetual read will make DrainAndServiceIO never return. using namespace SubscriptionPathQuotaHelpers; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); const auto kExpectedParallelSubs = - app::InteractionModelEngine::kMinSupportedSubscriptionsPerFabric * mpContext->GetFabricTable().FabricCount(); + app::InteractionModelEngine::kMinSupportedSubscriptionsPerFabric * GetFabricTable().FabricCount(); const auto kExpectedParallelPaths = kExpectedParallelSubs * app::InteractionModelEngine::kMinSupportedPathsPerSubscription; app::InteractionModelEngine::GetInstance()->RegisterReadHandlerAppCallback(this); @@ -3389,13 +3350,13 @@ TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) TestPerpetualListReadCallback perpetualReadCallback; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, 1, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, 1, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, kPerpetualAttributeid), app::ReadClient::InteractionType::Read, &perpetualReadCallback, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, kPerpetualAttributeid), app::ReadClient::InteractionType::Read, &perpetualReadCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Read) == 2; }); // Ensure our read transactions are established. @@ -3411,18 +3372,18 @@ TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) // // Subscription A EstablishReadOrSubscriptions( - mpContext->GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerSubscription + 1, + GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerSubscription + 1, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Subscribe, &readCallback, readClients); // Subscription B EstablishReadOrSubscriptions( - mpContext->GetSessionBobToAlice(), kExpectedParallelSubs, app::InteractionModelEngine::kMinSupportedPathsPerSubscription, + GetSessionBobToAlice(), kExpectedParallelSubs, app::InteractionModelEngine::kMinSupportedPathsPerSubscription, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Subscribe, &readCallback, readClients); // There are too many messages and the test (gcc_debug, which includes many sanity checks) will be quite slow. Note: report // engine is using ScheduleWork which cannot be handled by DrainAndServiceIO correctly. - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnSubscriptionEstablishedCount == kExpectedParallelSubs + 1 && readCallback.mAttributeCount == kExpectedParallelSubs * app::InteractionModelEngine::kMinSupportedPathsPerSubscription + @@ -3448,11 +3409,11 @@ TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) TestReadCallback callback; std::vector> outReadClient; EstablishReadOrSubscriptions( - mpContext->GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerSubscription + 1, + GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerSubscription + 1, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Subscribe, &callback, outReadClient); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return callback.mOnError == 1; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return callback.mOnError == 1; }); // Over-sized request after used all paths will receive Paths Exhausted status code. EXPECT_EQ(callback.mOnError, 1u); @@ -3463,13 +3424,13 @@ TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) // was previously established with more paths than the limit per fabric) { EstablishReadOrSubscriptions( - mpContext->GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerSubscription, + GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerSubscription, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Subscribe, &readCallback, readClients); readCallback.ClearCounters(); // Run until the new subscription got setup fully as viewed by the client. - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnSubscriptionEstablishedCount == 1 && readCallback.mAttributeCount == app::InteractionModelEngine::kMinSupportedPathsPerSubscription; }); @@ -3494,9 +3455,8 @@ TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) readCallback.ClearCounters(); // Run until all subscriptions are clean. - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), [&]() { - return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; - }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), + [&]() { return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; }); // Before the above subscription, we have one subscription with kMinSupportedPathsPerSubscription + 1 paths, we should evict // that subscription before evicting any other subscriptions, which will result we used exactly kExpectedParallelPaths and have @@ -3511,19 +3471,19 @@ TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) // Part 2: Testing per fabric minimas. // Validate we have more than kMinSupportedSubscriptionsPerFabric subscriptions for testing per fabric minimas. EXPECT_GT(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Subscribe, - mpContext->GetAliceFabricIndex()), + GetAliceFabricIndex()), app::InteractionModelEngine::kMinSupportedSubscriptionsPerFabric); // The following check will trigger the logic in im to kill the read handlers that use more paths than the limit per fabric. { EstablishReadOrSubscriptions( - mpContext->GetSessionAliceToBob(), app::InteractionModelEngine::kMinSupportedSubscriptionsPerFabric, + GetSessionAliceToBob(), app::InteractionModelEngine::kMinSupportedSubscriptionsPerFabric, app::InteractionModelEngine::kMinSupportedPathsPerSubscription, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Subscribe, &readCallbackFabric2, readClients); // Run until we have established the subscriptions. - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallbackFabric2.mOnSubscriptionEstablishedCount == app::InteractionModelEngine::kMinSupportedSubscriptionsPerFabric && readCallbackFabric2.mAttributeCount == @@ -3551,9 +3511,8 @@ TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) readCallbackFabric2.ClearCounters(); // Run until all subscriptions are clean. - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), [&]() { - return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; - }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), + [&]() { return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; }); // Some subscriptions on fabric 1 should be evicted since fabric 1 is using more resources than the limits. EXPECT_EQ(readCallback.mAttributeCount, @@ -3563,22 +3522,22 @@ TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) app::InteractionModelEngine::kMinSupportedPathsPerSubscription * app::InteractionModelEngine::kMinSupportedSubscriptionsPerFabric); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Subscribe, - mpContext->GetAliceFabricIndex()), + GetAliceFabricIndex()), app::InteractionModelEngine::kMinSupportedSubscriptionsPerFabric); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Subscribe, - mpContext->GetBobFabricIndex()), + GetBobFabricIndex()), app::InteractionModelEngine::kMinSupportedSubscriptionsPerFabric); // Ensure our read transactions are still alive. EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Read), 2u); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Shutdown all clients readClients.clear(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->SetForceHandlerQuota(false); app::InteractionModelEngine::GetInstance()->SetHandlerCapacityForSubscriptions(-1); app::InteractionModelEngine::GetInstance()->SetPathPoolCapacityForSubscriptions(-1); @@ -3587,10 +3546,10 @@ TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) TEST_F(TestRead, TestReadHandler_KillOldestSubscriptions) { using namespace SubscriptionPathQuotaHelpers; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); const auto kExpectedParallelSubs = - app::InteractionModelEngine::kMinSupportedSubscriptionsPerFabric * mpContext->GetFabricTable().FabricCount(); + app::InteractionModelEngine::kMinSupportedSubscriptionsPerFabric * GetFabricTable().FabricCount(); const auto kExpectedParallelPaths = kExpectedParallelSubs * app::InteractionModelEngine::kMinSupportedPathsPerSubscription; app::InteractionModelEngine::GetInstance()->RegisterReadHandlerAppCallback(this); @@ -3604,11 +3563,11 @@ TEST_F(TestRead, TestReadHandler_KillOldestSubscriptions) // This should just use all availbale resources. EstablishReadOrSubscriptions( - mpContext->GetSessionBobToAlice(), kExpectedParallelSubs, app::InteractionModelEngine::kMinSupportedPathsPerSubscription, + GetSessionBobToAlice(), kExpectedParallelSubs, app::InteractionModelEngine::kMinSupportedPathsPerSubscription, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Subscribe, &readCallback, readClients); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(readCallback.mAttributeCount, kExpectedParallelSubs * app::InteractionModelEngine::kMinSupportedPathsPerSubscription); EXPECT_EQ(readCallback.mOnSubscriptionEstablishedCount, kExpectedParallelSubs); @@ -3619,11 +3578,11 @@ TEST_F(TestRead, TestReadHandler_KillOldestSubscriptions) TestReadCallback callback; std::vector> outReadClient; EstablishReadOrSubscriptions( - mpContext->GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerSubscription + 1, + GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerSubscription + 1, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Subscribe, &callback, outReadClient); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Over-sized request after used all paths will receive Paths Exhausted status code. EXPECT_EQ(callback.mOnError, 1u); @@ -3633,12 +3592,12 @@ TEST_F(TestRead, TestReadHandler_KillOldestSubscriptions) // The following check will trigger the logic in im to kill the read handlers that uses more paths than the limit per fabric. { EstablishReadOrSubscriptions( - mpContext->GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerSubscription, + GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerSubscription, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Subscribe, &readCallback, readClients); readCallback.ClearCounters(); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // This read handler should evict some existing subscriptions for enough space EXPECT_EQ(readCallback.mOnSubscriptionEstablishedCount, 1u); @@ -3655,17 +3614,17 @@ TEST_F(TestRead, TestReadHandler_KillOldestSubscriptions) app::InteractionModelEngine::GetInstance()->GetReportingEngine().SetDirty(path); } readCallback.ClearCounters(); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_LE(readCallback.mAttributeCount, kExpectedParallelPaths); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Shutdown all clients readClients.clear(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->SetForceHandlerQuota(false); app::InteractionModelEngine::GetInstance()->SetHandlerCapacityForSubscriptions(-1); app::InteractionModelEngine::GetInstance()->SetPathPoolCapacityForSubscriptions(-1); @@ -3678,7 +3637,7 @@ struct TestReadHandler_ParallelReads_TestCase_Parameters int MaxFabrics = -1; }; -static void TestReadHandler_ParallelReads_TestCase(TestContext * apContext, +static void TestReadHandler_ParallelReads_TestCase(TestRead * apContext, const TestReadHandler_ParallelReads_TestCase_Parameters & params, std::function body) { @@ -3704,18 +3663,18 @@ static void TestReadHandler_ParallelReads_TestCase(TestContext * apContext, TEST_F(TestRead, TestReadHandler_ParallelReads) { - // Note: We cannot use mpContext->DrainAndServiceIO() except at the end of each test case since the perpetual read transactions - // will never end. Note: We use mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { CONDITION }); and + // Note: We cannot use DrainAndServiceIO() except at the end of each test case since the perpetual read transactions + // will never end. Note: We use GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { CONDITION }); and // EXPECT_EQ( CONDITION ) to ensure the CONDITION is satisfied. using namespace SubscriptionPathQuotaHelpers; using Params = TestReadHandler_ParallelReads_TestCase_Parameters; - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); app::InteractionModelEngine::GetInstance()->RegisterReadHandlerAppCallback(this); auto TestCase = [&](const TestReadHandler_ParallelReads_TestCase_Parameters & params, std::function body) { - TestReadHandler_ParallelReads_TestCase(mpContext, params, body); + TestReadHandler_ParallelReads_TestCase(this, params, body); }; // Case 1.1: 2 reads used up the path pool (but not the ReadHandler pool), and one incoming oversized read request => @@ -3732,16 +3691,14 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); @@ -3750,11 +3707,11 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) backgroundReadCallback2.ClearCounter(); EstablishReadOrSubscriptions( - mpContext->GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, + GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The two subscriptions should still alive EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); @@ -3777,14 +3734,14 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); @@ -3793,11 +3750,11 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) backgroundReadCallback2.ClearCounter(); EstablishReadOrSubscriptions( - mpContext->GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, + GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The two subscriptions should still alive EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); @@ -3819,26 +3776,24 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); EstablishReadOrSubscriptions( - mpContext->GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, + GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be accepted EXPECT_EQ(readCallback.mAttributeCount, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1); @@ -3847,7 +3802,7 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) // The two subscriptions should still alive backgroundReadCallback1.ClearCounter(); backgroundReadCallback2.ClearCounter(); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); @@ -3866,16 +3821,14 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); @@ -3884,11 +3837,11 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) backgroundReadCallback2.ClearCounter(); EstablishReadOrSubscriptions( - mpContext->GetSessionAliceToBob(), 1, 1, + GetSessionAliceToBob(), 1, 1, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be accepted EXPECT_EQ(readCallback.mAttributeCount, 1u); @@ -3897,7 +3850,7 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) // The two subscriptions should still alive backgroundReadCallback1.ClearCounter(); backgroundReadCallback2.ClearCounter(); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); @@ -3917,27 +3870,26 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &readCallbackForOversizedRead, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return readCallbackForOversizedRead.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), + [&]() { return readCallbackForOversizedRead.reportsReceived > 0; }); - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback.reportsReceived > 0; }); EXPECT_TRUE(readCallbackForOversizedRead.reportsReceived > 0 && backgroundReadCallback.reportsReceived > 0); EstablishReadOrSubscriptions( - mpContext->GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be accepted. EXPECT_EQ(readCallback.mOnError, 0u); @@ -3948,8 +3900,7 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 1u); backgroundReadCallback.ClearCounter(); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback.reportsReceived > 0; }); // We don't check the readCallbackForOversizedRead, since it cannot prove anything -- it can be 0 even when the // oversized read request is alive. We ensure this by checking (1) we have only one active read handler, (2) the one @@ -3973,27 +3924,26 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback.reportsReceived > 0; }); - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &readCallbackForOversizedRead, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return readCallbackForOversizedRead.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), + [&]() { return readCallbackForOversizedRead.reportsReceived > 0; }); EXPECT_TRUE(readCallbackForOversizedRead.reportsReceived > 0 && backgroundReadCallback.reportsReceived > 0); EstablishReadOrSubscriptions( - mpContext->GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be accepted. EXPECT_EQ(readCallback.mOnError, 0u); @@ -4004,8 +3954,7 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 1u); backgroundReadCallback.ClearCounter(); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback.reportsReceived > 0; }); // We don't check the readCallbackForOversizedRead, since it cannot prove anything -- it can be 0 even when the // oversized read request is alive. We ensure this by checking (1) we have only one active read handler, (2) the one @@ -4031,25 +3980,25 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &readCallbackForOversizedRead, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback.reportsReceived > 0 && readCallbackForOversizedRead.reportsReceived > 0; }); EXPECT_TRUE(readCallbackForOversizedRead.reportsReceived > 0 && backgroundReadCallback.reportsReceived > 0); EstablishReadOrSubscriptions( - mpContext->GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be rejected. EXPECT_NE(readCallback.mOnError, 0u); @@ -4058,7 +4007,7 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) // Ensure the two read transactions are not evicted. backgroundReadCallback.ClearCounter(); readCallbackForOversizedRead.ClearCounter(); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallbackForOversizedRead.reportsReceived > 0 && backgroundReadCallback.reportsReceived > 0; }); EXPECT_TRUE(readCallbackForOversizedRead.reportsReceived > 0 && backgroundReadCallback.reportsReceived > 0); @@ -4079,28 +4028,26 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback1.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0; }); - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback2.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); backgroundReadCallback1.ClearCounter(); backgroundReadCallback2.ClearCounter(); EstablishReadOrSubscriptions( - mpContext->GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be rejected. EXPECT_EQ(readCallback.mOnError, 0u); @@ -4113,8 +4060,7 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 1u); // Note: Younger read handler will be evicted. - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback1.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0; }); EXPECT_GT(backgroundReadCallback1.reportsReceived, 0); }); @@ -4132,29 +4078,27 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback1.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0; }); - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback2.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); backgroundReadCallback1.ClearCounter(); backgroundReadCallback2.ClearCounter(); EstablishReadOrSubscriptions( - mpContext->GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be rejected. EXPECT_EQ(readCallback.mOnError, 0u); @@ -4167,8 +4111,7 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 1u); // Note: Larger read handler will be evicted before evicting the younger one. - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback2.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback2.reportsReceived > 0; }); EXPECT_GT(backgroundReadCallback2.reportsReceived, 0); }); @@ -4189,17 +4132,17 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback3; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, 1, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback3, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0 && backgroundReadCallback3.reportsReceived > 0; }); @@ -4207,11 +4150,11 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) backgroundReadCallback3.reportsReceived > 0); EstablishReadOrSubscriptions( - mpContext->GetSessionCharlieToDavid(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + GetSessionCharlieToDavid(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be accepted. EXPECT_EQ(readCallback.mOnError, 0u); @@ -4219,10 +4162,10 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(readCallback.mAttributeCount, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest); // Should evict one read request from Bob fabric for enough resources. EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Read, - mpContext->GetAliceFabricIndex()), + GetAliceFabricIndex()), 1u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Read, - mpContext->GetBobFabricIndex()), + GetBobFabricIndex()), 1u); }); @@ -4243,17 +4186,17 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback3; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, 1, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, 1, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, 1, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback3, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0 && backgroundReadCallback3.reportsReceived > 0; }); @@ -4261,11 +4204,11 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) backgroundReadCallback3.reportsReceived > 0); EstablishReadOrSubscriptions( - mpContext->GetSessionCharlieToDavid(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + GetSessionCharlieToDavid(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be accepted. EXPECT_EQ(readCallback.mOnError, 0u); @@ -4273,10 +4216,10 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(readCallback.mAttributeCount, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest); // Should evict one read request from Bob fabric for enough resources. EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Read, - mpContext->GetAliceFabricIndex()), + GetAliceFabricIndex()), 1u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Read, - mpContext->GetBobFabricIndex()), + GetBobFabricIndex()), 1u); }); @@ -4295,20 +4238,17 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback3; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback3, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0 && backgroundReadCallback3.reportsReceived > 0; }); @@ -4316,21 +4256,21 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) backgroundReadCallback3.reportsReceived > 0); EstablishReadOrSubscriptions( - mpContext->GetSessionCharlieToDavid(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + GetSessionCharlieToDavid(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be rejected. EXPECT_EQ(readCallback.mOnError, 1u); EXPECT_EQ(readCallback.mLastError, CHIP_IM_GLOBAL_STATUS(Busy)); // Should evict one read request from Bob fabric for enough resources. EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Read, - mpContext->GetAliceFabricIndex()), + GetAliceFabricIndex()), 2u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Read, - mpContext->GetBobFabricIndex()), + GetBobFabricIndex()), 1u); }); @@ -4348,26 +4288,24 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); EstablishReadOrSubscriptions( - mpContext->GetSessionCharlieToDavid(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + GetSessionCharlieToDavid(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be accepted. EXPECT_EQ(readCallback.mOnError, 0u); @@ -4375,10 +4313,10 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(readCallback.mAttributeCount, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest); // No read transactions should be evicted. EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Read, - mpContext->GetAliceFabricIndex()), + GetAliceFabricIndex()), 1u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Read, - mpContext->GetBobFabricIndex()), + GetBobFabricIndex()), 1u); }); @@ -4396,22 +4334,22 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionCharlieToDavid(), 1, 1, + EstablishReadOrSubscriptions(GetSessionCharlieToDavid(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, 1, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); EstablishReadOrSubscriptions( - mpContext->GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be accepted. EXPECT_EQ(readCallback.mOnError, 0u); @@ -4440,23 +4378,23 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(mpContext->GetSessionCharlieToDavid(), 1, 1, + EstablishReadOrSubscriptions(GetSessionCharlieToDavid(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); EstablishReadOrSubscriptions( - mpContext->GetSessionBobToAlice(), 1, 1, + GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be accepted. EXPECT_EQ(readCallback.mOnError, 0u); @@ -4486,15 +4424,15 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) std::vector> readClients; EstablishReadOrSubscriptions( - mpContext->GetSessionCharlieToDavid(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), + GetSessionCharlieToDavid(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallbackForPASESession, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, 1, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, 1, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallbackForPASESession.reportsReceived > 0 && backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0; }); @@ -4502,10 +4440,10 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) backgroundReadCallback2.reportsReceived > 0); EstablishReadOrSubscriptions( - mpContext->GetSessionBobToAlice(), 1, 1, + GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be accepted. EXPECT_EQ(readCallback.mOnError, 0u); @@ -4538,14 +4476,14 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) std::vector> readClients; EstablishReadOrSubscriptions( - mpContext->GetSessionCharlieToDavid(), 3, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest - 1, + GetSessionCharlieToDavid(), 3, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest - 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallbackForPASESession, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionBobToAlice(), 3, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 3, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers( app::ReadHandler::InteractionType::Read) == 6; }); @@ -4555,10 +4493,10 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) // We have to evict one read transaction on PASE session and one read transaction on Alice's fabric. EstablishReadOrSubscriptions( - mpContext->GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be accepted. EXPECT_EQ(readCallback.mOnError, 0u); @@ -4591,18 +4529,18 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) std::vector> readClients; EstablishReadOrSubscriptions( - mpContext->GetSessionCharlieToDavid(), 2, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest - 1, + GetSessionCharlieToDavid(), 2, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest - 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallbackForPASESession, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(mpContext->GetSessionAliceToBob(), 1, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallbackForPASESession.reportsReceived > 0 && backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0 && app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(app::ReadHandler::InteractionType::Read, @@ -4615,10 +4553,10 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) // To handle this read request, we must evict both read transactions from the PASE session. EstablishReadOrSubscriptions( - mpContext->GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id), app::ReadClient::InteractionType::Read, &readCallback, readClients); - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.mOnDone != 0; }); // The new read request should be accepted. EXPECT_EQ(readCallback.mOnError, 0u); @@ -4635,9 +4573,9 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) }); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->SetForceHandlerQuota(false); app::InteractionModelEngine::GetInstance()->SetConfigMaxFabrics(-1); app::InteractionModelEngine::GetInstance()->SetHandlerCapacityForReads(-1); @@ -4651,14 +4589,14 @@ TEST_F(TestRead, TestReadHandler_TooManyPaths) { using namespace chip::app; - chip::Messaging::ReliableMessageMgr * rm = mpContext->GetExchangeManager().GetReliableMessageMgr(); + chip::Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); auto * engine = InteractionModelEngine::GetInstance(); engine->SetForceHandlerQuota(true); - ReadPrepareParams readPrepareParams(mpContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); // Needs to be larger than our plausible path pool. chip::app::AttributePathParams attributePathParams[sTooLargePathCount]; readPrepareParams.mpAttributePathParamsList = attributePathParams; @@ -4668,13 +4606,13 @@ TEST_F(TestRead, TestReadHandler_TooManyPaths) MockInteractionModelApp delegate; EXPECT_EQ(delegate.mNumAttributeResponse, 0); EXPECT_FALSE(delegate.mReadError); - ReadClient readClient(InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), delegate, + ReadClient readClient(InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, ReadClient::InteractionType::Read); CHIP_ERROR err = readClient.SendRequest(readPrepareParams); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(delegate.mNumAttributeResponse, 0); EXPECT_TRUE(delegate.mReadError); @@ -4684,7 +4622,7 @@ TEST_F(TestRead, TestReadHandler_TooManyPaths) } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); engine->SetForceHandlerQuota(false); } @@ -4692,7 +4630,7 @@ TEST_F(TestRead, TestReadHandler_TwoParallelReadsSecondTooManyPaths) { using namespace chip::app; - chip::Messaging::ReliableMessageMgr * rm = mpContext->GetExchangeManager().GetReliableMessageMgr(); + chip::Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. EXPECT_EQ(rm->TestGetCountRetransTable(), 0); @@ -4703,16 +4641,16 @@ TEST_F(TestRead, TestReadHandler_TwoParallelReadsSecondTooManyPaths) MockInteractionModelApp delegate1; EXPECT_EQ(delegate1.mNumAttributeResponse, 0); EXPECT_FALSE(delegate1.mReadError); - ReadClient readClient1(InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), delegate1, + ReadClient readClient1(InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate1, ReadClient::InteractionType::Read); MockInteractionModelApp delegate2; EXPECT_EQ(delegate2.mNumAttributeResponse, 0); EXPECT_FALSE(delegate2.mReadError); - ReadClient readClient2(InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), delegate2, + ReadClient readClient2(InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate2, ReadClient::InteractionType::Read); - ReadPrepareParams readPrepareParams1(mpContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams1(GetSessionBobToAlice()); // Read full wildcard paths, repeat twice to ensure chunking. chip::app::AttributePathParams attributePathParams1[2]; readPrepareParams1.mpAttributePathParamsList = attributePathParams1; @@ -4721,7 +4659,7 @@ TEST_F(TestRead, TestReadHandler_TwoParallelReadsSecondTooManyPaths) CHIP_ERROR err = readClient1.SendRequest(readPrepareParams1); EXPECT_EQ(err, CHIP_NO_ERROR); - ReadPrepareParams readPrepareParams2(mpContext->GetSessionBobToAlice()); + ReadPrepareParams readPrepareParams2(GetSessionBobToAlice()); // Read full wildcard paths, repeat twice to ensure chunking. chip::app::AttributePathParams attributePathParams2[sTooLargePathCount]; readPrepareParams2.mpAttributePathParamsList = attributePathParams2; @@ -4730,7 +4668,7 @@ TEST_F(TestRead, TestReadHandler_TwoParallelReadsSecondTooManyPaths) err = readClient2.SendRequest(readPrepareParams2); EXPECT_EQ(err, CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_NE(delegate1.mNumAttributeResponse, 0); EXPECT_FALSE(delegate1.mReadError); @@ -4743,13 +4681,13 @@ TEST_F(TestRead, TestReadHandler_TwoParallelReadsSecondTooManyPaths) } EXPECT_EQ(engine->GetNumActiveReadClients(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); engine->SetForceHandlerQuota(false); } TEST_F(TestRead, TestReadAttribute_ManyDataValues) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); size_t successCalls = 0; size_t failureCalls = 0; @@ -4768,21 +4706,21 @@ TEST_F(TestRead, TestReadAttribute_ManyDataValues) // not safe to do so. auto onFailureCb = [&failureCalls](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { ++failureCalls; }; - Controller::ReadAttribute(&mpContext->GetExchangeManager(), sessionHandle, + Controller::ReadAttribute(&GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(successCalls, 1u); EXPECT_EQ(failureCalls, 0u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients(), 0u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestRead, TestReadAttribute_ManyDataValuesWrongPath) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); size_t successCalls = 0; size_t failureCalls = 0; @@ -4801,21 +4739,21 @@ TEST_F(TestRead, TestReadAttribute_ManyDataValuesWrongPath) // not safe to do so. auto onFailureCb = [&failureCalls](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { ++failureCalls; }; - Controller::ReadAttribute(&mpContext->GetExchangeManager(), sessionHandle, + Controller::ReadAttribute(&GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(successCalls, 0u); EXPECT_EQ(failureCalls, 1u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients(), 0u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestRead, TestReadAttribute_ManyErrors) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); size_t successCalls = 0; size_t failureCalls = 0; @@ -4834,16 +4772,16 @@ TEST_F(TestRead, TestReadAttribute_ManyErrors) // not safe to do so. auto onFailureCb = [&failureCalls](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { ++failureCalls; }; - Controller::ReadAttribute(&mpContext->GetExchangeManager(), sessionHandle, + Controller::ReadAttribute(&GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(successCalls, 0u); EXPECT_EQ(failureCalls, 1u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients(), 0u); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // @@ -4859,7 +4797,7 @@ TEST_F(TestRead, TestReadHandler_KeepSubscriptionTest) TestReadCallback readCallback; app::AttributePathParams pathParams(kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int16u::Id); - app::ReadPrepareParams readParam(mpContext->GetSessionAliceToBob()); + app::ReadPrepareParams readParam(GetSessionAliceToBob()); readParam.mpAttributePathParamsList = &pathParams; readParam.mAttributePathParamsListSize = 1; readParam.mMaxIntervalCeilingSeconds = 1; @@ -4870,7 +4808,7 @@ TEST_F(TestRead, TestReadHandler_KeepSubscriptionTest) app::ReadClient::InteractionType::Subscribe); EXPECT_EQ(readClient->SendRequest(readParam), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 1u); @@ -4882,12 +4820,12 @@ TEST_F(TestRead, TestReadHandler_KeepSubscriptionTest) app::ReadClient::InteractionType::Subscribe); EXPECT_EQ(readClient->SendRequest(readParam), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 0u); EXPECT_NE(readCallback.mOnError, 0u); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); } System::Clock::Timeout TestRead::ComputeSubscriptionTimeout(System::Clock::Seconds16 aMaxInterval) diff --git a/src/controller/tests/data_model/TestWrite.cpp b/src/controller/tests/data_model/TestWrite.cpp index e0f2c19480a1b0..23c25ff2b8fc99 100644 --- a/src/controller/tests/data_model/TestWrite.cpp +++ b/src/controller/tests/data_model/TestWrite.cpp @@ -16,7 +16,7 @@ * limitations under the License. */ -#include +#include #include "app-common/zap-generated/ids/Clusters.h" #include @@ -30,8 +30,6 @@ #include #include -using TestContext = chip::Test::AppContext; - using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; @@ -253,31 +251,9 @@ class SingleWriteCallback : public WriteClient::Callback namespace { -class TestWrite : public ::testing::Test +class TestWrite : public chip::Test::AppContext { public: - // Performs shared setup for all tests in the test suite - static void SetUpTestSuite() - { - if (mpContext == nullptr) - { - mpContext = new TestContext(); - ASSERT_NE(mpContext, nullptr); - } - mpContext->SetUpTestSuite(); - } - - // Performs shared teardown for all tests in the test suite - static void TearDownTestSuite() - { - mpContext->TearDownTestSuite(); - if (mpContext != nullptr) - { - delete mpContext; - mpContext = nullptr; - } - } - void ResetCallback() { mSingleWriteCallback.reset(); } void PrepareWriteCallback(ConcreteAttributePath path) { mSingleWriteCallback = std::make_unique(path); } @@ -285,22 +261,12 @@ class TestWrite : public ::testing::Test SingleWriteCallback * GetWriteCallback() { return mSingleWriteCallback.get(); } protected: - // Performs setup for each individual test in the test suite - void SetUp() { mpContext->SetUp(); } - - // Performs teardown for each individual test in the test suite - void TearDown() { mpContext->TearDown(); } - - static TestContext * mpContext; - std::unique_ptr mSingleWriteCallback; }; -TestContext * TestWrite::mpContext = nullptr; - TEST_F(TestWrite, TestDataResponse) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; Clusters::UnitTesting::Structs::TestListStructOctet::Type valueBuf[4]; Clusters::UnitTesting::Attributes::ListStructOctetString::TypeInfo::Type value; @@ -329,16 +295,16 @@ TEST_F(TestWrite, TestDataResponse) chip::Controller::WriteAttribute( sessionHandle, kTestEndpointId, value, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(onSuccessCbInvoked && !onFailureCbInvoked); EXPECT_EQ(chip::app::InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestWrite, TestDataResponseWithAcceptedDataVersion) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; Clusters::UnitTesting::Structs::TestListStructOctet::Type valueBuf[4]; Clusters::UnitTesting::Attributes::ListStructOctetString::TypeInfo::Type value; @@ -369,16 +335,16 @@ TEST_F(TestWrite, TestDataResponseWithAcceptedDataVersion) chip::Controller::WriteAttribute( sessionHandle, kTestEndpointId, value, onSuccessCb, onFailureCb, nullptr, dataVersion); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(onSuccessCbInvoked && !onFailureCbInvoked); EXPECT_EQ(chip::app::InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestWrite, TestDataResponseWithRejectedDataVersion) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; Clusters::UnitTesting::Structs::TestListStructOctet::Type valueBuf[4]; Clusters::UnitTesting::Attributes::ListStructOctetString::TypeInfo::Type value; @@ -408,16 +374,16 @@ TEST_F(TestWrite, TestDataResponseWithRejectedDataVersion) chip::Controller::WriteAttribute( sessionHandle, kTestEndpointId, value, onSuccessCb, onFailureCb, nullptr, dataVersion); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(!onSuccessCbInvoked && onFailureCbInvoked); EXPECT_EQ(chip::app::InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestWrite, TestAttributeError) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; Attributes::ListStructOctetString::TypeInfo::Type value; Structs::TestListStructOctet::Type valueBuf[4]; @@ -447,16 +413,16 @@ TEST_F(TestWrite, TestAttributeError) Controller::WriteAttribute(sessionHandle, kTestEndpointId, value, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(!onSuccessCbInvoked && onFailureCbInvoked); EXPECT_EQ(InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestWrite, TestFabricScopedAttributeWithoutFabricIndex) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; Clusters::UnitTesting::Structs::TestFabricScoped::Type valueBuf[4]; Clusters::UnitTesting::Attributes::ListFabricScoped::TypeInfo::Type value; @@ -484,16 +450,16 @@ TEST_F(TestWrite, TestFabricScopedAttributeWithoutFabricIndex) chip::Controller::WriteAttribute( sessionHandle, kTestEndpointId, value, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(!onSuccessCbInvoked && onFailureCbInvoked); EXPECT_EQ(chip::app::InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestWrite, TestMultipleSuccessResponses) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); size_t successCalls = 0; size_t failureCalls = 0; @@ -510,17 +476,17 @@ TEST_F(TestWrite, TestMultipleSuccessResponses) chip::Controller::WriteAttribute(sessionHandle, kTestEndpointId, true, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(successCalls, 1u); EXPECT_EQ(failureCalls, 0u); EXPECT_EQ(chip::app::InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestWrite, TestMultipleFailureResponses) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); size_t successCalls = 0; size_t failureCalls = 0; @@ -537,17 +503,17 @@ TEST_F(TestWrite, TestMultipleFailureResponses) chip::Controller::WriteAttribute(sessionHandle, kTestEndpointId, true, onSuccessCb, onFailureCb); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(successCalls, 0u); EXPECT_EQ(failureCalls, 1u); EXPECT_EQ(chip::app::InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } TEST_F(TestWrite, TestWriteClusterSpecificStatuses) { - auto sessionHandle = mpContext->GetSessionBobToAlice(); + auto sessionHandle = GetSessionBobToAlice(); // Cluster-specific success code case { @@ -559,14 +525,14 @@ TEST_F(TestWrite, TestWriteClusterSpecificStatuses) SingleWriteCallback * writeCb = this->GetWriteCallback(); - WriteClient writeClient(&mpContext->GetExchangeManager(), this->GetWriteCallback(), Optional::Missing()); + WriteClient writeClient(&GetExchangeManager(), this->GetWriteCallback(), Optional::Missing()); AttributePathParams attributePath{ kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int8u::Id }; constexpr uint8_t attributeValue = 1u; ASSERT_EQ(writeClient.EncodeAttribute(attributePath, attributeValue), CHIP_NO_ERROR); ASSERT_EQ(writeClient.SendWriteRequest(sessionHandle), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(writeCb->WasDone()); EXPECT_TRUE(writeCb->PathWasResponded()); @@ -578,7 +544,7 @@ TEST_F(TestWrite, TestWriteClusterSpecificStatuses) EXPECT_EQ(pathStatus.mClusterStatus.Value(), kExampleClusterSpecificSuccess); EXPECT_EQ(chip::app::InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } // Cluster-specific failure code case @@ -591,7 +557,7 @@ TEST_F(TestWrite, TestWriteClusterSpecificStatuses) SingleWriteCallback * writeCb = this->GetWriteCallback(); - WriteClient writeClient(&mpContext->GetExchangeManager(), this->GetWriteCallback(), Optional::Missing()); + WriteClient writeClient(&GetExchangeManager(), this->GetWriteCallback(), Optional::Missing()); AttributePathParams attributePath{ kTestEndpointId, Clusters::UnitTesting::Id, Clusters::UnitTesting::Attributes::Int8u::Id }; @@ -599,7 +565,7 @@ TEST_F(TestWrite, TestWriteClusterSpecificStatuses) ASSERT_EQ(writeClient.EncodeAttribute(attributePath, attributeValue), CHIP_NO_ERROR); ASSERT_EQ(writeClient.SendWriteRequest(sessionHandle), CHIP_NO_ERROR); - mpContext->DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_TRUE(writeCb->WasDone()); EXPECT_TRUE(writeCb->PathWasResponded()); @@ -611,7 +577,7 @@ TEST_F(TestWrite, TestWriteClusterSpecificStatuses) EXPECT_EQ(pathStatus.mClusterStatus.Value(), kExampleClusterSpecificFailure); EXPECT_EQ(chip::app::InteractionModelEngine::GetInstance()->GetNumActiveWriteHandlers(), 0u); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } } diff --git a/src/messaging/tests/BUILD.gn b/src/messaging/tests/BUILD.gn index 3232796aabe7e1..9cb017ea512c3a 100644 --- a/src/messaging/tests/BUILD.gn +++ b/src/messaging/tests/BUILD.gn @@ -32,6 +32,7 @@ static_library("helpers") { deps = [ "${chip_root}/src/credentials/tests:cert_test_vectors", "${chip_root}/src/lib/support:testing", + "${chip_root}/src/lib/support/tests:pw-test-macros", "${chip_root}/src/messaging", "${chip_root}/src/protocols", "${chip_root}/src/transport", diff --git a/src/messaging/tests/MessagingContext.cpp b/src/messaging/tests/MessagingContext.cpp index 14ef27f147b624..c390f99096bb03 100644 --- a/src/messaging/tests/MessagingContext.cpp +++ b/src/messaging/tests/MessagingContext.cpp @@ -31,34 +31,34 @@ using namespace TestCerts; CHIP_ERROR MessagingContext::Init(TransportMgrBase * transport, IOContext * ioContext) { - VerifyOrReturnError(mInitialized == false, CHIP_ERROR_INTERNAL); - mInitialized = true; + VerifyOrReturnError(mpData->mInitialized == false, CHIP_ERROR_INTERNAL); + mpData->mInitialized = true; - mIOContext = ioContext; - mTransport = transport; + mpData->mIOContext = ioContext; + mpData->mTransport = transport; ReturnErrorOnFailure(PlatformMemoryUser::Init()); // Make sure the storage is clean, so we will not reuse any stale data. - mStorage.ClearStorage(); + mpData->mStorage.ClearStorage(); - ReturnErrorOnFailure(mOpKeyStore.Init(&mStorage)); - ReturnErrorOnFailure(mOpCertStore.Init(&mStorage)); + ReturnErrorOnFailure(mpData->mOpKeyStore.Init(&mpData->mStorage)); + ReturnErrorOnFailure(mpData->mOpCertStore.Init(&mpData->mStorage)); chip::FabricTable::InitParams initParams; - initParams.storage = &mStorage; - initParams.operationalKeystore = &mOpKeyStore; - initParams.opCertStore = &mOpCertStore; + initParams.storage = &mpData->mStorage; + initParams.operationalKeystore = &mpData->mOpKeyStore; + initParams.opCertStore = &mpData->mOpCertStore; - ReturnErrorOnFailure(mFabricTable.Init(initParams)); + ReturnErrorOnFailure(mpData->mFabricTable.Init(initParams)); - ReturnErrorOnFailure( - mSessionManager.Init(&GetSystemLayer(), transport, &mMessageCounterManager, &mStorage, &mFabricTable, mSessionKeystore)); + ReturnErrorOnFailure(mpData->mSessionManager.Init(&GetSystemLayer(), transport, &mpData->mMessageCounterManager, + &mpData->mStorage, &mpData->mFabricTable, mpData->mSessionKeystore)); - ReturnErrorOnFailure(mExchangeManager.Init(&mSessionManager)); - ReturnErrorOnFailure(mMessageCounterManager.Init(&mExchangeManager)); + ReturnErrorOnFailure(mpData->mExchangeManager.Init(&mpData->mSessionManager)); + ReturnErrorOnFailure(mpData->mMessageCounterManager.Init(&mpData->mExchangeManager)); - if (mInitializeNodes) + if (mpData->mInitializeNodes) { ReturnErrorOnFailure(CreateAliceFabric()); ReturnErrorOnFailure(CreateBobFabric()); @@ -80,15 +80,15 @@ CHIP_ERROR MessagingContext::Init(TransportMgrBase * transport, IOContext * ioCo // Shutdown all layers, finalize operations void MessagingContext::Shutdown() { - VerifyOrDie(mInitialized); - mInitialized = false; + VerifyOrDie(mpData->mInitialized); + mpData->mInitialized = false; - mMessageCounterManager.Shutdown(); - mExchangeManager.Shutdown(); - mSessionManager.Shutdown(); - mFabricTable.Shutdown(); - mOpCertStore.Finish(); - mOpKeyStore.Finish(); + mpData->mMessageCounterManager.Shutdown(); + mpData->mExchangeManager.Shutdown(); + mpData->mSessionManager.Shutdown(); + mpData->mFabricTable.Shutdown(); + mpData->mOpCertStore.Finish(); + mpData->mOpKeyStore.Finish(); // Reset the default additional MRP backoff. Messaging::ReliableMessageMgr::SetAdditionalMRPBackoffTime(NullOptional); @@ -96,7 +96,7 @@ void MessagingContext::Shutdown() CHIP_ERROR MessagingContext::InitFromExisting(const MessagingContext & existing) { - return Init(existing.mTransport, existing.mIOContext); + return Init(existing.mpData->mTransport, existing.mpData->mIOContext); } void MessagingContext::ShutdownAndRestoreExisting(MessagingContext & existing) @@ -104,7 +104,7 @@ void MessagingContext::ShutdownAndRestoreExisting(MessagingContext & existing) Shutdown(); // Point the transport back to the original session manager, since we had // pointed it to ours. - existing.mTransport->SetSessionManager(&existing.GetSecureSessionManager()); + existing.mpData->mTransport->SetSessionManager(&existing.GetSecureSessionManager()); } using namespace System::Clock::Literals; @@ -116,10 +116,10 @@ void MessagingContext::SetMRPMode(MRPMode mode) { if (mode == MRPMode::kDefault) { - mSessionBobToAlice->AsSecureSession()->SetRemoteSessionParameters(GetDefaultMRPConfig()); - mSessionAliceToBob->AsSecureSession()->SetRemoteSessionParameters(GetDefaultMRPConfig()); - mSessionCharlieToDavid->AsSecureSession()->SetRemoteSessionParameters(GetDefaultMRPConfig()); - mSessionDavidToCharlie->AsSecureSession()->SetRemoteSessionParameters(GetDefaultMRPConfig()); + mpData->mSessionBobToAlice->AsSecureSession()->SetRemoteSessionParameters(GetDefaultMRPConfig()); + mpData->mSessionAliceToBob->AsSecureSession()->SetRemoteSessionParameters(GetDefaultMRPConfig()); + mpData->mSessionCharlieToDavid->AsSecureSession()->SetRemoteSessionParameters(GetDefaultMRPConfig()); + mpData->mSessionDavidToCharlie->AsSecureSession()->SetRemoteSessionParameters(GetDefaultMRPConfig()); #if CONFIG_BUILD_FOR_HOST_UNIT_TEST ClearLocalMRPConfigOverride(); @@ -143,163 +143,169 @@ void MessagingContext::SetMRPMode(MRPMode mode) VerifyOrDie(false); #endif - mSessionBobToAlice->AsSecureSession()->SetRemoteSessionParameters(ReliableMessageProtocolConfig( + mpData->mSessionBobToAlice->AsSecureSession()->SetRemoteSessionParameters(ReliableMessageProtocolConfig( MessagingContext::kResponsiveIdleRetransTimeout, MessagingContext::kResponsiveActiveRetransTimeout)); - mSessionAliceToBob->AsSecureSession()->SetRemoteSessionParameters(ReliableMessageProtocolConfig( + mpData->mSessionAliceToBob->AsSecureSession()->SetRemoteSessionParameters(ReliableMessageProtocolConfig( MessagingContext::kResponsiveIdleRetransTimeout, MessagingContext::kResponsiveActiveRetransTimeout)); - mSessionCharlieToDavid->AsSecureSession()->SetRemoteSessionParameters(ReliableMessageProtocolConfig( + mpData->mSessionCharlieToDavid->AsSecureSession()->SetRemoteSessionParameters(ReliableMessageProtocolConfig( MessagingContext::kResponsiveIdleRetransTimeout, MessagingContext::kResponsiveActiveRetransTimeout)); - mSessionDavidToCharlie->AsSecureSession()->SetRemoteSessionParameters(ReliableMessageProtocolConfig( + mpData->mSessionDavidToCharlie->AsSecureSession()->SetRemoteSessionParameters(ReliableMessageProtocolConfig( MessagingContext::kResponsiveIdleRetransTimeout, MessagingContext::kResponsiveActiveRetransTimeout)); } } CHIP_ERROR MessagingContext::CreateAliceFabric() { - return mFabricTable.AddNewFabricForTestIgnoringCollisions(GetRootACertAsset().mCert, GetIAA1CertAsset().mCert, - GetNodeA1CertAsset().mCert, GetNodeA1CertAsset().mKey, - &mAliceFabricIndex); + return mpData->mFabricTable.AddNewFabricForTestIgnoringCollisions(GetRootACertAsset().mCert, GetIAA1CertAsset().mCert, + GetNodeA1CertAsset().mCert, GetNodeA1CertAsset().mKey, + &mpData->mAliceFabricIndex); } CHIP_ERROR MessagingContext::CreateBobFabric() { - return mFabricTable.AddNewFabricForTestIgnoringCollisions(GetRootACertAsset().mCert, GetIAA1CertAsset().mCert, - GetNodeA2CertAsset().mCert, GetNodeA2CertAsset().mKey, - &mBobFabricIndex); + return mpData->mFabricTable.AddNewFabricForTestIgnoringCollisions(GetRootACertAsset().mCert, GetIAA1CertAsset().mCert, + GetNodeA2CertAsset().mCert, GetNodeA2CertAsset().mKey, + &mpData->mBobFabricIndex); } CHIP_ERROR MessagingContext::CreateSessionBobToAlice() { - return mSessionManager.InjectPaseSessionWithTestKey(mSessionBobToAlice, kBobKeyId, GetAliceFabric()->GetNodeId(), kAliceKeyId, - mBobFabricIndex, mAliceAddress, CryptoContext::SessionRole::kInitiator); + return mpData->mSessionManager.InjectPaseSessionWithTestKey(mpData->mSessionBobToAlice, kBobKeyId, + GetAliceFabric()->GetNodeId(), kAliceKeyId, mpData->mBobFabricIndex, + mpData->mAliceAddress, CryptoContext::SessionRole::kInitiator); } CHIP_ERROR MessagingContext::CreateCASESessionBobToAlice() { - return mSessionManager.InjectCaseSessionWithTestKey(mSessionBobToAlice, kBobKeyId, kAliceKeyId, GetBobFabric()->GetNodeId(), - GetAliceFabric()->GetNodeId(), mBobFabricIndex, mAliceAddress, - CryptoContext::SessionRole::kInitiator); + return mpData->mSessionManager.InjectCaseSessionWithTestKey( + mpData->mSessionBobToAlice, kBobKeyId, kAliceKeyId, GetBobFabric()->GetNodeId(), GetAliceFabric()->GetNodeId(), + mpData->mBobFabricIndex, mpData->mAliceAddress, CryptoContext::SessionRole::kInitiator); } CHIP_ERROR MessagingContext::CreateCASESessionBobToAlice(const CATValues & cats) { - return mSessionManager.InjectCaseSessionWithTestKey(mSessionBobToAlice, kBobKeyId, kAliceKeyId, GetBobFabric()->GetNodeId(), - GetAliceFabric()->GetNodeId(), mBobFabricIndex, mAliceAddress, - CryptoContext::SessionRole::kInitiator, cats); + return mpData->mSessionManager.InjectCaseSessionWithTestKey( + mpData->mSessionBobToAlice, kBobKeyId, kAliceKeyId, GetBobFabric()->GetNodeId(), GetAliceFabric()->GetNodeId(), + mpData->mBobFabricIndex, mpData->mAliceAddress, CryptoContext::SessionRole::kInitiator, cats); } CHIP_ERROR MessagingContext::CreateSessionAliceToBob() { - return mSessionManager.InjectPaseSessionWithTestKey(mSessionAliceToBob, kAliceKeyId, GetBobFabric()->GetNodeId(), kBobKeyId, - mAliceFabricIndex, mBobAddress, CryptoContext::SessionRole::kResponder); + return mpData->mSessionManager.InjectPaseSessionWithTestKey(mpData->mSessionAliceToBob, kAliceKeyId, + GetBobFabric()->GetNodeId(), kBobKeyId, mpData->mAliceFabricIndex, + mpData->mBobAddress, CryptoContext::SessionRole::kResponder); } CHIP_ERROR MessagingContext::CreateCASESessionAliceToBob() { - return mSessionManager.InjectCaseSessionWithTestKey(mSessionAliceToBob, kAliceKeyId, kBobKeyId, GetAliceFabric()->GetNodeId(), - GetBobFabric()->GetNodeId(), mAliceFabricIndex, mBobAddress, - CryptoContext::SessionRole::kResponder); + return mpData->mSessionManager.InjectCaseSessionWithTestKey( + mpData->mSessionAliceToBob, kAliceKeyId, kBobKeyId, GetAliceFabric()->GetNodeId(), GetBobFabric()->GetNodeId(), + mpData->mAliceFabricIndex, mpData->mBobAddress, CryptoContext::SessionRole::kResponder); } CHIP_ERROR MessagingContext::CreateCASESessionAliceToBob(const CATValues & cats) { - return mSessionManager.InjectCaseSessionWithTestKey(mSessionAliceToBob, kAliceKeyId, kBobKeyId, GetAliceFabric()->GetNodeId(), - GetBobFabric()->GetNodeId(), mAliceFabricIndex, mBobAddress, - CryptoContext::SessionRole::kResponder, cats); + return mpData->mSessionManager.InjectCaseSessionWithTestKey( + mpData->mSessionAliceToBob, kAliceKeyId, kBobKeyId, GetAliceFabric()->GetNodeId(), GetBobFabric()->GetNodeId(), + mpData->mAliceFabricIndex, mpData->mBobAddress, CryptoContext::SessionRole::kResponder, cats); } CHIP_ERROR MessagingContext::CreatePASESessionCharlieToDavid() { - return mSessionManager.InjectPaseSessionWithTestKey(mSessionCharlieToDavid, kCharlieKeyId, 0xdeadbeef, kDavidKeyId, - kUndefinedFabricIndex, mDavidAddress, - CryptoContext::SessionRole::kInitiator); + return mpData->mSessionManager.InjectPaseSessionWithTestKey(mpData->mSessionCharlieToDavid, kCharlieKeyId, 0xdeadbeef, + kDavidKeyId, kUndefinedFabricIndex, mpData->mDavidAddress, + CryptoContext::SessionRole::kInitiator); } CHIP_ERROR MessagingContext::CreatePASESessionDavidToCharlie() { - return mSessionManager.InjectPaseSessionWithTestKey(mSessionDavidToCharlie, kDavidKeyId, 0xcafe, kCharlieKeyId, - kUndefinedFabricIndex, mCharlieAddress, - CryptoContext::SessionRole::kResponder); + return mpData->mSessionManager.InjectPaseSessionWithTestKey(mpData->mSessionDavidToCharlie, kDavidKeyId, 0xcafe, kCharlieKeyId, + kUndefinedFabricIndex, mpData->mCharlieAddress, + CryptoContext::SessionRole::kResponder); } CHIP_ERROR MessagingContext::CreateSessionBobToFriends() { - mSessionBobToFriends.Emplace(GetFriendsGroupId(), mBobFabricIndex); + mpData->mSessionBobToFriends.Emplace(GetFriendsGroupId(), mpData->mBobFabricIndex); return CHIP_NO_ERROR; } SessionHandle MessagingContext::GetSessionBobToAlice() { - auto sessionHandle = mSessionBobToAlice.Get(); + auto sessionHandle = mpData->mSessionBobToAlice.Get(); return std::move(sessionHandle.Value()); } SessionHandle MessagingContext::GetSessionAliceToBob() { - auto sessionHandle = mSessionAliceToBob.Get(); + auto sessionHandle = mpData->mSessionAliceToBob.Get(); return std::move(sessionHandle.Value()); } SessionHandle MessagingContext::GetSessionCharlieToDavid() { - auto sessionHandle = mSessionCharlieToDavid.Get(); + auto sessionHandle = mpData->mSessionCharlieToDavid.Get(); return std::move(sessionHandle.Value()); } SessionHandle MessagingContext::GetSessionDavidToCharlie() { - auto sessionHandle = mSessionDavidToCharlie.Get(); + auto sessionHandle = mpData->mSessionDavidToCharlie.Get(); return std::move(sessionHandle.Value()); } SessionHandle MessagingContext::GetSessionBobToFriends() { - return SessionHandle(mSessionBobToFriends.Value()); + return SessionHandle(mpData->mSessionBobToFriends.Value()); } void MessagingContext::ExpireSessionBobToAlice() { - if (mSessionBobToAlice) + if (mpData->mSessionBobToAlice) { - mSessionBobToAlice.Get().Value()->AsSecureSession()->MarkForEviction(); + mpData->mSessionBobToAlice.Get().Value()->AsSecureSession()->MarkForEviction(); } } void MessagingContext::ExpireSessionAliceToBob() { - if (mSessionAliceToBob) + if (mpData->mSessionAliceToBob) { - mSessionAliceToBob.Get().Value()->AsSecureSession()->MarkForEviction(); + mpData->mSessionAliceToBob.Get().Value()->AsSecureSession()->MarkForEviction(); } } void MessagingContext::ExpireSessionBobToFriends() { - mSessionBobToFriends.ClearValue(); + mpData->mSessionBobToFriends.ClearValue(); } Messaging::ExchangeContext * MessagingContext::NewUnauthenticatedExchangeToAlice(Messaging::ExchangeDelegate * delegate) { - return mExchangeManager.NewContext( - mSessionManager.CreateUnauthenticatedSession(mAliceAddress, GetLocalMRPConfig().ValueOr(GetDefaultMRPConfig())).Value(), + return mpData->mExchangeManager.NewContext( + mpData->mSessionManager + .CreateUnauthenticatedSession(mpData->mAliceAddress, GetLocalMRPConfig().ValueOr(GetDefaultMRPConfig())) + .Value(), delegate); } Messaging::ExchangeContext * MessagingContext::NewUnauthenticatedExchangeToBob(Messaging::ExchangeDelegate * delegate) { - return mExchangeManager.NewContext( - mSessionManager.CreateUnauthenticatedSession(mBobAddress, GetLocalMRPConfig().ValueOr(GetDefaultMRPConfig())).Value(), + return mpData->mExchangeManager.NewContext( + mpData->mSessionManager + .CreateUnauthenticatedSession(mpData->mBobAddress, GetLocalMRPConfig().ValueOr(GetDefaultMRPConfig())) + .Value(), delegate); } Messaging::ExchangeContext * MessagingContext::NewExchangeToAlice(Messaging::ExchangeDelegate * delegate, bool isInitiator) { - return mExchangeManager.NewContext(GetSessionBobToAlice(), delegate, isInitiator); + return mpData->mExchangeManager.NewContext(GetSessionBobToAlice(), delegate, isInitiator); } Messaging::ExchangeContext * MessagingContext::NewExchangeToBob(Messaging::ExchangeDelegate * delegate, bool isInitiator) { - return mExchangeManager.NewContext(GetSessionAliceToBob(), delegate, isInitiator); + return mpData->mExchangeManager.NewContext(GetSessionAliceToBob(), delegate, isInitiator); } LoopbackTransportManager * LoopbackMessagingContext::spLoopbackTransportManager = nullptr; diff --git a/src/messaging/tests/MessagingContext.h b/src/messaging/tests/MessagingContext.h index aafd93c5fcb4d6..c452b37b9c2ce1 100644 --- a/src/messaging/tests/MessagingContext.h +++ b/src/messaging/tests/MessagingContext.h @@ -93,16 +93,12 @@ class MessagingContext : public PlatformMemoryUser static constexpr System::Clock::Timeout kResponsiveIdleRetransTimeout = System::Clock::Milliseconds32(10); static constexpr System::Clock::Timeout kResponsiveActiveRetransTimeout = System::Clock::Milliseconds32(10); - MessagingContext() : - mInitialized(false), mAliceAddress(Transport::PeerAddress::UDP(GetAddress(), CHIP_PORT + 1)), - mBobAddress(Transport::PeerAddress::UDP(GetAddress(), CHIP_PORT)) - {} - // TODO Replace VerifyOrDie with Pigweed assert after transition app/tests to Pigweed. - // TODO Currently src/app/icd/server/tests is using MessagingConetext as dependency. - ~MessagingContext() { VerifyOrDie(mInitialized == false); } + MessagingContext() : mpData(new MessagingContextData()) {} + // TODO Currently src/app/icd/server/tests is using MessagingContext as dependency. + ~MessagingContext() { delete mpData; } // Whether Alice and Bob are initialized, must be called before Init - void ConfigInitializeNodes(bool initializeNodes) { mInitializeNodes = initializeNodes; } + void ConfigInitializeNodes(bool initializeNodes) { mpData->mInitializeNodes = initializeNodes; } /// Initialize the underlying layers and test suite pointer CHIP_ERROR Init(TransportMgrBase * transport, IOContext * io); @@ -129,18 +125,18 @@ class MessagingContext : public PlatformMemoryUser static const uint16_t kAliceKeyId = 2; static const uint16_t kCharlieKeyId = 3; static const uint16_t kDavidKeyId = 4; - GroupId GetFriendsGroupId() const { return mFriendsGroupId; } + GroupId GetFriendsGroupId() const { return mpData->mFriendsGroupId; } - SessionManager & GetSecureSessionManager() { return mSessionManager; } - Messaging::ExchangeManager & GetExchangeManager() { return mExchangeManager; } - secure_channel::MessageCounterManager & GetMessageCounterManager() { return mMessageCounterManager; } - FabricTable & GetFabricTable() { return mFabricTable; } - Crypto::DefaultSessionKeystore & GetSessionKeystore() { return mSessionKeystore; } + SessionManager & GetSecureSessionManager() { return mpData->mSessionManager; } + Messaging::ExchangeManager & GetExchangeManager() { return mpData->mExchangeManager; } + secure_channel::MessageCounterManager & GetMessageCounterManager() { return mpData->mMessageCounterManager; } + FabricTable & GetFabricTable() { return mpData->mFabricTable; } + Crypto::DefaultSessionKeystore & GetSessionKeystore() { return mpData->mSessionKeystore; } - FabricIndex GetAliceFabricIndex() { return mAliceFabricIndex; } - FabricIndex GetBobFabricIndex() { return mBobFabricIndex; } - const FabricInfo * GetAliceFabric() { return mFabricTable.FindFabricWithIndex(mAliceFabricIndex); } - const FabricInfo * GetBobFabric() { return mFabricTable.FindFabricWithIndex(mBobFabricIndex); } + FabricIndex GetAliceFabricIndex() { return mpData->mAliceFabricIndex; } + FabricIndex GetBobFabricIndex() { return mpData->mBobFabricIndex; } + const FabricInfo * GetAliceFabric() { return mpData->mFabricTable.FindFabricWithIndex(mpData->mAliceFabricIndex); } + const FabricInfo * GetBobFabric() { return mpData->mFabricTable.FindFabricWithIndex(mpData->mBobFabricIndex); } CHIP_ERROR CreateSessionBobToAlice(); // Creates PASE session CHIP_ERROR CreateCASESessionBobToAlice(); @@ -167,8 +163,8 @@ class MessagingContext : public PlatformMemoryUser CHIP_ERROR CreateAliceFabric(); CHIP_ERROR CreateBobFabric(); - const Transport::PeerAddress & GetAliceAddress() { return mAliceAddress; } - const Transport::PeerAddress & GetBobAddress() { return mBobAddress; } + const Transport::PeerAddress & GetAliceAddress() { return mpData->mAliceAddress; } + const Transport::PeerAddress & GetBobAddress() { return mpData->mBobAddress; } Messaging::ExchangeContext * NewUnauthenticatedExchangeToAlice(Messaging::ExchangeDelegate * delegate); Messaging::ExchangeContext * NewUnauthenticatedExchangeToBob(Messaging::ExchangeDelegate * delegate); @@ -176,35 +172,44 @@ class MessagingContext : public PlatformMemoryUser Messaging::ExchangeContext * NewExchangeToAlice(Messaging::ExchangeDelegate * delegate, bool isInitiator = true); Messaging::ExchangeContext * NewExchangeToBob(Messaging::ExchangeDelegate * delegate, bool isInitiator = true); - System::Layer & GetSystemLayer() { return mIOContext->GetSystemLayer(); } + System::Layer & GetSystemLayer() { return mpData->mIOContext->GetSystemLayer(); } private: - bool mInitializeNodes = true; - bool mInitialized; - FabricTable mFabricTable; - - SessionManager mSessionManager; - Messaging::ExchangeManager mExchangeManager; - secure_channel::MessageCounterManager mMessageCounterManager; - IOContext * mIOContext; - TransportMgrBase * mTransport; // Only needed for InitFromExisting. - chip::TestPersistentStorageDelegate mStorage; // for SessionManagerInit - chip::PersistentStorageOperationalKeystore mOpKeyStore; - chip::Credentials::PersistentStorageOpCertStore mOpCertStore; - chip::Crypto::DefaultSessionKeystore mSessionKeystore; - - FabricIndex mAliceFabricIndex = kUndefinedFabricIndex; - FabricIndex mBobFabricIndex = kUndefinedFabricIndex; - GroupId mFriendsGroupId = 0x0101; - Transport::PeerAddress mAliceAddress; - Transport::PeerAddress mBobAddress; - Transport::PeerAddress mCharlieAddress; - Transport::PeerAddress mDavidAddress; - SessionHolder mSessionAliceToBob; - SessionHolder mSessionBobToAlice; - SessionHolder mSessionCharlieToDavid; - SessionHolder mSessionDavidToCharlie; - Optional mSessionBobToFriends; + struct MessagingContextData + { + MessagingContextData() : + mInitialized(false), mAliceAddress(Transport::PeerAddress::UDP(GetAddress(), CHIP_PORT + 1)), + mBobAddress(Transport::PeerAddress::UDP(GetAddress(), CHIP_PORT)) + {} + ~MessagingContextData() { EXPECT_FALSE(mInitialized); } + + bool mInitializeNodes = true; + bool mInitialized; + FabricTable mFabricTable; + + SessionManager mSessionManager; + Messaging::ExchangeManager mExchangeManager; + secure_channel::MessageCounterManager mMessageCounterManager; + IOContext * mIOContext; + TransportMgrBase * mTransport; // Only needed for InitFromExisting. + chip::TestPersistentStorageDelegate mStorage; // for SessionManagerInit + chip::PersistentStorageOperationalKeystore mOpKeyStore; + chip::Credentials::PersistentStorageOpCertStore mOpCertStore; + chip::Crypto::DefaultSessionKeystore mSessionKeystore; + + FabricIndex mAliceFabricIndex = kUndefinedFabricIndex; + FabricIndex mBobFabricIndex = kUndefinedFabricIndex; + GroupId mFriendsGroupId = 0x0101; + Transport::PeerAddress mAliceAddress; + Transport::PeerAddress mBobAddress; + Transport::PeerAddress mCharlieAddress; + Transport::PeerAddress mDavidAddress; + SessionHolder mSessionAliceToBob; + SessionHolder mSessionBobToAlice; + SessionHolder mSessionCharlieToDavid; + SessionHolder mSessionDavidToCharlie; + Optional mSessionBobToFriends; + } * mpData; }; // LoopbackMessagingContext enriches MessagingContext with an async loopback transport diff --git a/src/messaging/tests/TestAbortExchangesForFabric.cpp b/src/messaging/tests/TestAbortExchangesForFabric.cpp index 8f8eb825553bf5..4d54a159bd27be 100644 --- a/src/messaging/tests/TestAbortExchangesForFabric.cpp +++ b/src/messaging/tests/TestAbortExchangesForFabric.cpp @@ -21,7 +21,7 @@ * one) for a fabric. */ -#include +#include #include #include @@ -48,12 +48,8 @@ using namespace chip::System; using namespace chip::System::Clock::Literals; using namespace chip::Protocols; -struct TestAbortExchangesForFabric : public chip::Test::LoopbackMessagingContext, public ::testing::Test +struct TestAbortExchangesForFabric : public chip::Test::LoopbackMessagingContext { - static void SetUpTestSuite() { chip::Test::LoopbackMessagingContext::SetUpTestSuite(); } - - static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } - void SetUp() override { #if CHIP_CRYPTO_PSA @@ -62,8 +58,6 @@ struct TestAbortExchangesForFabric : public chip::Test::LoopbackMessagingContext chip::Test::LoopbackMessagingContext::SetUp(); } - void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } - void CommonCheckAbortAllButOneExchange(bool dropResponseMessages); }; diff --git a/src/messaging/tests/TestExchange.cpp b/src/messaging/tests/TestExchange.cpp index 7c0257d3093d3f..ce8a89b3215aa7 100644 --- a/src/messaging/tests/TestExchange.cpp +++ b/src/messaging/tests/TestExchange.cpp @@ -17,7 +17,7 @@ #include #include -#include +#include #include #include @@ -43,10 +43,8 @@ using namespace chip::Messaging; class MockExchangeDelegate; -struct TestExchange : public Test::LoopbackMessagingContext, public ::testing::Test +struct TestExchange : public Test::LoopbackMessagingContext { - // TODO Add TearDown function when changing test framework to Pigweed to make it more clear how it works. - // Currently, the TearDown function is from LoopbackMessagingContext void SetUp() override { #if CHIP_CRYPTO_PSA @@ -55,12 +53,6 @@ struct TestExchange : public Test::LoopbackMessagingContext, public ::testing::T chip::Test::LoopbackMessagingContext::SetUp(); } - void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } - - static void SetUpTestSuite() { chip::Test::LoopbackMessagingContext::SetUpTestSuite(); } - - static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } - template void DoRoundTripTest(MockExchangeDelegate & delegate1, MockExchangeDelegate & delegate2, uint8_t requestMessageType, uint8_t responseMessageType, AfterRequestChecker && afterRequestChecker, diff --git a/src/messaging/tests/TestExchangeHolder.cpp b/src/messaging/tests/TestExchangeHolder.cpp index 35f0856cfede24..44e28b48c2fae3 100644 --- a/src/messaging/tests/TestExchangeHolder.cpp +++ b/src/messaging/tests/TestExchangeHolder.cpp @@ -21,7 +21,7 @@ * one) for a fabric. */ -#include +#include #include "messaging/ExchangeDelegate.h" #include "system/SystemClock.h" @@ -68,16 +68,7 @@ using namespace chip::Messaging; using namespace chip::System; using namespace chip::Protocols; -struct TestExchangeHolder : public chip::Test::LoopbackMessagingContext, public ::testing::Test -{ - static void SetUpTestSuite() { chip::Test::LoopbackMessagingContext::SetUpTestSuite(); } - - static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } - - void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } - - void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } -}; +using TestExchangeHolder = chip::Test::LoopbackMessagingContext; class MockProtocolResponder : public ExchangeDelegate, public Messaging::UnsolicitedMessageHandler { diff --git a/src/messaging/tests/TestExchangeMgr.cpp b/src/messaging/tests/TestExchangeMgr.cpp index 975078ede9bd78..f944f7792d4b21 100644 --- a/src/messaging/tests/TestExchangeMgr.cpp +++ b/src/messaging/tests/TestExchangeMgr.cpp @@ -23,7 +23,7 @@ #include #include -#include +#include #include #include @@ -47,12 +47,8 @@ using namespace chip::Inet; using namespace chip::Transport; using namespace chip::Messaging; -struct TestExchangeMgr : public chip::Test::LoopbackMessagingContext, public ::testing::Test +struct TestExchangeMgr : public chip::Test::LoopbackMessagingContext { - static void SetUpTestSuite() { chip::Test::LoopbackMessagingContext::SetUpTestSuite(); } - - static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } - void SetUp() override { #if CHIP_CRYPTO_PSA @@ -60,8 +56,6 @@ struct TestExchangeMgr : public chip::Test::LoopbackMessagingContext, public ::t #endif chip::Test::LoopbackMessagingContext::SetUp(); } - - void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } }; enum : uint8_t diff --git a/src/messaging/tests/TestMessagingLayer.cpp b/src/messaging/tests/TestMessagingLayer.cpp index 4e52cb96972ea6..eafffff1ce6753 100644 --- a/src/messaging/tests/TestMessagingLayer.cpp +++ b/src/messaging/tests/TestMessagingLayer.cpp @@ -23,7 +23,7 @@ #include #include -#include +#include #include #include @@ -47,18 +47,7 @@ using namespace chip::Messaging; using namespace chip::Protocols; using namespace chip::System::Clock::Literals; -using TestContext = Test::UDPMessagingContext; - -struct TestMessagingLayer : public chip::Test::UDPMessagingContext, public ::testing::Test -{ - static void SetUpTestSuite() { chip::Test::UDPMessagingContext::SetUpTestSuite(); } - static void TearDownTestSuite() { chip::Test::UDPMessagingContext::TearDownTestSuite(); } - - // Performs setup for each individual test in the test suite - void SetUp() override { chip::Test::UDPMessagingContext::SetUp(); } - - void TearDown() override { chip::Test::UDPMessagingContext::TearDown(); } -}; +using TestMessagingLayer = chip::Test::UDPMessagingContext; // The message timeout value in milliseconds. constexpr System::Clock::Timeout kMessageTimeout = System::Clock::Milliseconds32(100); diff --git a/src/messaging/tests/TestReliableMessageProtocol.cpp b/src/messaging/tests/TestReliableMessageProtocol.cpp index d965c172a1c010..48e26b17b791dd 100644 --- a/src/messaging/tests/TestReliableMessageProtocol.cpp +++ b/src/messaging/tests/TestReliableMessageProtocol.cpp @@ -23,7 +23,7 @@ */ #include -#include +#include #include #include @@ -60,12 +60,9 @@ using namespace chip::System::Clock::Literals; const char PAYLOAD[] = "Hello!"; -class TestReliableMessageProtocol : public chip::Test::LoopbackMessagingContext, public ::testing::Test +class TestReliableMessageProtocol : public chip::Test::LoopbackMessagingContext { public: - static void SetUpTestSuite() { chip::Test::LoopbackMessagingContext::SetUpTestSuite(); } - static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } - // Performs setup for each individual test in the test suite void SetUp() override { @@ -76,8 +73,6 @@ class TestReliableMessageProtocol : public chip::Test::LoopbackMessagingContext, GetSessionAliceToBob()->AsSecureSession()->SetRemoteSessionParameters(GetLocalMRPConfig().ValueOr(GetDefaultMRPConfig())); GetSessionBobToAlice()->AsSecureSession()->SetRemoteSessionParameters(GetLocalMRPConfig().ValueOr(GetDefaultMRPConfig())); } - - void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } }; class MockAppDelegate : public UnsolicitedMessageHandler, public ExchangeDelegate @@ -502,7 +497,6 @@ TEST_F(TestReliableMessageProtocol, CheckResendApplicationMessage) TEST_F(TestReliableMessageProtocol, CheckCloseExchangeAndResendApplicationMessage) { - chip::System::PacketBufferHandle buffer = chip::MessagePacketBuffer::NewWithData(PAYLOAD, sizeof(PAYLOAD)); EXPECT_FALSE(buffer.IsNull()); @@ -561,7 +555,6 @@ TEST_F(TestReliableMessageProtocol, CheckCloseExchangeAndResendApplicationMessag TEST_F(TestReliableMessageProtocol, CheckFailedMessageRetainOnSend) { - chip::System::PacketBufferHandle buffer = chip::MessagePacketBuffer::NewWithData(PAYLOAD, sizeof(PAYLOAD)); EXPECT_FALSE(buffer.IsNull()); @@ -854,23 +847,18 @@ TEST_F(TestReliableMessageProtocol, CheckDuplicateOldMessageClosedExchange) TEST_F(TestReliableMessageProtocol, CheckResendSessionEstablishmentMessageWithPeerExchange) { - // Making this static to reduce stack usage, as some platforms have limits on stack size. - static chip::Test::MessagingContext ctx; - CHIP_ERROR err = ctx.InitFromExisting(*this); - EXPECT_EQ(err, CHIP_NO_ERROR); - chip::System::PacketBufferHandle buffer = chip::MessagePacketBuffer::NewWithData(PAYLOAD, sizeof(PAYLOAD)); ASSERT_FALSE(buffer.IsNull()); MockSessionEstablishmentDelegate mockReceiver; - err = ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Echo::MsgType::EchoRequest, &mockReceiver); + CHIP_ERROR err = GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Echo::MsgType::EchoRequest, &mockReceiver); EXPECT_EQ(err, CHIP_NO_ERROR); MockSessionEstablishmentDelegate mockSender; - ExchangeContext * exchange = ctx.NewUnauthenticatedExchangeToAlice(&mockSender); + ExchangeContext * exchange = NewUnauthenticatedExchangeToAlice(&mockSender); ASSERT_NE(exchange, nullptr); - ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); ASSERT_NE(rm, nullptr); exchange->GetSessionHandle()->AsUnauthenticatedSession()->SetRemoteSessionParameters(ReliableMessageProtocolConfig({ @@ -907,10 +895,8 @@ TEST_F(TestReliableMessageProtocol, CheckResendSessionEstablishmentMessageWithPe EXPECT_EQ(rm->TestGetCountRetransTable(), 0); EXPECT_TRUE(mockReceiver.IsOnMessageReceivedCalled); - err = ctx.GetExchangeManager().UnregisterUnsolicitedMessageHandlerForType(Echo::MsgType::EchoRequest); + err = GetExchangeManager().UnregisterUnsolicitedMessageHandlerForType(Echo::MsgType::EchoRequest); EXPECT_EQ(err, CHIP_NO_ERROR); - - ctx.ShutdownAndRestoreExisting(*this); } TEST_F(TestReliableMessageProtocol, CheckDuplicateMessage) diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 24aaffce0dbcb4..aafda3c548fce7 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -26,7 +26,6 @@ #include #include #include -#include #include #include #include @@ -39,6 +38,7 @@ #include #include #include +#include #include #include "credentials/tests/CHIPCert_test_vectors.h" @@ -56,7 +56,7 @@ using namespace chip::Crypto; namespace chip { class TestCASESecurePairingDelegate; -class TestCASESession : public Test::LoopbackMessagingContext, public ::testing::Test +class TestCASESession : public Test::LoopbackMessagingContext { public: // Performs shared setup for all tests in the test suite @@ -70,8 +70,6 @@ class TestCASESession : public Test::LoopbackMessagingContext, public ::testing: chip::Test::LoopbackMessagingContext::SetUp(); } - virtual void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } - void ServiceEvents(); void SecurePairingHandshakeTestCommon(SessionManager & sessionManager, CASESession & pairingCommissioner, TestCASESecurePairingDelegate & delegateCommissioner); diff --git a/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp b/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp index 41b6539ecf0773..edd0bf5f3aa68d 100644 --- a/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp +++ b/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp @@ -34,8 +34,8 @@ #include #include -#include #include +#include #include @@ -64,14 +64,7 @@ class MockAppDelegate : public ExchangeDelegate int ReceiveHandlerCallCount = 0; }; -struct TestMessageCounterManager : public chip::Test::LoopbackMessagingContext, public ::testing::Test -{ - static void SetUpTestSuite() { chip::Test::LoopbackMessagingContext::SetUpTestSuite(); } - static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } - - void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } - void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } -}; +using TestMessageCounterManager = chip::Test::LoopbackMessagingContext; TEST_F(TestMessageCounterManager, MessageCounterSyncProcess) { diff --git a/src/protocols/secure_channel/tests/TestPASESession.cpp b/src/protocols/secure_channel/tests/TestPASESession.cpp index 5b3f957d51bf84..2d054821728379 100644 --- a/src/protocols/secure_channel/tests/TestPASESession.cpp +++ b/src/protocols/secure_channel/tests/TestPASESession.cpp @@ -22,7 +22,7 @@ */ #include -#include +#include #include #include @@ -84,21 +84,15 @@ constexpr Spake2pVerifierSerialized sTestSpake2p01_SerializedVerifier = { }; class TestSecurePairingDelegate; -class TestPASESession : public chip::Test::LoopbackMessagingContext, public ::testing::Test +class TestPASESession : public chip::Test::LoopbackMessagingContext { public: - // Performs shared setup for all tests in the test suite - static void SetUpTestSuite() { chip::Test::LoopbackMessagingContext::SetUpTestSuite(); } - static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } - void SetUp() override { ConfigInitializeNodes(false); chip::Test::LoopbackMessagingContext::SetUp(); } - void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } - void SecurePairingHandshakeTestCommon(SessionManager & sessionManager, PASESession & pairingCommissioner, Optional mrpCommissionerConfig, Optional mrpAccessoryConfig, diff --git a/src/transport/tests/TestSessionManagerDispatch.cpp b/src/transport/tests/TestSessionManagerDispatch.cpp index f90cb0fa2b21ac..3ef66057adfbc8 100644 --- a/src/transport/tests/TestSessionManagerDispatch.cpp +++ b/src/transport/tests/TestSessionManagerDispatch.cpp @@ -36,7 +36,7 @@ #include #include -#include +#include #include From a02c9d7a6abae77c57089c9b64f4a2afc7ef699f Mon Sep 17 00:00:00 2001 From: Jeff Feasel Date: Thu, 20 Jun 2024 18:46:35 +0000 Subject: [PATCH 03/16] Removed unneeded scope from call to parent setup/teardown --- src/app/tests/TestAclAttribute.cpp | 4 ++-- src/app/tests/TestAclEvent.cpp | 6 +++--- src/app/tests/TestEventLogging.cpp | 4 ++-- src/app/tests/TestEventLoggingNoUTCTime.cpp | 8 ++++---- src/app/tests/TestFabricScopedEventLogging.cpp | 4 ++-- src/app/tests/TestReadInteraction.cpp | 8 ++++---- src/app/tests/TestWriteInteraction.cpp | 4 ++-- src/controller/tests/TestEventChunking.cpp | 5 ++--- src/controller/tests/TestEventNumberCaching.cpp | 5 ++--- src/controller/tests/TestReadChunking.cpp | 1 - src/controller/tests/TestServerCommandDispatch.cpp | 1 - src/controller/tests/TestWriteChunking.cpp | 1 - src/controller/tests/data_model/TestCommands.cpp | 1 - src/controller/tests/data_model/TestRead.cpp | 1 - src/controller/tests/data_model/TestWrite.cpp | 1 - 15 files changed, 23 insertions(+), 31 deletions(-) diff --git a/src/app/tests/TestAclAttribute.cpp b/src/app/tests/TestAclAttribute.cpp index 9395603218de69..fac82e484d7450 100644 --- a/src/app/tests/TestAclAttribute.cpp +++ b/src/app/tests/TestAclAttribute.cpp @@ -109,12 +109,12 @@ class MockInteractionModelApp : public chip::app::ReadClient::Callback namespace chip { namespace app { -class TestAclAttribute : public chip::Test::AppContext +class TestAclAttribute : public Test::AppContext { public: void SetUp() override { - chip::Test::AppContext::SetUp(); + AppContext::SetUp(); Access::GetAccessControl().Finish(); Access::GetAccessControl().Init(GetTestAccessControlDelegate(), gDeviceTypeResolver); diff --git a/src/app/tests/TestAclEvent.cpp b/src/app/tests/TestAclEvent.cpp index 32ed5fbe346f8d..c216e8d1f9565d 100644 --- a/src/app/tests/TestAclEvent.cpp +++ b/src/app/tests/TestAclEvent.cpp @@ -172,7 +172,7 @@ class MockInteractionModelApp : public chip::app::ReadClient::Callback namespace chip { namespace app { -class TestAclEvent : public chip::Test::AppContext +class TestAclEvent : public Test::AppContext { public: // Performs setup for each individual test in the test suite @@ -184,7 +184,7 @@ class TestAclEvent : public chip::Test::AppContext { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - chip::Test::AppContext::SetUp(); + AppContext::SetUp(); ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), @@ -198,7 +198,7 @@ class TestAclEvent : public chip::Test::AppContext void TearDown() override { chip::app::EventManagement::DestroyEventManagement(); - chip::Test::AppContext::TearDown(); + AppContext::TearDown(); } private: diff --git a/src/app/tests/TestEventLogging.cpp b/src/app/tests/TestEventLogging.cpp index 93e3b905670de3..cbc42d9060e435 100644 --- a/src/app/tests/TestEventLogging.cpp +++ b/src/app/tests/TestEventLogging.cpp @@ -65,7 +65,7 @@ class TestEventLogging : public chip::Test::AppContext { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - chip::Test::AppContext::SetUp(); + AppContext::SetUp(); ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); @@ -75,7 +75,7 @@ class TestEventLogging : public chip::Test::AppContext void TearDown() override { chip::app::EventManagement::DestroyEventManagement(); - chip::Test::AppContext::TearDown(); + AppContext::TearDown(); } private: diff --git a/src/app/tests/TestEventLoggingNoUTCTime.cpp b/src/app/tests/TestEventLoggingNoUTCTime.cpp index 80176a58c8be54..f3cfc0e8a30ddc 100644 --- a/src/app/tests/TestEventLoggingNoUTCTime.cpp +++ b/src/app/tests/TestEventLoggingNoUTCTime.cpp @@ -79,7 +79,7 @@ class TestEventLoggingNoUTCTime : public chip::Test::AppContext // Performs shared setup for all tests in the test suite static void SetUpTestSuite() { - chip::Test::AppContext::SetUpTestSuite(); + AppContext::SetUpTestSuite(); sClock.Emplace(chip::System::SystemClock()); } @@ -87,7 +87,7 @@ class TestEventLoggingNoUTCTime : public chip::Test::AppContext static void TearDownTestSuite() { sClock.ClearValue(); - chip::Test::AppContext::TearDownTestSuite(); + AppContext::TearDownTestSuite(); } // Performs setup for each individual test in the test suite @@ -99,7 +99,7 @@ class TestEventLoggingNoUTCTime : public chip::Test::AppContext { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - chip::Test::AppContext::SetUp(); + AppContext::SetUp(); ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), gCircularEventBuffer, logStorageResources, &mEventCounter); @@ -109,7 +109,7 @@ class TestEventLoggingNoUTCTime : public chip::Test::AppContext void TearDown() override { chip::app::EventManagement::DestroyEventManagement(); - chip::Test::AppContext::TearDown(); + AppContext::TearDown(); } private: diff --git a/src/app/tests/TestFabricScopedEventLogging.cpp b/src/app/tests/TestFabricScopedEventLogging.cpp index 98132a1d990479..d825626688f90b 100644 --- a/src/app/tests/TestFabricScopedEventLogging.cpp +++ b/src/app/tests/TestFabricScopedEventLogging.cpp @@ -65,7 +65,7 @@ class TestFabricScopedEventLogging : public chip::Test::AppContext { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - chip::Test::AppContext::SetUp(); + AppContext::SetUp(); ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), @@ -76,7 +76,7 @@ class TestFabricScopedEventLogging : public chip::Test::AppContext void TearDown() override { chip::app::EventManagement::DestroyEventManagement(); - chip::Test::AppContext::TearDown(); + AppContext::TearDown(); } private: diff --git a/src/app/tests/TestReadInteraction.cpp b/src/app/tests/TestReadInteraction.cpp index ab7440b6bec767..81c66e45f40999 100644 --- a/src/app/tests/TestReadInteraction.cpp +++ b/src/app/tests/TestReadInteraction.cpp @@ -236,7 +236,7 @@ class TestReadInteraction : public chip::Test::AppContext public: static void SetUpTestSuite() { - chip::Test::AppContext::SetUpTestSuite(); + AppContext::SetUpTestSuite(); gRealClock = &chip::System::SystemClock(); chip::System::Clock::Internal::SetSystemClockForTesting(&gMockClock); @@ -255,7 +255,7 @@ class TestReadInteraction : public chip::Test::AppContext { chip::System::Clock::Internal::SetSystemClockForTesting(gRealClock); - chip::Test::AppContext::TearDownTestSuite(); + AppContext::TearDownTestSuite(); } void SetUp() @@ -266,7 +266,7 @@ class TestReadInteraction : public chip::Test::AppContext { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - chip::Test::AppContext::SetUp(); + AppContext::SetUp(); ASSERT_EQ(mEventCounter.Init(0), CHIP_NO_ERROR); chip::app::EventManagement::CreateEventManagement(&GetExchangeManager(), ArraySize(logStorageResources), @@ -275,7 +275,7 @@ class TestReadInteraction : public chip::Test::AppContext void TearDown() { chip::app::EventManagement::DestroyEventManagement(); - chip::Test::AppContext::TearDown(); + AppContext::TearDown(); } void TestReadClient(); diff --git a/src/app/tests/TestWriteInteraction.cpp b/src/app/tests/TestWriteInteraction.cpp index 896f29870b28ab..7b359505ef1501 100644 --- a/src/app/tests/TestWriteInteraction.cpp +++ b/src/app/tests/TestWriteInteraction.cpp @@ -58,7 +58,7 @@ class TestWriteInteraction : public chip::Test::AppContext public: void SetUp() override { - chip::Test::AppContext::SetUp(); + AppContext::SetUp(); gTestStorage.ClearStorage(); gGroupsProvider.SetStorageDelegate(&gTestStorage); @@ -78,7 +78,7 @@ class TestWriteInteraction : public chip::Test::AppContext { provider->Finish(); } - chip::Test::AppContext::TearDown(); + AppContext::TearDown(); } void TestWriteClient(); diff --git a/src/controller/tests/TestEventChunking.cpp b/src/controller/tests/TestEventChunking.cpp index 641c5b4470400f..fc71da8662596d 100644 --- a/src/controller/tests/TestEventChunking.cpp +++ b/src/controller/tests/TestEventChunking.cpp @@ -41,7 +41,6 @@ #include #include #include -#include using namespace chip; using namespace chip::app; @@ -79,7 +78,7 @@ class TestEventChunking : public chip::Test::AppContext { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - chip::Test::AppContext::SetUp(); + AppContext::SetUp(); CHIP_ERROR err = CHIP_NO_ERROR; // TODO: use ASSERT_EQ, once transition to pw_unit_test is complete @@ -93,7 +92,7 @@ class TestEventChunking : public chip::Test::AppContext void TearDown() { chip::app::EventManagement::DestroyEventManagement(); - chip::Test::AppContext::TearDown(); + AppContext::TearDown(); } private: diff --git a/src/controller/tests/TestEventNumberCaching.cpp b/src/controller/tests/TestEventNumberCaching.cpp index f44f7ed5af78ad..344d8a26ed2653 100644 --- a/src/controller/tests/TestEventNumberCaching.cpp +++ b/src/controller/tests/TestEventNumberCaching.cpp @@ -33,7 +33,6 @@ #include #include #include -#include using namespace chip; using namespace chip::app; @@ -65,7 +64,7 @@ class TestEventNumberCaching : public chip::Test::AppContext { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical }, }; - chip::Test::AppContext::SetUp(); + AppContext::SetUp(); CHIP_ERROR err = CHIP_NO_ERROR; // TODO: use ASSERT_EQ, once transition to pw_unit_test is complete @@ -79,7 +78,7 @@ class TestEventNumberCaching : public chip::Test::AppContext void TearDown() { chip::app::EventManagement::DestroyEventManagement(); - chip::Test::AppContext::TearDown(); + AppContext::TearDown(); } private: diff --git a/src/controller/tests/TestReadChunking.cpp b/src/controller/tests/TestReadChunking.cpp index 97acb81bd11d20..6a7e349436a865 100644 --- a/src/controller/tests/TestReadChunking.cpp +++ b/src/controller/tests/TestReadChunking.cpp @@ -44,7 +44,6 @@ #include #include #include -#include using namespace chip; using namespace chip::app; diff --git a/src/controller/tests/TestServerCommandDispatch.cpp b/src/controller/tests/TestServerCommandDispatch.cpp index 1536d0ccc4c2d5..e1a266c5f99d66 100644 --- a/src/controller/tests/TestServerCommandDispatch.cpp +++ b/src/controller/tests/TestServerCommandDispatch.cpp @@ -36,7 +36,6 @@ #include #include #include -#include using namespace chip; using namespace chip::app; diff --git a/src/controller/tests/TestWriteChunking.cpp b/src/controller/tests/TestWriteChunking.cpp index 5059b8eb40f2ac..dcb4b36044c985 100644 --- a/src/controller/tests/TestWriteChunking.cpp +++ b/src/controller/tests/TestWriteChunking.cpp @@ -36,7 +36,6 @@ #include #include #include -#include using namespace chip; using namespace chip::app; diff --git a/src/controller/tests/data_model/TestCommands.cpp b/src/controller/tests/data_model/TestCommands.cpp index 9ebb4d39a4c524..1a5aecb7badcef 100644 --- a/src/controller/tests/data_model/TestCommands.cpp +++ b/src/controller/tests/data_model/TestCommands.cpp @@ -35,7 +35,6 @@ #include #include #include -#include #include #include diff --git a/src/controller/tests/data_model/TestRead.cpp b/src/controller/tests/data_model/TestRead.cpp index 7e31d255ae2390..9b6cb033a891d1 100644 --- a/src/controller/tests/data_model/TestRead.cpp +++ b/src/controller/tests/data_model/TestRead.cpp @@ -31,7 +31,6 @@ #include #include #include -#include #include using namespace chip; diff --git a/src/controller/tests/data_model/TestWrite.cpp b/src/controller/tests/data_model/TestWrite.cpp index 23c25ff2b8fc99..f7eb94bc78e420 100644 --- a/src/controller/tests/data_model/TestWrite.cpp +++ b/src/controller/tests/data_model/TestWrite.cpp @@ -27,7 +27,6 @@ #include #include #include -#include #include using namespace chip; From 302bf20965afe8d5f87102bd503ecfb77c1a4a71 Mon Sep 17 00:00:00 2001 From: Jeff Feasel Date: Fri, 21 Jun 2024 13:04:40 +0000 Subject: [PATCH 04/16] Made some helper functions into class methods. --- src/controller/tests/TestReadChunking.cpp | 95 +++++++++++--------- src/controller/tests/data_model/TestRead.cpp | 18 ++-- 2 files changed, 62 insertions(+), 51 deletions(-) diff --git a/src/controller/tests/TestReadChunking.cpp b/src/controller/tests/TestReadChunking.cpp index 6a7e349436a865..b64e715e013660 100644 --- a/src/controller/tests/TestReadChunking.cpp +++ b/src/controller/tests/TestReadChunking.cpp @@ -70,8 +70,6 @@ constexpr AttributeId kTestBadAttribute = constexpr int kListAttributeItems = 5; -using TestReadChunking = chip::Test::AppContext; - //clang-format off DECLARE_DYNAMIC_ATTRIBUTE_LIST_BEGIN(testClusterAttrs) DECLARE_DYNAMIC_ATTRIBUTE(0x00000001, INT8U, 1, 0), DECLARE_DYNAMIC_ATTRIBUTE(0x00000002, INT8U, 1, 0), @@ -456,6 +454,15 @@ void TestMutableReadCallback::OnAttributeData(const app::ConcreteDataAttributePa // Ignore all other attributes, we don't care above the global attributes. } +class TestReadChunking : public chip::Test::AppContext +{ +protected: + struct Instruction; + void DoTest(TestMutableReadCallback * callback, Instruction instruction); + void DriveIOUntilSubscriptionEstablished(TestMutableReadCallback * callback); + void DriveIOUntilEndOfReport(TestMutableReadCallback * callback); +}; + /* * This validates all the various corner cases encountered during chunking by * artificially reducing the size of a packet buffer used to encode attribute data @@ -809,57 +816,59 @@ enum AttrIds using AttributeWithValue = std::pair; using AttributesList = std::vector; -struct Instruction +void CheckValues(TestMutableReadCallback * callback, std::vector expectedValues = {}) +{ + for (const auto & vals : expectedValues) + { + EXPECT_EQ(callback->mValues[vals.first], vals.second); + } +} + +void ExpectSameDataVersions(TestMutableReadCallback * callback, AttributesList attrList) +{ + if (attrList.size() == 0) + { + return; + } + DataVersion expectedVersion = callback->mDataVersions[attrList[0]]; + for (const auto & attr : attrList) + { + EXPECT_EQ(callback->mDataVersions[attr], expectedVersion); + } +} + +}; // namespace TestSetDirtyBetweenChunksUtil + +struct TestReadChunking::Instruction { // The maximum number of attributes should be iterated in a single report chunk. uint32_t chunksize; // A list of functions that will be executed before driving the main loop. std::vector> preworks; // A list of pair for attributes and their expected values in the report. - std::vector expectedValues; + std::vector expectedValues; // A list of list of various attributes which should have the same data version in the report. - std::vector attributesWithSameDataVersion; + std::vector attributesWithSameDataVersion; }; -void DriveIOUntilSubscriptionEstablished(TestReadChunking * pContext, TestMutableReadCallback * callback) +void TestReadChunking::DriveIOUntilSubscriptionEstablished(TestMutableReadCallback * callback) { callback->mOnReportEnd = false; - pContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return callback->mOnSubscriptionEstablished; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return callback->mOnSubscriptionEstablished; }); EXPECT_TRUE(callback->mOnReportEnd); EXPECT_TRUE(callback->mOnSubscriptionEstablished); callback->mActionOn.clear(); } -void DriveIOUntilEndOfReport(TestReadChunking * pContext, TestMutableReadCallback * callback) +void TestReadChunking::DriveIOUntilEndOfReport(TestMutableReadCallback * callback) { callback->mOnReportEnd = false; - pContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return callback->mOnReportEnd; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return callback->mOnReportEnd; }); EXPECT_TRUE(callback->mOnReportEnd); callback->mActionOn.clear(); } -void CheckValues(TestMutableReadCallback * callback, std::vector expectedValues = {}) -{ - for (const auto & vals : expectedValues) - { - EXPECT_EQ(callback->mValues[vals.first], vals.second); - } -} - -void ExpectSameDataVersions(TestMutableReadCallback * callback, AttributesList attrList) -{ - if (attrList.size() == 0) - { - return; - } - DataVersion expectedVersion = callback->mDataVersions[attrList[0]]; - for (const auto & attr : attrList) - { - EXPECT_EQ(callback->mDataVersions[attr], expectedVersion); - } -} - -void DoTest(TestReadChunking * pContext, TestMutableReadCallback * callback, Instruction instruction) +void TestReadChunking::DoTest(TestMutableReadCallback * callback, Instruction instruction) { app::InteractionModelEngine::GetInstance()->GetReportingEngine().SetMaxAttributesPerChunk(instruction.chunksize); @@ -868,18 +877,16 @@ void DoTest(TestReadChunking * pContext, TestMutableReadCallback * callback, Ins act(); } - DriveIOUntilEndOfReport(pContext, callback); + DriveIOUntilEndOfReport(callback); - CheckValues(callback, instruction.expectedValues); + TestSetDirtyBetweenChunksUtil::CheckValues(callback, instruction.expectedValues); for (const auto & attrList : instruction.attributesWithSameDataVersion) { - ExpectSameDataVersions(callback, attrList); + TestSetDirtyBetweenChunksUtil::ExpectSameDataVersions(callback, attrList); } } -}; // namespace TestSetDirtyBetweenChunksUtil - TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) { using namespace TestSetDirtyBetweenChunksUtil; @@ -929,11 +936,11 @@ TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) // We are expected to miss attributes on kTestEndpointId during initial reports. ChipLogProgress(DataManagement, "Case 1-1: Set dirty during priming report."); readCallback.mActionOn[AttrOnEp5] = TouchAttrOp(AttrOnEp1); - DriveIOUntilSubscriptionEstablished(this, &readCallback); + DriveIOUntilSubscriptionEstablished(&readCallback); CheckValues(&readCallback, { { AttrOnEp1, 1 } }); ChipLogProgress(DataManagement, "Case 1-2: Check for attributes missed last report."); - DoTest(this, &readCallback, Instruction{ .chunksize = 2, .expectedValues = { { AttrOnEp1, 2 } } }); + DoTest(&readCallback, Instruction{ .chunksize = 2, .expectedValues = { { AttrOnEp1, 2 } } }); } // CASE 2 -- Set dirty during chunked report, the attribute is already dirty. @@ -941,7 +948,7 @@ TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) ChipLogProgress(DataManagement, "Case 2: Set dirty during chunked report by wildcard path."); readCallback.mActionOn[AttrOnEp5] = WriteAttrOp(AttrOnEp5, 3); DoTest( - this, &readCallback, + &readCallback, Instruction{ .chunksize = 2, .preworks = { WriteAttrOp(AttrOnEp5, 2), WriteAttrOp(AttrOnEp5, 2), WriteAttrOp(AttrOnEp5, 2) }, @@ -955,7 +962,7 @@ TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) "Case 3-1: Set dirty during chunked report by wildcard path -- new dirty attribute."); readCallback.mActionOn[AttrOnEp5] = WriteAttrOp(AttrOnEp5, 4); DoTest( - this, &readCallback, + &readCallback, Instruction{ .chunksize = 1, .preworks = { WriteAttrOp(AttrOnEp5, 4), WriteAttrOp(AttrOnEp5, 4) }, .expectedValues = { { AttrOnEp5, 4 }, { AttrOnEp5, 4 }, { AttrOnEp5, 4 } }, @@ -966,7 +973,7 @@ TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) app::InteractionModelEngine::GetInstance()->GetReportingEngine().SetMaxAttributesPerChunk(1); readCallback.mActionOn[AttrOnEp5] = WriteAttrOp(AttrOnEp5, 5); DoTest( - this, &readCallback, + &readCallback, Instruction{ .chunksize = 1, .preworks = { WriteAttrOp(AttrOnEp5, 5), WriteAttrOp(AttrOnEp5, 5) }, .expectedValues = { { AttrOnEp5, 5 }, { AttrOnEp5, 5 }, { AttrOnEp5, 5 } }, @@ -1001,13 +1008,13 @@ TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) EXPECT_EQ(readClient.SendRequest(readParams), CHIP_NO_ERROR); - DriveIOUntilSubscriptionEstablished(this, &readCallback); + DriveIOUntilSubscriptionEstablished(&readCallback); // Note, although the two attributes comes from the same cluster, they are generated by different interested paths. // In this case, we won't reset the path iterator. ChipLogProgress(DataManagement, "Case 1-1: Test set dirty during reports generated by concrete paths."); readCallback.mActionOn[AttrOnEp5] = WriteAttrOp(AttrOnEp5, 4); - DoTest(this, &readCallback, + DoTest(&readCallback, Instruction{ .chunksize = 1, .preworks = { WriteAttrOp(AttrOnEp5, 3), WriteAttrOp(AttrOnEp5, 3), WriteAttrOp(AttrOnEp5, 3) }, @@ -1015,7 +1022,7 @@ TEST_F(TestReadChunking, TestSetDirtyBetweenChunks) // The attribute failed to catch last report will be picked by this report. ChipLogProgress(DataManagement, "Case 1-2: Check for attributes missed last report."); - DoTest(this, &readCallback, { .chunksize = 1, .expectedValues = { { AttrOnEp5, 4 } } }); + DoTest(&readCallback, { .chunksize = 1, .expectedValues = { { AttrOnEp5, 4 } } }); } } diff --git a/src/controller/tests/data_model/TestRead.cpp b/src/controller/tests/data_model/TestRead.cpp index 9b6cb033a891d1..1a561d738ff323 100644 --- a/src/controller/tests/data_model/TestRead.cpp +++ b/src/controller/tests/data_model/TestRead.cpp @@ -294,6 +294,11 @@ class TestRead : public chip::Test::AppContext, public app::ReadHandler::Applica bool mEmitSubscriptionError = false; int32_t mNumActiveSubscriptions = 0; bool mAlterSubscriptionIntervals = false; + +protected: + struct TestReadHandler_ParallelReads_TestCase_Parameters; + void TestReadHandler_ParallelReads_TestCase(const TestReadHandler_ParallelReads_TestCase_Parameters & params, + std::function body); }; uint16_t TestRead::mMaxInterval = 66; @@ -3629,16 +3634,15 @@ TEST_F(TestRead, TestReadHandler_KillOldestSubscriptions) app::InteractionModelEngine::GetInstance()->SetPathPoolCapacityForSubscriptions(-1); } -struct TestReadHandler_ParallelReads_TestCase_Parameters +struct TestRead::TestReadHandler_ParallelReads_TestCase_Parameters { int ReadHandlerCapacity = -1; int PathPoolCapacity = -1; int MaxFabrics = -1; }; -static void TestReadHandler_ParallelReads_TestCase(TestRead * apContext, - const TestReadHandler_ParallelReads_TestCase_Parameters & params, - std::function body) +void TestRead::TestReadHandler_ParallelReads_TestCase(const TestReadHandler_ParallelReads_TestCase_Parameters & params, + std::function body) { app::InteractionModelEngine::GetInstance()->SetForceHandlerQuota(true); app::InteractionModelEngine::GetInstance()->SetHandlerCapacityForReads(params.ReadHandlerCapacity); @@ -3649,10 +3653,10 @@ static void TestReadHandler_ParallelReads_TestCase(TestRead * apContext, // Clean up app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - apContext->DrainAndServiceIO(); + DrainAndServiceIO(); // Sanity check - EXPECT_EQ(apContext->GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->SetForceHandlerQuota(false); app::InteractionModelEngine::GetInstance()->SetHandlerCapacityForReads(-1); @@ -3673,7 +3677,7 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) app::InteractionModelEngine::GetInstance()->RegisterReadHandlerAppCallback(this); auto TestCase = [&](const TestReadHandler_ParallelReads_TestCase_Parameters & params, std::function body) { - TestReadHandler_ParallelReads_TestCase(this, params, body); + TestReadHandler_ParallelReads_TestCase(params, body); }; // Case 1.1: 2 reads used up the path pool (but not the ReadHandler pool), and one incoming oversized read request => From 1c12067b441b2e50df35c09ba07ee66207a87fd0 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Fri, 21 Jun 2024 13:06:00 +0000 Subject: [PATCH 05/16] Restyled by prettier-markdown --- docs/testing/unit_testing.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/testing/unit_testing.md b/docs/testing/unit_testing.md index 568bfbf9af3326..243e35d9b380c9 100644 --- a/docs/testing/unit_testing.md +++ b/docs/testing/unit_testing.md @@ -218,8 +218,8 @@ your overriding function make sure to check `HasFailure()` and return if the parent function failed. If you don't override any of the setup/teardown functions, you can simply make a -type alias: `using YourTestContext = Test::AppContext;` instead of defining -your own text context class. +type alias: `using YourTestContext = Test::AppContext;` instead of defining your +own text context class. ## Best practices From b5c630fe31a6e367b5d9f4d4ef15f4c87a8f7beb Mon Sep 17 00:00:00 2001 From: Jeff Feasel Date: Mon, 1 Jul 2024 10:44:01 +0000 Subject: [PATCH 06/16] Reverted TestICDManager back to using LoopbackMessagingContext --- src/app/icd/server/tests/BUILD.gn | 2 -- src/app/icd/server/tests/TestICDManager.cpp | 16 ++++++++++------ 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/app/icd/server/tests/BUILD.gn b/src/app/icd/server/tests/BUILD.gn index a5d0fb83090f5f..e96954a97dde58 100644 --- a/src/app/icd/server/tests/BUILD.gn +++ b/src/app/icd/server/tests/BUILD.gn @@ -31,8 +31,6 @@ chip_test_suite("tests") { public_deps = [ "${chip_root}/src/app/icd/server:manager", "${chip_root}/src/app/icd/server:monitoring-table", - "${chip_root}/src/app/tests:helpers", - "${chip_root}/src/controller/data_model", "${chip_root}/src/lib/support:test_utils", "${chip_root}/src/lib/support:testing", "${chip_root}/src/messaging/tests:helpers", diff --git a/src/app/icd/server/tests/TestICDManager.cpp b/src/app/icd/server/tests/TestICDManager.cpp index b2c5918ba4ee04..ee13264001ad9d 100644 --- a/src/app/icd/server/tests/TestICDManager.cpp +++ b/src/app/icd/server/tests/TestICDManager.cpp @@ -25,12 +25,12 @@ #include #include #include -#include #include #include #include #include #include +#include #include using namespace chip; @@ -131,7 +131,7 @@ System::Clock::ClockBase * pRealClock = nullptr; namespace chip { namespace app { -class TestICDManager : public Test::AppContext +class TestICDManager : public Test::LoopbackMessagingContext { public: /* @@ -156,9 +156,11 @@ class TestICDManager : public Test::AppContext ASSERT_NE(pMockClock, nullptr); } - AppContext::SetUpTestSuite(); + LoopbackMessagingContext::SetUpTestSuite(); VerifyOrReturn(!HasFailure()); + ASSERT_EQ(chip::DeviceLayer::PlatformMgr().InitChipStack(), CHIP_NO_ERROR); + DeviceLayer::SetSystemLayerForTesting(&GetSystemLayer()); pRealClock = &SystemClock(); Clock::Internal::SetSystemClockForTesting(pMockClock); @@ -170,7 +172,9 @@ class TestICDManager : public Test::AppContext Clock::Internal::SetSystemClockForTesting(pRealClock); DeviceLayer::SetSystemLayerForTesting(nullptr); - AppContext::TearDownTestSuite(); + DeviceLayer::PlatformMgr().Shutdown(); + + LoopbackMessagingContext::TearDownTestSuite(); if (pMockClock != nullptr) { @@ -184,7 +188,7 @@ class TestICDManager : public Test::AppContext // Performs setup for each individual test in the test suite void SetUp() override { - AppContext::SetUp(); + LoopbackMessagingContext::SetUp(); VerifyOrReturn(!HasFailure()); mICDStateObserver.ResetAll(); @@ -196,7 +200,7 @@ class TestICDManager : public Test::AppContext void TearDown() override { mICDManager.Shutdown(); - AppContext::TearDown(); + LoopbackMessagingContext::TearDown(); } TestSessionKeystoreImpl mKeystore; From 2d7a896dd2414b0c6b51da6596d30e03b215e51b Mon Sep 17 00:00:00 2001 From: Jeff Feasel Date: Wed, 3 Jul 2024 14:24:31 +0000 Subject: [PATCH 07/16] fixing merge conflicts --- src/app/icd/server/tests/TestICDManager.cpp | 1 + src/messaging/tests/MessagingContext.h | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/app/icd/server/tests/TestICDManager.cpp b/src/app/icd/server/tests/TestICDManager.cpp index ee13264001ad9d..c9baa0dd7ce559 100644 --- a/src/app/icd/server/tests/TestICDManager.cpp +++ b/src/app/icd/server/tests/TestICDManager.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include diff --git a/src/messaging/tests/MessagingContext.h b/src/messaging/tests/MessagingContext.h index c452b37b9c2ce1..99959debd58dac 100644 --- a/src/messaging/tests/MessagingContext.h +++ b/src/messaging/tests/MessagingContext.h @@ -179,7 +179,7 @@ class MessagingContext : public PlatformMemoryUser { MessagingContextData() : mInitialized(false), mAliceAddress(Transport::PeerAddress::UDP(GetAddress(), CHIP_PORT + 1)), - mBobAddress(Transport::PeerAddress::UDP(GetAddress(), CHIP_PORT)) + mBobAddress(LoopbackTransport::LoopbackPeer(mAliceAddress)) {} ~MessagingContextData() { EXPECT_FALSE(mInitialized); } From 8f75457f0e97370a2e326334fa7568e7fb4e5dc7 Mon Sep 17 00:00:00 2001 From: Jeff Feasel Date: Wed, 3 Jul 2024 14:47:13 +0000 Subject: [PATCH 08/16] fixing merge conflicts --- .../tests/data_model/TestCommands.cpp | 171 +---- src/controller/tests/data_model/TestRead.cpp | 602 ++++++++---------- src/controller/tests/data_model/TestWrite.cpp | 196 +----- 3 files changed, 284 insertions(+), 685 deletions(-) diff --git a/src/controller/tests/data_model/TestCommands.cpp b/src/controller/tests/data_model/TestCommands.cpp index 1a5aecb7badcef..9a6d10916dc88b 100644 --- a/src/controller/tests/data_model/TestCommands.cpp +++ b/src/controller/tests/data_model/TestCommands.cpp @@ -22,12 +22,15 @@ * */ +#include #include -#include "app/data-model/NullObject.h" +#include "DataModelFixtures.h" + #include #include #include +#include #include #include #include @@ -35,151 +38,19 @@ #include #include #include +#include #include #include using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; +using namespace chip::app::DataModelTests; using namespace chip::Protocols; -namespace { -chip::ClusterStatus kTestSuccessClusterStatus = 1; -chip::ClusterStatus kTestFailureClusterStatus = 2; - -constexpr EndpointId kTestEndpointId = 1; - -enum ResponseDirective -{ - kSendDataResponse, - kSendSuccessStatusCode, - kSendMultipleSuccessStatusCodes, - kSendError, - kSendMultipleErrors, - kSendSuccessStatusCodeWithClusterStatus, - kSendErrorWithClusterStatus, - kAsync, -}; - -ResponseDirective responseDirective; -CommandHandler::Handle asyncHandle; - -} // namespace - -namespace chip { -namespace app { - -void DispatchSingleClusterCommand(const ConcreteCommandPath & aCommandPath, chip::TLV::TLVReader & aReader, - CommandHandler * apCommandObj) -{ - ChipLogDetail(Controller, "Received Cluster Command: Endpoint=%x Cluster=" ChipLogFormatMEI " Command=" ChipLogFormatMEI, - aCommandPath.mEndpointId, ChipLogValueMEI(aCommandPath.mClusterId), ChipLogValueMEI(aCommandPath.mCommandId)); - - if (aCommandPath.mClusterId == Clusters::UnitTesting::Id && - aCommandPath.mCommandId == Clusters::UnitTesting::Commands::TestSimpleArgumentRequest::Type::GetCommandId()) - { - Clusters::UnitTesting::Commands::TestSimpleArgumentRequest::DecodableType dataRequest; - - if (DataModel::Decode(aReader, dataRequest) != CHIP_NO_ERROR) - { - apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::Failure, "Unable to decode the request"); - return; - } - - if (responseDirective == kSendDataResponse) - { - Clusters::UnitTesting::Commands::TestStructArrayArgumentResponse::Type dataResponse; - Clusters::UnitTesting::Structs::NestedStructList::Type nestedStructList[4]; - - uint8_t i = 0; - for (auto & item : nestedStructList) - { - item.a = i; - item.b = false; - item.c.a = i; - item.c.b = true; - i++; - } - - dataResponse.arg1 = nestedStructList; - dataResponse.arg6 = true; - - apCommandObj->AddResponse(aCommandPath, dataResponse); - } - else if (responseDirective == kSendSuccessStatusCode) - { - apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::Success); - } - else if (responseDirective == kSendMultipleSuccessStatusCodes) - { - apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::Success, - "No error but testing status success case"); - - // TODO: Right now all but the first AddStatus call fail, so this - // test is not really testing what it should. - for (size_t i = 0; i < 3; ++i) - { - (void) apCommandObj->FallibleAddStatus(aCommandPath, Protocols::InteractionModel::Status::Success, - "No error but testing status success case"); - } - // And one failure on the end. - (void) apCommandObj->FallibleAddStatus(aCommandPath, Protocols::InteractionModel::Status::Failure); - } - else if (responseDirective == kSendError) - { - apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::Failure); - } - else if (responseDirective == kSendMultipleErrors) - { - apCommandObj->AddStatus(aCommandPath, Protocols::InteractionModel::Status::Failure); - - // TODO: Right now all but the first AddStatus call fail, so this - // test is not really testing what it should. - for (size_t i = 0; i < 3; ++i) - { - (void) apCommandObj->FallibleAddStatus(aCommandPath, Protocols::InteractionModel::Status::Failure); - } - } - else if (responseDirective == kSendSuccessStatusCodeWithClusterStatus) - { - apCommandObj->AddStatus( - aCommandPath, Protocols::InteractionModel::ClusterStatusCode::ClusterSpecificSuccess(kTestSuccessClusterStatus)); - } - else if (responseDirective == kSendErrorWithClusterStatus) - { - apCommandObj->AddStatus( - aCommandPath, Protocols::InteractionModel::ClusterStatusCode::ClusterSpecificFailure(kTestFailureClusterStatus)); - } - else if (responseDirective == kAsync) - { - asyncHandle = apCommandObj; - } - } -} - -InteractionModel::Status ServerClusterCommandExists(const ConcreteCommandPath & aCommandPath) -{ - // Mock cluster catalog, only support commands on one cluster on one endpoint. - using InteractionModel::Status; - - if (aCommandPath.mEndpointId != kTestEndpointId) - { - return Status::UnsupportedEndpoint; - } - - if (aCommandPath.mClusterId != Clusters::UnitTesting::Id) - { - return Status::UnsupportedCluster; - } - - return Status::Success; -} -} // namespace app -} // namespace chip - namespace { -using TestCommands = chip::Test::AppContext; +using TestCommands = chip::Test::AppContext TEST_F(TestCommands, TestDataResponse) { @@ -226,7 +97,7 @@ TEST_F(TestCommands, TestDataResponse) // not safe to do so. auto onFailureCb = [&onFailureWasCalled](CHIP_ERROR aError) { onFailureWasCalled = true; }; - responseDirective = kSendDataResponse; + ScopedChange directive(gCommandResponseDirective, CommandResponseDirective::kSendDataResponse); chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); @@ -264,7 +135,7 @@ TEST_F(TestCommands, TestSuccessNoDataResponse) // not safe to do so. auto onFailureCb = [&onFailureWasCalled](CHIP_ERROR aError) { onFailureWasCalled = true; }; - responseDirective = kSendSuccessStatusCode; + ScopedChange directive(gCommandResponseDirective, CommandResponseDirective::kSendSuccessStatusCode); chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); @@ -302,9 +173,10 @@ TEST_F(TestCommands, TestMultipleSuccessNoDataResponses) // not safe to do so. auto onFailureCb = [&failureCalls](CHIP_ERROR aError) { ++failureCalls; }; - responseDirective = kSendMultipleSuccessStatusCodes; + ScopedChange directive(gCommandResponseDirective, CommandResponseDirective::kSendMultipleSuccessStatusCodes); - Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); + Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, + onFailureCb); DrainAndServiceIO(); @@ -340,7 +212,7 @@ TEST_F(TestCommands, TestAsyncResponse) // not safe to do so. auto onFailureCb = [&onFailureWasCalled](CHIP_ERROR aError) { onFailureWasCalled = true; }; - responseDirective = kAsync; + ScopedChange directive(gCommandResponseDirective, CommandResponseDirective::kAsync); chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); @@ -350,12 +222,12 @@ TEST_F(TestCommands, TestAsyncResponse) EXPECT_TRUE(!onSuccessWasCalled && !onFailureWasCalled && !statusCheck); EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 2u); - CommandHandler * commandHandle = asyncHandle.Get(); + CommandHandler * commandHandle = gAsyncCommandHandle.Get(); ASSERT_NE(commandHandle, nullptr); commandHandle->AddStatus(ConcreteCommandPath(kTestEndpointId, request.GetClusterId(), request.GetCommandId()), Protocols::InteractionModel::Status::Success); - asyncHandle.Release(); + gAsyncCommandHandle.Release(); DrainAndServiceIO(); @@ -385,7 +257,7 @@ TEST_F(TestCommands, TestFailure) onFailureWasCalled = true; }; - responseDirective = kSendError; + ScopedChange directive(gCommandResponseDirective, CommandResponseDirective::kSendError); chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); @@ -423,9 +295,10 @@ TEST_F(TestCommands, TestMultipleFailures) ++failureCalls; }; - responseDirective = kSendMultipleErrors; + ScopedChange directive(gCommandResponseDirective, CommandResponseDirective::kSendMultipleErrors); - Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); + Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, + onFailureCb); DrainAndServiceIO(); @@ -462,7 +335,7 @@ TEST_F(TestCommands, TestSuccessNoDataResponseWithClusterStatus) // not safe to do so. auto onFailureCb = [&onFailureWasCalled](CHIP_ERROR aError) { onFailureWasCalled = true; }; - responseDirective = kSendSuccessStatusCodeWithClusterStatus; + ScopedChange directive(gCommandResponseDirective, CommandResponseDirective::kSendSuccessStatusCodeWithClusterStatus); chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); @@ -501,7 +374,7 @@ TEST_F(TestCommands, TestFailureWithClusterStatus) onFailureWasCalled = true; }; - responseDirective = kSendErrorWithClusterStatus; + ScopedChange directive(gCommandResponseDirective, CommandResponseDirective::kSendErrorWithClusterStatus); chip::Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); @@ -512,4 +385,4 @@ TEST_F(TestCommands, TestFailureWithClusterStatus) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -} // namespace +} // namespace \ No newline at end of file diff --git a/src/controller/tests/data_model/TestRead.cpp b/src/controller/tests/data_model/TestRead.cpp index 1a561d738ff323..98d192dd882e03 100644 --- a/src/controller/tests/data_model/TestRead.cpp +++ b/src/controller/tests/data_model/TestRead.cpp @@ -16,242 +16,34 @@ * limitations under the License. */ +#include #include -#include "system/SystemClock.h" -#include "transport/SecureSession.h" +#include "DataModelFixtures.h" + #include #include #include #include #include +#include #include #include #include #include #include #include +#include #include +#include +#include using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; +using namespace chip::app::DataModelTests; using namespace chip::Protocols; - -namespace { - -constexpr EndpointId kTestEndpointId = 1; -constexpr DataVersion kDataVersion = 5; -constexpr AttributeId kPerpetualAttributeid = chip::Test::MockAttributeId(1); -constexpr ClusterId kPerpetualClusterId = chip::Test::MockClusterId(2); -bool expectedAttribute1 = true; -int16_t expectedAttribute2 = 42; -uint64_t expectedAttribute3 = 0xdeadbeef0000cafe; -uint8_t expectedAttribute4[256] = { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, -}; - -enum ResponseDirective -{ - kSendDataResponse, - kSendManyDataResponses, // Many data blocks, for a single concrete path - // read, simulating a malicious server. - kSendManyDataResponsesWrongPath, // Many data blocks, all using the wrong - // path, for a single concrete path - // read, simulating a malicious server. - kSendDataError, - kSendTwoDataErrors, // Multiple errors, for a single concrete path, - // simulating a malicious server. -}; - -ResponseDirective responseDirective; - -// Number of reads of Clusters::UnitTesting::Attributes::Int16u that we have observed. -// Every read will increment this count by 1 and return the new value. -uint16_t totalReadCount = 0; - -bool isLitIcd = false; - -} // namespace - -namespace chip { -namespace app { -CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, - const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, - AttributeEncodeState * apEncoderState) -{ - if (aPath.mEndpointId >= chip::Test::kMockEndpointMin) - { - return chip::Test::ReadSingleMockClusterData(aSubjectDescriptor.fabricIndex, aPath, aAttributeReports, apEncoderState); - } - - if (responseDirective == kSendManyDataResponses || responseDirective == kSendManyDataResponsesWrongPath) - { - if (aPath.mClusterId != Clusters::UnitTesting::Id || aPath.mAttributeId != Clusters::UnitTesting::Attributes::Boolean::Id) - { - return CHIP_ERROR_INCORRECT_STATE; - } - - for (size_t i = 0; i < 4; ++i) - { - ConcreteAttributePath path(aPath); - // Use an incorrect attribute id for some of the responses. - path.mAttributeId = - static_cast(path.mAttributeId + (i / 2) + (responseDirective == kSendManyDataResponsesWrongPath)); - AttributeEncodeState state(apEncoderState); - AttributeValueEncoder valueEncoder(aAttributeReports, aSubjectDescriptor, path, kDataVersion, aIsFabricFiltered, state); - ReturnErrorOnFailure(valueEncoder.Encode(true)); - } - - return CHIP_NO_ERROR; - } - - if (responseDirective == kSendDataResponse) - { - if (aPath.mClusterId == app::Clusters::UnitTesting::Id && - aPath.mAttributeId == app::Clusters::UnitTesting::Attributes::ListFabricScoped::Id) - { - AttributeEncodeState state(apEncoderState); - AttributeValueEncoder valueEncoder(aAttributeReports, aSubjectDescriptor, aPath, kDataVersion, aIsFabricFiltered, - state); - - return valueEncoder.EncodeList([aSubjectDescriptor](const auto & encoder) -> CHIP_ERROR { - app::Clusters::UnitTesting::Structs::TestFabricScoped::Type val; - val.fabricIndex = aSubjectDescriptor.fabricIndex; - ReturnErrorOnFailure(encoder.Encode(val)); - val.fabricIndex = (val.fabricIndex == 1) ? 2 : 1; - ReturnErrorOnFailure(encoder.Encode(val)); - return CHIP_NO_ERROR; - }); - } - if (aPath.mClusterId == app::Clusters::UnitTesting::Id && - aPath.mAttributeId == app::Clusters::UnitTesting::Attributes::Int16u::Id) - { - AttributeEncodeState state(apEncoderState); - AttributeValueEncoder valueEncoder(aAttributeReports, aSubjectDescriptor, aPath, kDataVersion, aIsFabricFiltered, - state); - - return valueEncoder.Encode(++totalReadCount); - } - if (aPath.mClusterId == kPerpetualClusterId || - (aPath.mClusterId == app::Clusters::UnitTesting::Id && aPath.mAttributeId == kPerpetualAttributeid)) - { - AttributeEncodeState state; - AttributeValueEncoder valueEncoder(aAttributeReports, aSubjectDescriptor, aPath, kDataVersion, aIsFabricFiltered, - state); - - CHIP_ERROR err = valueEncoder.EncodeList([](const auto & encoder) -> CHIP_ERROR { - encoder.Encode(static_cast(1)); - return CHIP_ERROR_NO_MEMORY; - }); - - if (err != CHIP_NO_ERROR) - { - // If the err is not CHIP_NO_ERROR, means the encoding was aborted, then the valueEncoder may save its state. - // The state is used by list chunking feature for now. - if (apEncoderState != nullptr) - { - *apEncoderState = valueEncoder.GetState(); - } - return err; - } - } - if (aPath.mClusterId == app::Clusters::IcdManagement::Id && - aPath.mAttributeId == app::Clusters::IcdManagement::Attributes::OperatingMode::Id) - { - AttributeEncodeState state(apEncoderState); - AttributeValueEncoder valueEncoder(aAttributeReports, aSubjectDescriptor, aPath, kDataVersion, aIsFabricFiltered, - state); - - return valueEncoder.Encode(isLitIcd ? Clusters::IcdManagement::OperatingModeEnum::kLit - : Clusters::IcdManagement::OperatingModeEnum::kSit); - } - - AttributeReportIB::Builder & attributeReport = aAttributeReports.CreateAttributeReport(); - ReturnErrorOnFailure(aAttributeReports.GetError()); - AttributeDataIB::Builder & attributeData = attributeReport.CreateAttributeData(); - ReturnErrorOnFailure(attributeReport.GetError()); - Clusters::UnitTesting::Attributes::ListStructOctetString::TypeInfo::Type value; - Clusters::UnitTesting::Structs::TestListStructOctet::Type valueBuf[4]; - - value = valueBuf; - - uint8_t i = 0; - for (auto & item : valueBuf) - { - item.member1 = i; - i++; - } - - attributeData.DataVersion(kDataVersion); - ReturnErrorOnFailure(attributeData.GetError()); - AttributePathIB::Builder & attributePath = attributeData.CreatePath(); - attributePath.Endpoint(aPath.mEndpointId).Cluster(aPath.mClusterId).Attribute(aPath.mAttributeId).EndOfAttributePathIB(); - ReturnErrorOnFailure(attributePath.GetError()); - - ReturnErrorOnFailure(DataModel::Encode(*(attributeData.GetWriter()), TLV::ContextTag(AttributeDataIB::Tag::kData), value)); - ReturnErrorOnFailure(attributeData.EndOfAttributeDataIB()); - return attributeReport.EndOfAttributeReportIB(); - } - - for (size_t i = 0; i < (responseDirective == kSendTwoDataErrors ? 2 : 1); ++i) - { - AttributeReportIB::Builder & attributeReport = aAttributeReports.CreateAttributeReport(); - ReturnErrorOnFailure(aAttributeReports.GetError()); - AttributeStatusIB::Builder & attributeStatus = attributeReport.CreateAttributeStatus(); - AttributePathIB::Builder & attributePath = attributeStatus.CreatePath(); - 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::Busy)); - attributeStatus.EndOfAttributeStatusIB(); - ReturnErrorOnFailure(attributeStatus.GetError()); - ReturnErrorOnFailure(attributeReport.EndOfAttributeReportIB()); - } - - return CHIP_NO_ERROR; -} - -bool IsClusterDataVersionEqual(const app::ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) -{ - if (aRequiredVersion == kDataVersion) - { - return true; - } - if (Test::GetVersion() == aRequiredVersion) - { - return true; - } - - return false; -} - -bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) -{ - return false; -} - -bool ConcreteAttributePathExists(const ConcreteAttributePath & aPath) -{ - return true; -} - -Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath) -{ - return Protocols::InteractionModel::Status::Success; -} - -} // namespace app -} // namespace chip +using namespace chip::Test; namespace { @@ -281,7 +73,8 @@ class TestRead : public chip::Test::AppContext, public app::ReadHandler::Applica // Helper for MultipleReadHelper that does not spin the event loop, so we // don't end up with nested event loops. - void MultipleReadHelperInternal(size_t aReadCount, uint32_t & aNumSuccessCalls, uint32_t & aNumFailureCalls); + void MultipleReadHelperInternal(size_t aReadCount, uint32_t & aNumSuccessCalls, + uint32_t & aNumFailureCalls); // Establish the given number of subscriptions, then issue the given number // of reads in parallel and wait for them all to succeed. @@ -294,14 +87,9 @@ class TestRead : public chip::Test::AppContext, public app::ReadHandler::Applica bool mEmitSubscriptionError = false; int32_t mNumActiveSubscriptions = 0; bool mAlterSubscriptionIntervals = false; - -protected: - struct TestReadHandler_ParallelReads_TestCase_Parameters; - void TestReadHandler_ParallelReads_TestCase(const TestReadHandler_ParallelReads_TestCase_Parameters & params, - std::function body); }; -uint16_t TestRead::mMaxInterval = 66; +uint16_t TestRead::mMaxInterval = 66; class MockInteractionModelApp : public chip::app::ClusterStateCache::Callback { @@ -357,7 +145,7 @@ TEST_F(TestRead, TestReadAttributeResponse) auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -397,8 +185,8 @@ TEST_F(TestRead, TestReadAttributeResponse) // `EXPECT_TRUE(version1.HasValue() && (version1.Value() == 0))`. TEST_F(TestRead, TestReadSubscribeAttributeResponseWithVersionOnlyCache) { - CHIP_ERROR err = CHIP_NO_ERROR; - responseDirective = kSendDataResponse; + CHIP_ERROR err = CHIP_NO_ERROR; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); MockInteractionModelApp delegate; chip::app::ClusterStateCache cache(delegate, Optional::Missing(), false /*cachedData*/); @@ -469,8 +257,8 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithVersionOnlyCache) TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) { - CHIP_ERROR err = CHIP_NO_ERROR; - responseDirective = kSendDataResponse; + CHIP_ERROR err = CHIP_NO_ERROR; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); MockInteractionModelApp delegate; chip::app::ClusterStateCache cache(delegate); @@ -573,7 +361,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -583,7 +371,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } { @@ -593,7 +381,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } delegate.mNumAttributeResponse = 0; @@ -651,7 +439,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } { @@ -661,7 +449,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } delegate.mNumAttributeResponse = 0; } @@ -706,7 +494,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -716,7 +504,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } { @@ -726,7 +514,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); uint64_t receivedAttribute3; reader.Get(receivedAttribute3); - EXPECT_EQ(receivedAttribute3, expectedAttribute3); + EXPECT_EQ(receivedAttribute3, mockAttribute3); } { @@ -736,7 +524,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } delegate.mNumAttributeResponse = 0; } @@ -785,7 +573,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -795,7 +583,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } { @@ -805,7 +593,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } delegate.mNumAttributeResponse = 0; } @@ -849,7 +637,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -859,7 +647,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } { @@ -869,7 +657,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); uint64_t receivedAttribute3; reader.Get(receivedAttribute3); - EXPECT_EQ(receivedAttribute3, expectedAttribute3); + EXPECT_EQ(receivedAttribute3, mockAttribute3); } { @@ -879,7 +667,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } delegate.mNumAttributeResponse = 0; } @@ -931,7 +719,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -941,7 +729,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } { @@ -951,7 +739,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } delegate.mNumAttributeResponse = 0; } @@ -1000,7 +788,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -1010,7 +798,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } { @@ -1020,7 +808,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } delegate.mNumAttributeResponse = 0; } @@ -1064,7 +852,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -1074,7 +862,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } { @@ -1084,7 +872,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); uint64_t receivedAttribute3; reader.Get(receivedAttribute3); - EXPECT_EQ(receivedAttribute3, expectedAttribute3); + EXPECT_EQ(receivedAttribute3, mockAttribute3); } { @@ -1094,7 +882,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } delegate.mNumAttributeResponse = 0; } @@ -1147,7 +935,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -1157,7 +945,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } { @@ -1167,7 +955,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); uint64_t receivedAttribute3; reader.Get(receivedAttribute3); - EXPECT_EQ(receivedAttribute3, expectedAttribute3); + EXPECT_EQ(receivedAttribute3, mockAttribute3); } { @@ -1177,7 +965,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } delegate.mNumAttributeResponse = 0; readPrepareParams.mpEventPathParamsList = nullptr; @@ -1236,7 +1024,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -1246,7 +1034,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -1256,7 +1044,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } { @@ -1266,7 +1054,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); uint64_t receivedAttribute3; reader.Get(receivedAttribute3); - EXPECT_EQ(receivedAttribute3, expectedAttribute3); + EXPECT_EQ(receivedAttribute3, mockAttribute3); } { @@ -1276,7 +1064,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { app::ConcreteAttributePath attributePath(chip::Test::kMockEndpoint2, chip::Test::MockClusterId(2), @@ -1285,7 +1073,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } delegate.mNumAttributeResponse = 0; @@ -1347,7 +1135,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -1357,7 +1145,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -1367,7 +1155,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } { @@ -1377,7 +1165,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); uint64_t receivedAttribute3; reader.Get(receivedAttribute3); - EXPECT_EQ(receivedAttribute3, expectedAttribute3); + EXPECT_EQ(receivedAttribute3, mockAttribute3); } { @@ -1387,7 +1175,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -1397,7 +1185,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } delegate.mNumAttributeResponse = 0; readPrepareParams.mpEventPathParamsList = nullptr; @@ -1436,7 +1224,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); bool receivedAttribute1; reader.Get(receivedAttribute1); - EXPECT_EQ(receivedAttribute1, expectedAttribute1); + EXPECT_EQ(receivedAttribute1, mockAttribute1); } { @@ -1446,7 +1234,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); int16_t receivedAttribute2; reader.Get(receivedAttribute2); - EXPECT_EQ(receivedAttribute2, expectedAttribute2); + EXPECT_EQ(receivedAttribute2, mockAttribute2); } { @@ -1456,7 +1244,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); uint64_t receivedAttribute3; reader.Get(receivedAttribute3); - EXPECT_EQ(receivedAttribute3, expectedAttribute3); + EXPECT_EQ(receivedAttribute3, mockAttribute3); } { @@ -1466,7 +1254,7 @@ TEST_F(TestRead, TestReadSubscribeAttributeResponseWithCache) EXPECT_EQ(cache.Get(attributePath, reader), CHIP_NO_ERROR); uint8_t receivedAttribute4[256]; reader.GetBytes(receivedAttribute4, 256); - EXPECT_TRUE(memcmp(receivedAttribute4, expectedAttribute4, 256)); + EXPECT_TRUE(memcmp(receivedAttribute4, mockAttribute4, 256)); } delegate.mNumAttributeResponse = 0; } @@ -1513,7 +1301,7 @@ TEST_F(TestRead, TestReadAttributeError) auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; - responseDirective = kSendDataError; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataError); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -1544,7 +1332,7 @@ TEST_F(TestRead, TestReadAttributeTimeout) auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; - responseDirective = kSendDataError; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataError); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -1678,7 +1466,7 @@ TEST_F(TestRead, TestResubscribeAttributeTimeout) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); EXPECT_EQ(callback.mOnError, 0); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 0); @@ -1695,7 +1483,7 @@ TEST_F(TestRead, TestResubscribeAttributeTimeout) // GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return callback.mOnResubscriptionsAttempted > 0; }); + [&]() { return callback.mOnResubscriptionsAttempted > 0; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_TIMEOUT); @@ -1707,7 +1495,7 @@ TEST_F(TestRead, TestResubscribeAttributeTimeout) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -1762,7 +1550,7 @@ TEST_F(TestRead, TestSubscribeAttributeTimeout) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -1782,7 +1570,7 @@ TEST_F(TestRead, TestSubscribeAttributeTimeout) // retransmit timeouts. // GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return callback.mOnError >= 1; }); + [&]() { return callback.mOnError >= 1; }); EXPECT_EQ(callback.mOnError, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_TIMEOUT); @@ -1803,7 +1591,7 @@ TEST_F(TestRead, TestReadHandler_MultipleSubscriptions) uint32_t numSuccessCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -1871,7 +1659,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionAppRejection) uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -1937,7 +1725,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest1) uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -2012,7 +1800,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest2) uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -2087,7 +1875,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest3) uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -2164,7 +1952,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest4) uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -2231,7 +2019,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest5) uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -2306,7 +2094,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest6) uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -2381,7 +2169,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest7) uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -2457,7 +2245,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest8) uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -2520,7 +2308,7 @@ TEST_F(TestRead, TestReadHandler_SubscriptionReportingIntervalsTest9) uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -2613,7 +2401,7 @@ TEST_F(TestRead, TestSubscribe_OnActiveModeNotification) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); EXPECT_EQ(callback.mOnError, 0); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 0); @@ -2630,7 +2418,8 @@ TEST_F(TestRead, TestSubscribe_OnActiveModeNotification) // // GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; - GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), [&]() { return false; }); + GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), + [&]() { return false; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT); @@ -2645,7 +2434,7 @@ TEST_F(TestRead, TestSubscribe_OnActiveModeNotification) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -2670,16 +2459,16 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) auto sessionHandle = GetSessionBobToAlice(); SetMRPMode(chip::Test::MessagingContext::MRPMode::kResponsive); + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); + ScopedChange isLitIcd(gIsLitIcd, false); { TestResubscriptionCallback callback; app::ReadClient readClient(app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), callback, app::ReadClient::InteractionType::Subscribe); - responseDirective = kSendDataResponse; callback.mScheduleLITResubscribeImmediately = false; callback.SetReadClient(&readClient); - isLitIcd = false; app::ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); @@ -2703,7 +2492,7 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); EXPECT_EQ(callback.mOnError, 0); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 0); @@ -2724,7 +2513,7 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) // normal, non-LIT subscriptions. GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return callback.mOnResubscriptionsAttempted != 0; }); + [&]() { return callback.mOnResubscriptionsAttempted != 0; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_TIMEOUT); @@ -2735,7 +2524,7 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -2755,12 +2544,14 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) app::InteractionModelEngine::GetInstance()->GetReportingEngine().SetDirty(path); } callback.ClearCounters(); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), - [&]() { return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), [&]() { + return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; + }); // When we received the update that OperatingMode becomes LIT, we automatically set the inner peer type to LIT ICD. GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; - GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), [&]() { return false; }); + GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), + [&]() { return false; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT); @@ -2772,8 +2563,6 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); - - isLitIcd = false; } /** @@ -2816,7 +2605,7 @@ TEST_F(TestRead, TestSubscribe_ImmediatelyResubscriptionForLIT) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); EXPECT_EQ(callback.mOnError, 0); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 0); @@ -2834,7 +2623,7 @@ TEST_F(TestRead, TestSubscribe_ImmediatelyResubscriptionForLIT) // GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return callback.mLastError == CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT; }); + [&]() { return callback.mLastError == CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT); @@ -2845,7 +2634,7 @@ TEST_F(TestRead, TestSubscribe_ImmediatelyResubscriptionForLIT) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -2908,7 +2697,7 @@ void TestRead::SubscribeThenReadHelper(size_t aSubscribeCount, size_t aReadCount uint32_t numReadSuccessCalls = 0; uint32_t numReadFailureCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -2953,16 +2742,17 @@ void TestRead::SubscribeThenReadHelper(size_t aSubscribeCount, size_t aReadCount // The guts of MultipleReadHelper which take references to the success/failure // counts to modify and assume the consumer will be spinning the event loop. -void TestRead::MultipleReadHelperInternal(size_t aReadCount, uint32_t & aNumSuccessCalls, uint32_t & aNumFailureCalls) +void TestRead::MultipleReadHelperInternal(size_t aReadCount, uint32_t & aNumSuccessCalls, + uint32_t & aNumFailureCalls) { EXPECT_EQ(aNumSuccessCalls, 0u); EXPECT_EQ(aNumFailureCalls, 0u); auto sessionHandle = GetSessionBobToAlice(); - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); - uint16_t firstExpectedResponse = totalReadCount + 1; + uint16_t firstExpectedResponse = gInt16uTotalReadCount + 1; auto onFailureCb = [&aNumFailureCalls](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { aNumFailureCalls++; @@ -3003,7 +2793,7 @@ TEST_F(TestRead, TestReadHandler_MultipleSubscriptionsWithDataVersionFilter) uint32_t numSuccessCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -3058,13 +2848,93 @@ TEST_F(TestRead, TestReadHandler_MultipleSubscriptionsWithDataVersionFilter) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } +TEST_F(TestRead, TestReadHandler_DataVersionFiltersTruncated) +{ + struct : public chip::Test::LoopbackTransportDelegate + { + size_t requestSize = 0; + void WillSendMessage(const Transport::PeerAddress & peer, const System::PacketBufferHandle & message) override + { + // We only care about the messages we (Alice) send to Bob, not the responses. + // Assume the first message we see in an iteration is the request. + if (peer == GetBobAddress() && requestSize == 0) + { + requestSize = message->TotalLength(); + } + } + } loopbackDelegate; + GetLoopback().SetLoopbackTransportDelegate(&loopbackDelegate); + + // Note that on the server side, wildcard expansion does not actually work for kTestEndpointId due + // to lack of meta-data, but we don't care about the reports we get back in this test. + AttributePathParams wildcardPath(kTestEndpointId, kInvalidClusterId, kInvalidAttributeId); + constexpr size_t maxDataVersionFilterCount = 100; + DataVersionFilter dataVersionFilters[maxDataVersionFilterCount]; + ClusterId nextClusterId = 0; + for (auto & dv : dataVersionFilters) + { + dv.mEndpointId = wildcardPath.mEndpointId; + dv.mClusterId = nextClusterId++; + dv.mDataVersion = MakeOptional(0x01000000u); + } + + // Keep increasing the number of data version filters until we see truncation kick in. + size_t lastRequestSize; + for (size_t count = 1; count <= maxDataVersionFilterCount; count++) + { + lastRequestSize = loopbackDelegate.requestSize; + loopbackDelegate.requestSize = 0; // reset + + ReadPrepareParams read(GetSessionAliceToBob()); + read.mpAttributePathParamsList = &wildcardPath; + read.mAttributePathParamsListSize = 1; + read.mpDataVersionFilterList = dataVersionFilters; + read.mDataVersionFilterListSize = count; + + struct : public ReadClient::Callback + { + CHIP_ERROR error = CHIP_NO_ERROR; + bool done = false; + void OnError(CHIP_ERROR aError) override { error = aError; } + void OnDone(ReadClient * apReadClient) override { done = true; }; + + } readCallback; + + ReadClient readClient(app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), readCallback, + ReadClient::InteractionType::Read); + + EXPECT_EQ(readClient.SendRequest(read), CHIP_NO_ERROR); + + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.done; }); + EXPECT_EQ(readCallback.error, CHIP_NO_ERROR); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); + + EXPECT_NE(loopbackDelegate.requestSize, 0u); + EXPECT_GE(loopbackDelegate.requestSize, lastRequestSize); + if (loopbackDelegate.requestSize == lastRequestSize) + { + ChipLogProgress(DataManagement, "Data Version truncation detected after %llu elements", + static_cast(count - 1)); + // With the parameters used in this test and current encoding rules we can fit 68 data versions + // into a packet. If we're seeing substantially less then something is likely gone wrong. + EXPECT_GE(count, 60u); + ExitNow(); + } + } + ChipLogProgress(DataManagement, "Unable to detect Data Version truncation, maxDataVersionFilterCount too small?"); + ADD_FAILURE(); + +exit: + GetLoopback().SetLoopbackTransportDelegate(nullptr); +} + TEST_F(TestRead, TestReadHandlerResourceExhaustion_MultipleReads) { auto sessionHandle = GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -3115,7 +2985,7 @@ TEST_F(TestRead, TestReadFabricScopedWithoutFabricFilter) auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -3160,7 +3030,7 @@ TEST_F(TestRead, TestReadFabricScopedWithFabricFilter) auto sessionHandle = GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; - responseDirective = kSendDataResponse; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendDataResponse); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -3459,8 +3329,9 @@ TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) readCallback.ClearCounters(); // Run until all subscriptions are clean. - GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), - [&]() { return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), [&]() { + return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; + }); // Before the above subscription, we have one subscription with kMinSupportedPathsPerSubscription + 1 paths, we should evict // that subscription before evicting any other subscriptions, which will result we used exactly kExpectedParallelPaths and have @@ -3515,8 +3386,9 @@ TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) readCallbackFabric2.ClearCounters(); // Run until all subscriptions are clean. - GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), - [&]() { return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), [&]() { + return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; + }); // Some subscriptions on fabric 1 should be evicted since fabric 1 is using more resources than the limits. EXPECT_EQ(readCallback.mAttributeCount, @@ -3634,15 +3506,16 @@ TEST_F(TestRead, TestReadHandler_KillOldestSubscriptions) app::InteractionModelEngine::GetInstance()->SetPathPoolCapacityForSubscriptions(-1); } -struct TestRead::TestReadHandler_ParallelReads_TestCase_Parameters +struct TestReadHandler_ParallelReads_TestCase_Parameters { int ReadHandlerCapacity = -1; int PathPoolCapacity = -1; int MaxFabrics = -1; }; -void TestRead::TestReadHandler_ParallelReads_TestCase(const TestReadHandler_ParallelReads_TestCase_Parameters & params, - std::function body) +static void TestReadHandler_ParallelReads_TestCase(TeatRead * apContext, + const TestReadHandler_ParallelReads_TestCase_Parameters & params, + std::function body) { app::InteractionModelEngine::GetInstance()->SetForceHandlerQuota(true); app::InteractionModelEngine::GetInstance()->SetHandlerCapacityForReads(params.ReadHandlerCapacity); @@ -3653,10 +3526,10 @@ void TestRead::TestReadHandler_ParallelReads_TestCase(const TestReadHandler_Para // Clean up app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); - DrainAndServiceIO(); + apContext->DrainAndServiceIO(); // Sanity check - EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); + EXPECT_EQ(apContext->GetExchangeManager().GetNumActiveExchanges(), 0u); app::InteractionModelEngine::GetInstance()->SetForceHandlerQuota(false); app::InteractionModelEngine::GetInstance()->SetHandlerCapacityForReads(-1); @@ -3677,7 +3550,7 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) app::InteractionModelEngine::GetInstance()->RegisterReadHandlerAppCallback(this); auto TestCase = [&](const TestReadHandler_ParallelReads_TestCase_Parameters & params, std::function body) { - TestReadHandler_ParallelReads_TestCase(params, body); + TestReadHandler_ParallelReads_TestCase(this, params, body); }; // Case 1.1: 2 reads used up the path pool (but not the ReadHandler pool), and one incoming oversized read request => @@ -3694,10 +3567,12 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, + app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, + app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); @@ -3779,10 +3654,12 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, + app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, + app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); @@ -3824,10 +3701,12 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, + app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, + app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); @@ -3878,12 +3757,13 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &readCallbackForOversizedRead, readClients); GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return readCallbackForOversizedRead.reportsReceived > 0; }); + [&]() { return readCallbackForOversizedRead.reportsReceived > 0; }); EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback, readClients); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), + [&]() { return backgroundReadCallback.reportsReceived > 0; }); EXPECT_TRUE(readCallbackForOversizedRead.reportsReceived > 0 && backgroundReadCallback.reportsReceived > 0); @@ -3903,7 +3783,8 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 1u); backgroundReadCallback.ClearCounter(); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), + [&]() { return backgroundReadCallback.reportsReceived > 0; }); // We don't check the readCallbackForOversizedRead, since it cannot prove anything -- it can be 0 even when the // oversized read request is alive. We ensure this by checking (1) we have only one active read handler, (2) the one @@ -3930,14 +3811,15 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback, readClients); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), + [&]() { return backgroundReadCallback.reportsReceived > 0; }); EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &readCallbackForOversizedRead, readClients); GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return readCallbackForOversizedRead.reportsReceived > 0; }); + [&]() { return readCallbackForOversizedRead.reportsReceived > 0; }); EXPECT_TRUE(readCallbackForOversizedRead.reportsReceived > 0 && backgroundReadCallback.reportsReceived > 0); @@ -3957,7 +3839,8 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 1u); backgroundReadCallback.ClearCounter(); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), + [&]() { return backgroundReadCallback.reportsReceived > 0; }); // We don't check the readCallbackForOversizedRead, since it cannot prove anything -- it can be 0 even when the // oversized read request is alive. We ensure this by checking (1) we have only one active read handler, (2) the one @@ -4034,12 +3917,14 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), + [&]() { return backgroundReadCallback1.reportsReceived > 0; }); EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback2.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), + [&]() { return backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); backgroundReadCallback1.ClearCounter(); @@ -4063,7 +3948,8 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 1u); // Note: Younger read handler will be evicted. - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), + [&]() { return backgroundReadCallback1.reportsReceived > 0; }); EXPECT_GT(backgroundReadCallback1.reportsReceived, 0); }); @@ -4085,12 +3971,14 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), + [&]() { return backgroundReadCallback1.reportsReceived > 0; }); EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback2.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), + [&]() { return backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); backgroundReadCallback1.ClearCounter(); @@ -4114,7 +4002,8 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 1u); // Note: Larger read handler will be evicted before evicting the younger one. - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback2.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), + [&]() { return backgroundReadCallback2.reportsReceived > 0; }); EXPECT_GT(backgroundReadCallback2.reportsReceived, 0); }); @@ -4241,13 +4130,16 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback3; std::vector> readClients; - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, + app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, + app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, + app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback3, readClients); @@ -4291,10 +4183,12 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, + app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, + app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); @@ -4694,7 +4588,7 @@ TEST_F(TestRead, TestReadAttribute_ManyDataValues) size_t successCalls = 0; size_t failureCalls = 0; - responseDirective = kSendManyDataResponses; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendManyDataResponses); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -4727,7 +4621,7 @@ TEST_F(TestRead, TestReadAttribute_ManyDataValuesWrongPath) size_t successCalls = 0; size_t failureCalls = 0; - responseDirective = kSendManyDataResponsesWrongPath; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendManyDataResponsesWrongPath); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -4760,7 +4654,7 @@ TEST_F(TestRead, TestReadAttribute_ManyErrors) size_t successCalls = 0; size_t failureCalls = 0; - responseDirective = kSendTwoDataErrors; + ScopedChange directive(gReadResponseDirective, ReadResponseDirective::kSendTwoDataErrors); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -4844,4 +4738,4 @@ System::Clock::Timeout TestRead::ComputeSubscriptionTimeout(System::Clock::Secon return publisherTransmissionTimeout + aMaxInterval + System::Clock::Milliseconds32(1000); } -} // namespace +} // namespace \ No newline at end of file diff --git a/src/controller/tests/data_model/TestWrite.cpp b/src/controller/tests/data_model/TestWrite.cpp index f7eb94bc78e420..6b7bd884b0ff67 100644 --- a/src/controller/tests/data_model/TestWrite.cpp +++ b/src/controller/tests/data_model/TestWrite.cpp @@ -16,8 +16,11 @@ * limitations under the License. */ +#include #include +#include "DataModelFixtures.h" + #include "app-common/zap-generated/ids/Clusters.h" #include #include @@ -27,184 +30,18 @@ #include #include #include +#include #include using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; using namespace chip::app::Clusters::UnitTesting; +using namespace chip::app::DataModelTests; using namespace chip::Protocols; namespace { -constexpr EndpointId kTestEndpointId = 1; -constexpr DataVersion kRejectedDataVersion = 1; -constexpr DataVersion kAcceptedDataVersion = 5; - -constexpr uint8_t kExampleClusterSpecificSuccess = 11u; -constexpr uint8_t kExampleClusterSpecificFailure = 12u; - -enum ResponseDirective -{ - kSendAttributeSuccess, - kSendAttributeError, - kSendMultipleSuccess, - kSendMultipleErrors, - kSendClusterSpecificSuccess, - kSendClusterSpecificFailure, -}; - -ResponseDirective gResponseDirective = kSendAttributeSuccess; - -} // namespace - -namespace chip { -namespace app { - -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) -{ - static ListIndex listStructOctetStringElementCount = 0; - - if (aPath.mDataVersion.HasValue() && aPath.mDataVersion.Value() == kRejectedDataVersion) - { - return aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::DataVersionMismatch); - } - - if (aPath.mClusterId == Clusters::UnitTesting::Id && - aPath.mAttributeId == Attributes::ListStructOctetString::TypeInfo::GetAttributeId()) - { - if (gResponseDirective == kSendAttributeSuccess) - { - if (!aPath.IsListOperation() || aPath.mListOp == ConcreteDataAttributePath::ListOperation::ReplaceAll) - { - - Attributes::ListStructOctetString::TypeInfo::DecodableType value; - - ReturnErrorOnFailure(DataModel::Decode(aReader, value)); - - auto iter = value.begin(); - listStructOctetStringElementCount = 0; - while (iter.Next()) - { - auto & item = iter.GetValue(); - - VerifyOrReturnError(item.member1 == listStructOctetStringElementCount, CHIP_ERROR_INVALID_ARGUMENT); - listStructOctetStringElementCount++; - } - - aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Success); - } - else if (aPath.mListOp == ConcreteDataAttributePath::ListOperation::AppendItem) - { - Structs::TestListStructOctet::DecodableType item; - ReturnErrorOnFailure(DataModel::Decode(aReader, item)); - VerifyOrReturnError(item.member1 == listStructOctetStringElementCount, CHIP_ERROR_INVALID_ARGUMENT); - listStructOctetStringElementCount++; - - aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Success); - } - else - { - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; - } - } - else - { - aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Failure); - } - - return CHIP_NO_ERROR; - } - if (aPath.mClusterId == Clusters::UnitTesting::Id && aPath.mAttributeId == Attributes::ListFabricScoped::Id) - { - // Mock a invalid SubjectDescriptor - AttributeValueDecoder decoder(aReader, Access::SubjectDescriptor()); - if (!aPath.IsListOperation() || aPath.mListOp == ConcreteDataAttributePath::ListOperation::ReplaceAll) - { - Attributes::ListFabricScoped::TypeInfo::DecodableType value; - - ReturnErrorOnFailure(decoder.Decode(value)); - - auto iter = value.begin(); - while (iter.Next()) - { - auto & item = iter.GetValue(); - (void) item; - } - - aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Success); - } - else if (aPath.mListOp == ConcreteDataAttributePath::ListOperation::AppendItem) - { - Structs::TestFabricScoped::DecodableType item; - ReturnErrorOnFailure(decoder.Decode(item)); - - aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Success); - } - else - { - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; - } - return CHIP_NO_ERROR; - } - - // Boolean attribute of unit testing cluster triggers "multiple errors" case. - if (aPath.mClusterId == Clusters::UnitTesting::Id && aPath.mAttributeId == Attributes::Boolean::TypeInfo::GetAttributeId()) - { - InteractionModel::ClusterStatusCode status{ Protocols::InteractionModel::Status::InvalidValue }; - - if (gResponseDirective == kSendMultipleSuccess) - { - status = InteractionModel::Status::Success; - } - else if (gResponseDirective == kSendMultipleErrors) - { - status = InteractionModel::Status::Failure; - } - else - { - VerifyOrDie(false); - } - - for (size_t i = 0; i < 4; ++i) - { - aWriteHandler->AddStatus(aPath, status); - } - - return CHIP_NO_ERROR; - } - - if (aPath.mClusterId == Clusters::UnitTesting::Id && aPath.mAttributeId == Attributes::Int8u::TypeInfo::GetAttributeId()) - { - InteractionModel::ClusterStatusCode status{ Protocols::InteractionModel::Status::InvalidValue }; - if (gResponseDirective == kSendClusterSpecificSuccess) - { - status = InteractionModel::ClusterStatusCode::ClusterSpecificSuccess(kExampleClusterSpecificSuccess); - } - else if (gResponseDirective == kSendClusterSpecificFailure) - { - status = InteractionModel::ClusterStatusCode::ClusterSpecificFailure(kExampleClusterSpecificFailure); - } - else - { - VerifyOrDie(false); - } - - aWriteHandler->AddStatus(aPath, status); - return CHIP_NO_ERROR; - } - - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; -} - class SingleWriteCallback : public WriteClient::Callback { public: @@ -245,11 +82,6 @@ class SingleWriteCallback : public WriteClient::Callback StatusIB mPathStatus; }; -} // namespace app -} // namespace chip - -namespace { - class TestWrite : public chip::Test::AppContext { public: @@ -279,7 +111,7 @@ TEST_F(TestWrite, TestDataResponse) i++; } - gResponseDirective = kSendAttributeSuccess; + ScopedChange directive(gWriteResponseDirective, WriteResponseDirective::kSendAttributeSuccess); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -317,7 +149,7 @@ TEST_F(TestWrite, TestDataResponseWithAcceptedDataVersion) i++; } - gResponseDirective = kSendAttributeSuccess; + ScopedChange directive(gWriteResponseDirective, WriteResponseDirective::kSendAttributeSuccess); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -357,7 +189,7 @@ TEST_F(TestWrite, TestDataResponseWithRejectedDataVersion) i++; } - gResponseDirective = kSendAttributeSuccess; + ScopedChange directive(gWriteResponseDirective, WriteResponseDirective::kSendAttributeSuccess); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -396,7 +228,7 @@ TEST_F(TestWrite, TestAttributeError) i++; } - gResponseDirective = kSendAttributeError; + ScopedChange directive(gWriteResponseDirective, WriteResponseDirective::kSendAttributeError); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -462,7 +294,7 @@ TEST_F(TestWrite, TestMultipleSuccessResponses) size_t successCalls = 0; size_t failureCalls = 0; - gResponseDirective = kSendMultipleSuccess; + ScopedChange directive(gWriteResponseDirective, WriteResponseDirective::kSendMultipleSuccess); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -489,7 +321,7 @@ TEST_F(TestWrite, TestMultipleFailureResponses) size_t successCalls = 0; size_t failureCalls = 0; - gResponseDirective = kSendMultipleErrors; + ScopedChange directive(gWriteResponseDirective, WriteResponseDirective::kSendMultipleErrors); // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. @@ -516,7 +348,7 @@ TEST_F(TestWrite, TestWriteClusterSpecificStatuses) // Cluster-specific success code case { - gResponseDirective = kSendClusterSpecificSuccess; + ScopedChange directive(gWriteResponseDirective, WriteResponseDirective::kSendClusterSpecificSuccess); this->ResetCallback(); this->PrepareWriteCallback( @@ -548,7 +380,7 @@ TEST_F(TestWrite, TestWriteClusterSpecificStatuses) // Cluster-specific failure code case { - gResponseDirective = kSendClusterSpecificFailure; + ScopedChange directive(gWriteResponseDirective, WriteResponseDirective::kSendClusterSpecificFailure); this->ResetCallback(); this->PrepareWriteCallback( @@ -580,4 +412,4 @@ TEST_F(TestWrite, TestWriteClusterSpecificStatuses) } } -} // namespace +} // namespace \ No newline at end of file From c043105fbfc3519b2526b8fe3fe2cf846cd229cc Mon Sep 17 00:00:00 2001 From: Jeff Feasel Date: Wed, 3 Jul 2024 15:53:34 +0000 Subject: [PATCH 09/16] Fixed duplicate code and missing semicolon --- .../tests/data_model/TestCommands.cpp | 2 +- src/controller/tests/data_model/TestRead.cpp | 80 ------------------- 2 files changed, 1 insertion(+), 81 deletions(-) diff --git a/src/controller/tests/data_model/TestCommands.cpp b/src/controller/tests/data_model/TestCommands.cpp index 9a6d10916dc88b..36af9c8c0b2e7a 100644 --- a/src/controller/tests/data_model/TestCommands.cpp +++ b/src/controller/tests/data_model/TestCommands.cpp @@ -50,7 +50,7 @@ using namespace chip::Protocols; namespace { -using TestCommands = chip::Test::AppContext +using TestCommands = chip::Test::AppContext; TEST_F(TestCommands, TestDataResponse) { diff --git a/src/controller/tests/data_model/TestRead.cpp b/src/controller/tests/data_model/TestRead.cpp index 879b0f9abac59b..98d192dd882e03 100644 --- a/src/controller/tests/data_model/TestRead.cpp +++ b/src/controller/tests/data_model/TestRead.cpp @@ -2928,86 +2928,6 @@ TEST_F(TestRead, TestReadHandler_DataVersionFiltersTruncated) GetLoopback().SetLoopbackTransportDelegate(nullptr); } -TEST_F(TestRead, TestReadHandler_DataVersionFiltersTruncated) -{ - struct : public chip::Test::LoopbackTransportDelegate - { - size_t requestSize = 0; - void WillSendMessage(const Transport::PeerAddress & peer, const System::PacketBufferHandle & message) override - { - // We only care about the messages we (Alice) send to Bob, not the responses. - // Assume the first message we see in an iteration is the request. - if (peer == mpContext->GetBobAddress() && requestSize == 0) - { - requestSize = message->TotalLength(); - } - } - } loopbackDelegate; - mpContext->GetLoopback().SetLoopbackTransportDelegate(&loopbackDelegate); - - // Note that on the server side, wildcard expansion does not actually work for kTestEndpointId due - // to lack of meta-data, but we don't care about the reports we get back in this test. - AttributePathParams wildcardPath(kTestEndpointId, kInvalidClusterId, kInvalidAttributeId); - constexpr size_t maxDataVersionFilterCount = 100; - DataVersionFilter dataVersionFilters[maxDataVersionFilterCount]; - ClusterId nextClusterId = 0; - for (auto & dv : dataVersionFilters) - { - dv.mEndpointId = wildcardPath.mEndpointId; - dv.mClusterId = nextClusterId++; - dv.mDataVersion = MakeOptional(0x01000000u); - } - - // Keep increasing the number of data version filters until we see truncation kick in. - size_t lastRequestSize; - for (size_t count = 1; count <= maxDataVersionFilterCount; count++) - { - lastRequestSize = loopbackDelegate.requestSize; - loopbackDelegate.requestSize = 0; // reset - - ReadPrepareParams read(mpContext->GetSessionAliceToBob()); - read.mpAttributePathParamsList = &wildcardPath; - read.mAttributePathParamsListSize = 1; - read.mpDataVersionFilterList = dataVersionFilters; - read.mDataVersionFilterListSize = count; - - struct : public ReadClient::Callback - { - CHIP_ERROR error = CHIP_NO_ERROR; - bool done = false; - void OnError(CHIP_ERROR aError) override { error = aError; } - void OnDone(ReadClient * apReadClient) override { done = true; }; - - } readCallback; - - ReadClient readClient(app::InteractionModelEngine::GetInstance(), &mpContext->GetExchangeManager(), readCallback, - ReadClient::InteractionType::Read); - - EXPECT_EQ(readClient.SendRequest(read), CHIP_NO_ERROR); - - mpContext->GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.done; }); - EXPECT_EQ(readCallback.error, CHIP_NO_ERROR); - EXPECT_EQ(mpContext->GetExchangeManager().GetNumActiveExchanges(), 0u); - - EXPECT_NE(loopbackDelegate.requestSize, 0u); - EXPECT_GE(loopbackDelegate.requestSize, lastRequestSize); - if (loopbackDelegate.requestSize == lastRequestSize) - { - ChipLogProgress(DataManagement, "Data Version truncation detected after %llu elements", - static_cast(count - 1)); - // With the parameters used in this test and current encoding rules we can fit 68 data versions - // into a packet. If we're seeing substantially less then something is likely gone wrong. - EXPECT_GE(count, 60u); - ExitNow(); - } - } - ChipLogProgress(DataManagement, "Unable to detect Data Version truncation, maxDataVersionFilterCount too small?"); - ADD_FAILURE(); - -exit: - mpContext->GetLoopback().SetLoopbackTransportDelegate(nullptr); -} - TEST_F(TestRead, TestReadHandlerResourceExhaustion_MultipleReads) { auto sessionHandle = GetSessionBobToAlice(); From 789d6c0a65c3c785a3ad3d6da05f2ee60cb86d59 Mon Sep 17 00:00:00 2001 From: Jeff Feasel Date: Wed, 3 Jul 2024 16:24:20 +0000 Subject: [PATCH 10/16] Trying to update TestReadHandler_DataVersionFiltersTruncated --- src/controller/tests/data_model/TestRead.cpp | 161 ++++++++++--------- 1 file changed, 81 insertions(+), 80 deletions(-) diff --git a/src/controller/tests/data_model/TestRead.cpp b/src/controller/tests/data_model/TestRead.cpp index 98d192dd882e03..4f6f1b052d9b4a 100644 --- a/src/controller/tests/data_model/TestRead.cpp +++ b/src/controller/tests/data_model/TestRead.cpp @@ -2848,85 +2848,86 @@ TEST_F(TestRead, TestReadHandler_MultipleSubscriptionsWithDataVersionFilter) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F(TestRead, TestReadHandler_DataVersionFiltersTruncated) -{ - struct : public chip::Test::LoopbackTransportDelegate - { - size_t requestSize = 0; - void WillSendMessage(const Transport::PeerAddress & peer, const System::PacketBufferHandle & message) override - { - // We only care about the messages we (Alice) send to Bob, not the responses. - // Assume the first message we see in an iteration is the request. - if (peer == GetBobAddress() && requestSize == 0) - { - requestSize = message->TotalLength(); - } - } - } loopbackDelegate; - GetLoopback().SetLoopbackTransportDelegate(&loopbackDelegate); - - // Note that on the server side, wildcard expansion does not actually work for kTestEndpointId due - // to lack of meta-data, but we don't care about the reports we get back in this test. - AttributePathParams wildcardPath(kTestEndpointId, kInvalidClusterId, kInvalidAttributeId); - constexpr size_t maxDataVersionFilterCount = 100; - DataVersionFilter dataVersionFilters[maxDataVersionFilterCount]; - ClusterId nextClusterId = 0; - for (auto & dv : dataVersionFilters) - { - dv.mEndpointId = wildcardPath.mEndpointId; - dv.mClusterId = nextClusterId++; - dv.mDataVersion = MakeOptional(0x01000000u); - } - - // Keep increasing the number of data version filters until we see truncation kick in. - size_t lastRequestSize; - for (size_t count = 1; count <= maxDataVersionFilterCount; count++) - { - lastRequestSize = loopbackDelegate.requestSize; - loopbackDelegate.requestSize = 0; // reset - - ReadPrepareParams read(GetSessionAliceToBob()); - read.mpAttributePathParamsList = &wildcardPath; - read.mAttributePathParamsListSize = 1; - read.mpDataVersionFilterList = dataVersionFilters; - read.mDataVersionFilterListSize = count; - - struct : public ReadClient::Callback - { - CHIP_ERROR error = CHIP_NO_ERROR; - bool done = false; - void OnError(CHIP_ERROR aError) override { error = aError; } - void OnDone(ReadClient * apReadClient) override { done = true; }; - - } readCallback; - - ReadClient readClient(app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), readCallback, - ReadClient::InteractionType::Read); - - EXPECT_EQ(readClient.SendRequest(read), CHIP_NO_ERROR); - - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.done; }); - EXPECT_EQ(readCallback.error, CHIP_NO_ERROR); - EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); - - EXPECT_NE(loopbackDelegate.requestSize, 0u); - EXPECT_GE(loopbackDelegate.requestSize, lastRequestSize); - if (loopbackDelegate.requestSize == lastRequestSize) - { - ChipLogProgress(DataManagement, "Data Version truncation detected after %llu elements", - static_cast(count - 1)); - // With the parameters used in this test and current encoding rules we can fit 68 data versions - // into a packet. If we're seeing substantially less then something is likely gone wrong. - EXPECT_GE(count, 60u); - ExitNow(); - } - } - ChipLogProgress(DataManagement, "Unable to detect Data Version truncation, maxDataVersionFilterCount too small?"); - ADD_FAILURE(); - -exit: - GetLoopback().SetLoopbackTransportDelegate(nullptr); -} +// TEST_F(TestRead, TestReadHandler_DataVersionFiltersTruncated) +// { +// TestRead * pContext = this; +// struct : public chip::Test::LoopbackTransportDelegate +// { +// size_t requestSize = 0; +// void WillSendMessage(const Transport::PeerAddress & peer, const System::PacketBufferHandle & message) override +// { +// // We only care about the messages we (Alice) send to Bob, not the responses. +// // Assume the first message we see in an iteration is the request. +// if (peer == pContext->GetBobAddress() && requestSize == 0) +// { +// requestSize = message->TotalLength(); +// } +// } +// } loopbackDelegate; +// GetLoopback().SetLoopbackTransportDelegate(&loopbackDelegate); + +// // Note that on the server side, wildcard expansion does not actually work for kTestEndpointId due +// // to lack of meta-data, but we don't care about the reports we get back in this test. +// AttributePathParams wildcardPath(kTestEndpointId, kInvalidClusterId, kInvalidAttributeId); +// constexpr size_t maxDataVersionFilterCount = 100; +// DataVersionFilter dataVersionFilters[maxDataVersionFilterCount]; +// ClusterId nextClusterId = 0; +// for (auto & dv : dataVersionFilters) +// { +// dv.mEndpointId = wildcardPath.mEndpointId; +// dv.mClusterId = nextClusterId++; +// dv.mDataVersion = MakeOptional(0x01000000u); +// } + +// // Keep increasing the number of data version filters until we see truncation kick in. +// size_t lastRequestSize; +// for (size_t count = 1; count <= maxDataVersionFilterCount; count++) +// { +// lastRequestSize = loopbackDelegate.requestSize; +// loopbackDelegate.requestSize = 0; // reset + +// ReadPrepareParams read(GetSessionAliceToBob()); +// read.mpAttributePathParamsList = &wildcardPath; +// read.mAttributePathParamsListSize = 1; +// read.mpDataVersionFilterList = dataVersionFilters; +// read.mDataVersionFilterListSize = count; + +// struct : public ReadClient::Callback +// { +// CHIP_ERROR error = CHIP_NO_ERROR; +// bool done = false; +// void OnError(CHIP_ERROR aError) override { error = aError; } +// void OnDone(ReadClient * apReadClient) override { done = true; }; + +// } readCallback; + +// ReadClient readClient(app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), readCallback, +// ReadClient::InteractionType::Read); + +// EXPECT_EQ(readClient.SendRequest(read), CHIP_NO_ERROR); + +// GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.done; }); +// EXPECT_EQ(readCallback.error, CHIP_NO_ERROR); +// EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); + +// EXPECT_NE(loopbackDelegate.requestSize, 0u); +// EXPECT_GE(loopbackDelegate.requestSize, lastRequestSize); +// if (loopbackDelegate.requestSize == lastRequestSize) +// { +// ChipLogProgress(DataManagement, "Data Version truncation detected after %llu elements", +// static_cast(count - 1)); +// // With the parameters used in this test and current encoding rules we can fit 68 data versions +// // into a packet. If we're seeing substantially less then something is likely gone wrong. +// EXPECT_GE(count, 60u); +// ExitNow(); +// } +// } +// ChipLogProgress(DataManagement, "Unable to detect Data Version truncation, maxDataVersionFilterCount too small?"); +// ADD_FAILURE(); + +// exit: +// GetLoopback().SetLoopbackTransportDelegate(nullptr); +// } TEST_F(TestRead, TestReadHandlerResourceExhaustion_MultipleReads) { @@ -3513,7 +3514,7 @@ struct TestReadHandler_ParallelReads_TestCase_Parameters int MaxFabrics = -1; }; -static void TestReadHandler_ParallelReads_TestCase(TeatRead * apContext, +static void TestReadHandler_ParallelReads_TestCase(TestRead * apContext, const TestReadHandler_ParallelReads_TestCase_Parameters & params, std::function body) { From 6525d9fda833e420f192031336dc17d2cfa28f68 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Wed, 3 Jul 2024 16:24:52 +0000 Subject: [PATCH 11/16] Restyled by whitespace --- src/controller/tests/data_model/TestCommands.cpp | 2 +- src/controller/tests/data_model/TestRead.cpp | 2 +- src/controller/tests/data_model/TestWrite.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/controller/tests/data_model/TestCommands.cpp b/src/controller/tests/data_model/TestCommands.cpp index 36af9c8c0b2e7a..33f3029df69466 100644 --- a/src/controller/tests/data_model/TestCommands.cpp +++ b/src/controller/tests/data_model/TestCommands.cpp @@ -385,4 +385,4 @@ TEST_F(TestCommands, TestFailureWithClusterStatus) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -} // namespace \ No newline at end of file +} // namespace diff --git a/src/controller/tests/data_model/TestRead.cpp b/src/controller/tests/data_model/TestRead.cpp index 4f6f1b052d9b4a..3015ce9304503b 100644 --- a/src/controller/tests/data_model/TestRead.cpp +++ b/src/controller/tests/data_model/TestRead.cpp @@ -4739,4 +4739,4 @@ System::Clock::Timeout TestRead::ComputeSubscriptionTimeout(System::Clock::Secon return publisherTransmissionTimeout + aMaxInterval + System::Clock::Milliseconds32(1000); } -} // namespace \ No newline at end of file +} // namespace diff --git a/src/controller/tests/data_model/TestWrite.cpp b/src/controller/tests/data_model/TestWrite.cpp index 6b7bd884b0ff67..03d100ab33dabb 100644 --- a/src/controller/tests/data_model/TestWrite.cpp +++ b/src/controller/tests/data_model/TestWrite.cpp @@ -412,4 +412,4 @@ TEST_F(TestWrite, TestWriteClusterSpecificStatuses) } } -} // namespace \ No newline at end of file +} // namespace From 246062465715b989f3de0fc13897f71d4652a1a7 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Wed, 3 Jul 2024 16:24:56 +0000 Subject: [PATCH 12/16] Restyled by clang-format --- .../tests/data_model/TestCommands.cpp | 6 +- src/controller/tests/data_model/TestRead.cpp | 122 +++++++----------- 2 files changed, 49 insertions(+), 79 deletions(-) diff --git a/src/controller/tests/data_model/TestCommands.cpp b/src/controller/tests/data_model/TestCommands.cpp index 33f3029df69466..0f6166cfed59b9 100644 --- a/src/controller/tests/data_model/TestCommands.cpp +++ b/src/controller/tests/data_model/TestCommands.cpp @@ -175,8 +175,7 @@ TEST_F(TestCommands, TestMultipleSuccessNoDataResponses) ScopedChange directive(gCommandResponseDirective, CommandResponseDirective::kSendMultipleSuccessStatusCodes); - Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, - onFailureCb); + Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); DrainAndServiceIO(); @@ -297,8 +296,7 @@ TEST_F(TestCommands, TestMultipleFailures) ScopedChange directive(gCommandResponseDirective, CommandResponseDirective::kSendMultipleErrors); - Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, - onFailureCb); + Controller::InvokeCommandRequest(&GetExchangeManager(), sessionHandle, kTestEndpointId, request, onSuccessCb, onFailureCb); DrainAndServiceIO(); diff --git a/src/controller/tests/data_model/TestRead.cpp b/src/controller/tests/data_model/TestRead.cpp index 3015ce9304503b..3f698a27ae822c 100644 --- a/src/controller/tests/data_model/TestRead.cpp +++ b/src/controller/tests/data_model/TestRead.cpp @@ -73,8 +73,7 @@ class TestRead : public chip::Test::AppContext, public app::ReadHandler::Applica // Helper for MultipleReadHelper that does not spin the event loop, so we // don't end up with nested event loops. - void MultipleReadHelperInternal(size_t aReadCount, uint32_t & aNumSuccessCalls, - uint32_t & aNumFailureCalls); + void MultipleReadHelperInternal(size_t aReadCount, uint32_t & aNumSuccessCalls, uint32_t & aNumFailureCalls); // Establish the given number of subscriptions, then issue the given number // of reads in parallel and wait for them all to succeed. @@ -89,7 +88,7 @@ class TestRead : public chip::Test::AppContext, public app::ReadHandler::Applica bool mAlterSubscriptionIntervals = false; }; -uint16_t TestRead::mMaxInterval = 66; +uint16_t TestRead::mMaxInterval = 66; class MockInteractionModelApp : public chip::app::ClusterStateCache::Callback { @@ -1466,7 +1465,7 @@ TEST_F(TestRead, TestResubscribeAttributeTimeout) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); EXPECT_EQ(callback.mOnError, 0); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 0); @@ -1483,7 +1482,7 @@ TEST_F(TestRead, TestResubscribeAttributeTimeout) // GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return callback.mOnResubscriptionsAttempted > 0; }); + [&]() { return callback.mOnResubscriptionsAttempted > 0; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_TIMEOUT); @@ -1495,7 +1494,7 @@ TEST_F(TestRead, TestResubscribeAttributeTimeout) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -1550,7 +1549,7 @@ TEST_F(TestRead, TestSubscribeAttributeTimeout) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -1570,7 +1569,7 @@ TEST_F(TestRead, TestSubscribeAttributeTimeout) // retransmit timeouts. // GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return callback.mOnError >= 1; }); + [&]() { return callback.mOnError >= 1; }); EXPECT_EQ(callback.mOnError, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_TIMEOUT); @@ -2401,7 +2400,7 @@ TEST_F(TestRead, TestSubscribe_OnActiveModeNotification) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); EXPECT_EQ(callback.mOnError, 0); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 0); @@ -2418,8 +2417,7 @@ TEST_F(TestRead, TestSubscribe_OnActiveModeNotification) // // GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; - GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return false; }); + GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), [&]() { return false; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT); @@ -2434,7 +2432,7 @@ TEST_F(TestRead, TestSubscribe_OnActiveModeNotification) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -2492,7 +2490,7 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); EXPECT_EQ(callback.mOnError, 0); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 0); @@ -2513,7 +2511,7 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) // normal, non-LIT subscriptions. GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return callback.mOnResubscriptionsAttempted != 0; }); + [&]() { return callback.mOnResubscriptionsAttempted != 0; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_TIMEOUT); @@ -2524,7 +2522,7 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -2544,14 +2542,12 @@ TEST_F(TestRead, TestSubscribe_DynamicLITSubscription) app::InteractionModelEngine::GetInstance()->GetReportingEngine().SetDirty(path); } callback.ClearCounters(); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), [&]() { - return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; - }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), + [&]() { return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; }); // When we received the update that OperatingMode becomes LIT, we automatically set the inner peer type to LIT ICD. GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; - GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return false; }); + GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), [&]() { return false; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT); @@ -2605,7 +2601,7 @@ TEST_F(TestRead, TestSubscribe_ImmediatelyResubscriptionForLIT) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount >= 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); EXPECT_EQ(callback.mOnError, 0); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 0); @@ -2623,7 +2619,7 @@ TEST_F(TestRead, TestSubscribe_ImmediatelyResubscriptionForLIT) // GetLoopback().mNumMessagesToDrop = chip::Test::LoopbackTransport::kUnlimitedMessageCount; GetIOContext().DriveIOUntil(ComputeSubscriptionTimeout(System::Clock::Seconds16(maxInterval)), - [&]() { return callback.mLastError == CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT; }); + [&]() { return callback.mLastError == CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT; }); EXPECT_EQ(callback.mOnResubscriptionsAttempted, 1); EXPECT_EQ(callback.mLastError, CHIP_ERROR_LIT_SUBSCRIBE_INACTIVE_TIMEOUT); @@ -2634,7 +2630,7 @@ TEST_F(TestRead, TestSubscribe_ImmediatelyResubscriptionForLIT) // Drive servicing IO till we have established a subscription. // GetIOContext().DriveIOUntil(System::Clock::Milliseconds32(2000), - [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); + [&]() { return callback.mOnSubscriptionEstablishedCount == 1; }); EXPECT_EQ(callback.mOnSubscriptionEstablishedCount, 1); // @@ -2742,8 +2738,7 @@ void TestRead::SubscribeThenReadHelper(size_t aSubscribeCount, size_t aReadCount // The guts of MultipleReadHelper which take references to the success/failure // counts to modify and assume the consumer will be spinning the event loop. -void TestRead::MultipleReadHelperInternal(size_t aReadCount, uint32_t & aNumSuccessCalls, - uint32_t & aNumFailureCalls) +void TestRead::MultipleReadHelperInternal(size_t aReadCount, uint32_t & aNumSuccessCalls, uint32_t & aNumFailureCalls) { EXPECT_EQ(aNumSuccessCalls, 0u); EXPECT_EQ(aNumFailureCalls, 0u); @@ -3330,9 +3325,8 @@ TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) readCallback.ClearCounters(); // Run until all subscriptions are clean. - GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), [&]() { - return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; - }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), + [&]() { return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; }); // Before the above subscription, we have one subscription with kMinSupportedPathsPerSubscription + 1 paths, we should evict // that subscription before evicting any other subscriptions, which will result we used exactly kExpectedParallelPaths and have @@ -3387,9 +3381,8 @@ TEST_F(TestRead, TestReadHandler_KillOverQuotaSubscriptions) readCallbackFabric2.ClearCounters(); // Run until all subscriptions are clean. - GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), [&]() { - return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; - }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(60), + [&]() { return app::InteractionModelEngine::GetInstance()->GetNumDirtySubscriptions() == 0; }); // Some subscriptions on fabric 1 should be evicted since fabric 1 is using more resources than the limits. EXPECT_EQ(readCallback.mAttributeCount, @@ -3568,12 +3561,10 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); @@ -3655,12 +3646,10 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); @@ -3702,12 +3691,10 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); @@ -3758,13 +3745,12 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &readCallbackForOversizedRead, readClients); GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return readCallbackForOversizedRead.reportsReceived > 0; }); + [&]() { return readCallbackForOversizedRead.reportsReceived > 0; }); EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback, readClients); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback.reportsReceived > 0; }); EXPECT_TRUE(readCallbackForOversizedRead.reportsReceived > 0 && backgroundReadCallback.reportsReceived > 0); @@ -3784,8 +3770,7 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 1u); backgroundReadCallback.ClearCounter(); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback.reportsReceived > 0; }); // We don't check the readCallbackForOversizedRead, since it cannot prove anything -- it can be 0 even when the // oversized read request is alive. We ensure this by checking (1) we have only one active read handler, (2) the one @@ -3812,15 +3797,14 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback, readClients); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback.reportsReceived > 0; }); EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &readCallbackForOversizedRead, readClients); GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return readCallbackForOversizedRead.reportsReceived > 0; }); + [&]() { return readCallbackForOversizedRead.reportsReceived > 0; }); EXPECT_TRUE(readCallbackForOversizedRead.reportsReceived > 0 && backgroundReadCallback.reportsReceived > 0); @@ -3840,8 +3824,7 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 1u); backgroundReadCallback.ClearCounter(); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback.reportsReceived > 0; }); // We don't check the readCallbackForOversizedRead, since it cannot prove anything -- it can be 0 even when the // oversized read request is alive. We ensure this by checking (1) we have only one active read handler, (2) the one @@ -3918,14 +3901,12 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback1.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0; }); EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback2.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); backgroundReadCallback1.ClearCounter(); @@ -3949,8 +3930,7 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 1u); // Note: Younger read handler will be evicted. - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback1.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0; }); EXPECT_GT(backgroundReadCallback1.reportsReceived, 0); }); @@ -3972,14 +3952,12 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) app::InteractionModelEngine::kMinSupportedPathsPerReadRequest + 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback1.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback1.reportsReceived > 0; }); EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, 1, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback2.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback2.reportsReceived > 0; }); EXPECT_TRUE(backgroundReadCallback1.reportsReceived > 0 && backgroundReadCallback2.reportsReceived > 0); backgroundReadCallback1.ClearCounter(); @@ -4003,8 +3981,7 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) EXPECT_EQ(app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers(), 1u); // Note: Larger read handler will be evicted before evicting the younger one. - GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), - [&]() { return backgroundReadCallback2.reportsReceived > 0; }); + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return backgroundReadCallback2.reportsReceived > 0; }); EXPECT_GT(backgroundReadCallback2.reportsReceived, 0); }); @@ -4131,16 +4108,13 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback3; std::vector> readClients; - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); - EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback3, readClients); @@ -4184,12 +4158,10 @@ TEST_F(TestRead, TestReadHandler_ParallelReads) TestPerpetualListReadCallback backgroundReadCallback2; std::vector> readClients; - EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionBobToAlice(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback1, readClients); - EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, - app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, + EstablishReadOrSubscriptions(GetSessionAliceToBob(), 1, app::InteractionModelEngine::kMinSupportedPathsPerReadRequest, app::AttributePathParams(kTestEndpointId, kPerpetualClusterId, 1), app::ReadClient::InteractionType::Read, &backgroundReadCallback2, readClients); From eaa0e347c1cc18971a97669feffc1c300980599e Mon Sep 17 00:00:00 2001 From: Jeff Feasel Date: Wed, 3 Jul 2024 18:04:05 +0000 Subject: [PATCH 13/16] fixed problem with the new TestReadHandler_DataVersionFiltersTruncated --- src/controller/tests/data_model/TestRead.cpp | 160 +++++++++---------- 1 file changed, 80 insertions(+), 80 deletions(-) diff --git a/src/controller/tests/data_model/TestRead.cpp b/src/controller/tests/data_model/TestRead.cpp index 3f698a27ae822c..9df501c45e7d78 100644 --- a/src/controller/tests/data_model/TestRead.cpp +++ b/src/controller/tests/data_model/TestRead.cpp @@ -2843,86 +2843,86 @@ TEST_F(TestRead, TestReadHandler_MultipleSubscriptionsWithDataVersionFilter) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -// TEST_F(TestRead, TestReadHandler_DataVersionFiltersTruncated) -// { -// TestRead * pContext = this; -// struct : public chip::Test::LoopbackTransportDelegate -// { -// size_t requestSize = 0; -// void WillSendMessage(const Transport::PeerAddress & peer, const System::PacketBufferHandle & message) override -// { -// // We only care about the messages we (Alice) send to Bob, not the responses. -// // Assume the first message we see in an iteration is the request. -// if (peer == pContext->GetBobAddress() && requestSize == 0) -// { -// requestSize = message->TotalLength(); -// } -// } -// } loopbackDelegate; -// GetLoopback().SetLoopbackTransportDelegate(&loopbackDelegate); - -// // Note that on the server side, wildcard expansion does not actually work for kTestEndpointId due -// // to lack of meta-data, but we don't care about the reports we get back in this test. -// AttributePathParams wildcardPath(kTestEndpointId, kInvalidClusterId, kInvalidAttributeId); -// constexpr size_t maxDataVersionFilterCount = 100; -// DataVersionFilter dataVersionFilters[maxDataVersionFilterCount]; -// ClusterId nextClusterId = 0; -// for (auto & dv : dataVersionFilters) -// { -// dv.mEndpointId = wildcardPath.mEndpointId; -// dv.mClusterId = nextClusterId++; -// dv.mDataVersion = MakeOptional(0x01000000u); -// } - -// // Keep increasing the number of data version filters until we see truncation kick in. -// size_t lastRequestSize; -// for (size_t count = 1; count <= maxDataVersionFilterCount; count++) -// { -// lastRequestSize = loopbackDelegate.requestSize; -// loopbackDelegate.requestSize = 0; // reset - -// ReadPrepareParams read(GetSessionAliceToBob()); -// read.mpAttributePathParamsList = &wildcardPath; -// read.mAttributePathParamsListSize = 1; -// read.mpDataVersionFilterList = dataVersionFilters; -// read.mDataVersionFilterListSize = count; - -// struct : public ReadClient::Callback -// { -// CHIP_ERROR error = CHIP_NO_ERROR; -// bool done = false; -// void OnError(CHIP_ERROR aError) override { error = aError; } -// void OnDone(ReadClient * apReadClient) override { done = true; }; - -// } readCallback; - -// ReadClient readClient(app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), readCallback, -// ReadClient::InteractionType::Read); - -// EXPECT_EQ(readClient.SendRequest(read), CHIP_NO_ERROR); - -// GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.done; }); -// EXPECT_EQ(readCallback.error, CHIP_NO_ERROR); -// EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); - -// EXPECT_NE(loopbackDelegate.requestSize, 0u); -// EXPECT_GE(loopbackDelegate.requestSize, lastRequestSize); -// if (loopbackDelegate.requestSize == lastRequestSize) -// { -// ChipLogProgress(DataManagement, "Data Version truncation detected after %llu elements", -// static_cast(count - 1)); -// // With the parameters used in this test and current encoding rules we can fit 68 data versions -// // into a packet. If we're seeing substantially less then something is likely gone wrong. -// EXPECT_GE(count, 60u); -// ExitNow(); -// } -// } -// ChipLogProgress(DataManagement, "Unable to detect Data Version truncation, maxDataVersionFilterCount too small?"); -// ADD_FAILURE(); - -// exit: -// GetLoopback().SetLoopbackTransportDelegate(nullptr); -// } +TEST_F(TestRead, TestReadHandler_DataVersionFiltersTruncated) +{ + static TestRead * pContext = this; + struct : public chip::Test::LoopbackTransportDelegate + { + size_t requestSize = 0; + void WillSendMessage(const Transport::PeerAddress & peer, const System::PacketBufferHandle & message) override + { + // We only care about the messages we (Alice) send to Bob, not the responses. + // Assume the first message we see in an iteration is the request. + if (peer == pContext->GetBobAddress() && requestSize == 0) + { + requestSize = message->TotalLength(); + } + } + } loopbackDelegate; + GetLoopback().SetLoopbackTransportDelegate(&loopbackDelegate); + + // Note that on the server side, wildcard expansion does not actually work for kTestEndpointId due + // to lack of meta-data, but we don't care about the reports we get back in this test. + AttributePathParams wildcardPath(kTestEndpointId, kInvalidClusterId, kInvalidAttributeId); + constexpr size_t maxDataVersionFilterCount = 100; + DataVersionFilter dataVersionFilters[maxDataVersionFilterCount]; + ClusterId nextClusterId = 0; + for (auto & dv : dataVersionFilters) + { + dv.mEndpointId = wildcardPath.mEndpointId; + dv.mClusterId = nextClusterId++; + dv.mDataVersion = MakeOptional(0x01000000u); + } + + // Keep increasing the number of data version filters until we see truncation kick in. + size_t lastRequestSize; + for (size_t count = 1; count <= maxDataVersionFilterCount; count++) + { + lastRequestSize = loopbackDelegate.requestSize; + loopbackDelegate.requestSize = 0; // reset + + ReadPrepareParams read(GetSessionAliceToBob()); + read.mpAttributePathParamsList = &wildcardPath; + read.mAttributePathParamsListSize = 1; + read.mpDataVersionFilterList = dataVersionFilters; + read.mDataVersionFilterListSize = count; + + struct : public ReadClient::Callback + { + CHIP_ERROR error = CHIP_NO_ERROR; + bool done = false; + void OnError(CHIP_ERROR aError) override { error = aError; } + void OnDone(ReadClient * apReadClient) override { done = true; }; + + } readCallback; + + ReadClient readClient(app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), readCallback, + ReadClient::InteractionType::Read); + + EXPECT_EQ(readClient.SendRequest(read), CHIP_NO_ERROR); + + GetIOContext().DriveIOUntil(System::Clock::Seconds16(5), [&]() { return readCallback.done; }); + EXPECT_EQ(readCallback.error, CHIP_NO_ERROR); + EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); + + EXPECT_NE(loopbackDelegate.requestSize, 0u); + EXPECT_GE(loopbackDelegate.requestSize, lastRequestSize); + if (loopbackDelegate.requestSize == lastRequestSize) + { + ChipLogProgress(DataManagement, "Data Version truncation detected after %llu elements", + static_cast(count - 1)); + // With the parameters used in this test and current encoding rules we can fit 68 data versions + // into a packet. If we're seeing substantially less then something is likely gone wrong. + EXPECT_GE(count, 60u); + ExitNow(); + } + } + ChipLogProgress(DataManagement, "Unable to detect Data Version truncation, maxDataVersionFilterCount too small?"); + ADD_FAILURE(); + +exit: + GetLoopback().SetLoopbackTransportDelegate(nullptr); +} TEST_F(TestRead, TestReadHandlerResourceExhaustion_MultipleReads) { From 4e34d77820c19a904d1e83f79f9edf743e60af64 Mon Sep 17 00:00:00 2001 From: Jeff Feasel Date: Thu, 4 Jul 2024 12:03:07 +0000 Subject: [PATCH 14/16] fix in tracing --- src/tracing/tests/BUILD.gn | 1 + src/tracing/tests/TestMetricEvents.cpp | 4 +++- src/tracing/tests/TestTracing.cpp | 4 +++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/tracing/tests/BUILD.gn b/src/tracing/tests/BUILD.gn index fcb9bc2810544d..e44bb6b14cf741 100644 --- a/src/tracing/tests/BUILD.gn +++ b/src/tracing/tests/BUILD.gn @@ -14,6 +14,7 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") import("${chip_root}/build/chip/chip_test_suite.gni") import("${chip_root}/src/tracing/tracing_args.gni") diff --git a/src/tracing/tests/TestMetricEvents.cpp b/src/tracing/tests/TestMetricEvents.cpp index a0190265d57e0b..01c2c6e5a93eeb 100644 --- a/src/tracing/tests/TestMetricEvents.cpp +++ b/src/tracing/tests/TestMetricEvents.cpp @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include +#include + +#include #include #include diff --git a/src/tracing/tests/TestTracing.cpp b/src/tracing/tests/TestTracing.cpp index 254c6de5c78cb7..fa519a02163cbe 100644 --- a/src/tracing/tests/TestTracing.cpp +++ b/src/tracing/tests/TestTracing.cpp @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include +#include + +#include #include #include #include From 57ab3d312af5a7a367729d0dd6700a1233d93774 Mon Sep 17 00:00:00 2001 From: Jeff Feasel Date: Fri, 5 Jul 2024 19:03:18 +0000 Subject: [PATCH 15/16] Changes to MessagingContext member variable initialization in response to code review --- src/messaging/tests/MessagingContext.h | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/messaging/tests/MessagingContext.h b/src/messaging/tests/MessagingContext.h index 99959debd58dac..c4c6e1fda30389 100644 --- a/src/messaging/tests/MessagingContext.h +++ b/src/messaging/tests/MessagingContext.h @@ -94,7 +94,6 @@ class MessagingContext : public PlatformMemoryUser static constexpr System::Clock::Timeout kResponsiveActiveRetransTimeout = System::Clock::Milliseconds32(10); MessagingContext() : mpData(new MessagingContextData()) {} - // TODO Currently src/app/icd/server/tests is using MessagingContext as dependency. ~MessagingContext() { delete mpData; } // Whether Alice and Bob are initialized, must be called before Init @@ -175,23 +174,25 @@ class MessagingContext : public PlatformMemoryUser System::Layer & GetSystemLayer() { return mpData->mIOContext->GetSystemLayer(); } private: + // These members are encapsulated in a struct which is allocated upon construction of MessagingContext and freed upon + // destruction of MessagingContext. This is done to save stack space. struct MessagingContextData { MessagingContextData() : - mInitialized(false), mAliceAddress(Transport::PeerAddress::UDP(GetAddress(), CHIP_PORT + 1)), + mAliceAddress(Transport::PeerAddress::UDP(GetAddress(), CHIP_PORT + 1)), mBobAddress(LoopbackTransport::LoopbackPeer(mAliceAddress)) {} ~MessagingContextData() { EXPECT_FALSE(mInitialized); } bool mInitializeNodes = true; - bool mInitialized; + bool mInitialized = false; FabricTable mFabricTable; SessionManager mSessionManager; Messaging::ExchangeManager mExchangeManager; secure_channel::MessageCounterManager mMessageCounterManager; - IOContext * mIOContext; - TransportMgrBase * mTransport; // Only needed for InitFromExisting. + IOContext * mIOContext = nullptr; + TransportMgrBase * mTransport = nullptr; // Only needed for InitFromExisting. chip::TestPersistentStorageDelegate mStorage; // for SessionManagerInit chip::PersistentStorageOperationalKeystore mOpKeyStore; chip::Credentials::PersistentStorageOpCertStore mOpCertStore; From 7c35ed2181a10e8f5eece91e9295e57a31b2cc11 Mon Sep 17 00:00:00 2001 From: Jeff Feasel Date: Fri, 5 Jul 2024 19:29:31 +0000 Subject: [PATCH 16/16] Used std::unique_ptr for MessagingContext.mpData --- src/messaging/tests/MessagingContext.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/messaging/tests/MessagingContext.h b/src/messaging/tests/MessagingContext.h index c4c6e1fda30389..b5b16cbce73ab8 100644 --- a/src/messaging/tests/MessagingContext.h +++ b/src/messaging/tests/MessagingContext.h @@ -93,8 +93,7 @@ class MessagingContext : public PlatformMemoryUser static constexpr System::Clock::Timeout kResponsiveIdleRetransTimeout = System::Clock::Milliseconds32(10); static constexpr System::Clock::Timeout kResponsiveActiveRetransTimeout = System::Clock::Milliseconds32(10); - MessagingContext() : mpData(new MessagingContextData()) {} - ~MessagingContext() { delete mpData; } + MessagingContext() : mpData(std::make_unique()) {} // Whether Alice and Bob are initialized, must be called before Init void ConfigInitializeNodes(bool initializeNodes) { mpData->mInitializeNodes = initializeNodes; } @@ -210,7 +209,8 @@ class MessagingContext : public PlatformMemoryUser SessionHolder mSessionCharlieToDavid; SessionHolder mSessionDavidToCharlie; Optional mSessionBobToFriends; - } * mpData; + }; + std::unique_ptr mpData; }; // LoopbackMessagingContext enriches MessagingContext with an async loopback transport