diff --git a/src/BUILD.gn b/src/BUILD.gn index 5f7d6cc95ab6ba..d455a596b4e346 100644 --- a/src/BUILD.gn +++ b/src/BUILD.gn @@ -101,7 +101,6 @@ if (chip_build_tests) { "${chip_root}/src/lib/format/tests", "${chip_root}/src/lib/support/tests", "${chip_root}/src/protocols/secure_channel/tests", - "${chip_root}/src/protocols/secure_channel/tests:tests_nltest", "${chip_root}/src/system/tests", "${chip_root}/src/transport/tests", ] diff --git a/src/lib/support/tests/BUILD.gn b/src/lib/support/tests/BUILD.gn index 565eb85097d133..b8cdcfeb2e059f 100644 --- a/src/lib/support/tests/BUILD.gn +++ b/src/lib/support/tests/BUILD.gn @@ -19,6 +19,15 @@ import("//build_overrides/pigweed.gni") import("${chip_root}/build/chip/chip_test_suite.gni") +pw_source_set("pw-test-macros") { + output_dir = "${root_out_dir}/lib" + public_deps = [ + "$dir_pw_log:impl", + "$dir_pw_unit_test", + ] + sources = [ "ExtraPwTestMacros.h" ] +} + chip_test_suite("tests") { output_name = "libSupportTests" diff --git a/src/lib/support/tests/ExtraPwTestMacros.h b/src/lib/support/tests/ExtraPwTestMacros.h new file mode 100644 index 00000000000000..ab592800716592 --- /dev/null +++ b/src/lib/support/tests/ExtraPwTestMacros.h @@ -0,0 +1,56 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +/* + * Run Fixture's class function as a test. + * It is used to execute test cases that need to use private members of a particular class. + * Unlike the pigweed macro `FRIEND_TEST`, this approach allows you to define the entire + * test_fixture class as a friend, rather than having to define each testcase as a friend. + * + * @param test_fixture - the fixture class. + * + * @param test_name - the name of the test function. + * + * Example: + * class Foo // class to be tested + * { + * friend class TestCtx; + * private: + * bool privateFunction(); + * }; + * + * class TestCtx: public ::testing::Test + * { + * public: + * void testFunction(); + * }; + * + * TEST_F_FROM_FIXTURE(TestCtx, testFunction) + * { + * Foo foo; + * EXPECT_TRUE(foo.privateFunction()); + * } + * + */ +#define TEST_F_FROM_FIXTURE(test_fixture, test_name) \ + TEST_F(test_fixture, test_name) \ + { \ + test_name(); \ + } \ + void test_fixture::test_name() diff --git a/src/protocols/secure_channel/tests/BUILD.gn b/src/protocols/secure_channel/tests/BUILD.gn index 371937c4297b7b..0760998e818422 100644 --- a/src/protocols/secure_channel/tests/BUILD.gn +++ b/src/protocols/secure_channel/tests/BUILD.gn @@ -1,6 +1,5 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") import("${chip_root}/src/app/icd/icd.gni") @@ -8,32 +7,9 @@ chip_test_suite("tests") { output_name = "libSecureChannelTests" test_sources = [ + "TestCASESession.cpp", "TestCheckInCounter.cpp", "TestCheckinMsg.cpp", - ] - - sources = [ "CheckIn_Message_test_vectors.h" ] - - cflags = [ "-Wconversion" ] - public_deps = [ - "${chip_root}/src/app/icd/server:icd-server-config", - "${chip_root}/src/credentials/tests:cert_test_vectors", - "${chip_root}/src/lib/core", - "${chip_root}/src/lib/support", - "${chip_root}/src/lib/support:test_utils", - "${chip_root}/src/lib/support:testing", - "${chip_root}/src/protocols/secure_channel", - "${chip_root}/src/protocols/secure_channel:check-in-counter", - "${dir_pw_unit_test}", - ] -} - -chip_test_suite_using_nltest("tests_nltest") { - # Renamed ouput during the transition away from nltest - output_name = "libSecureChannelTestsNL" - - test_sources = [ - "TestCASESession.cpp", "TestDefaultSessionResumptionStorage.cpp", "TestPASESession.cpp", "TestPairingSession.cpp", @@ -44,22 +20,26 @@ chip_test_suite_using_nltest("tests_nltest") { # "TestMessageCounterManager.cpp", ] + sources = [ "CheckIn_Message_test_vectors.h" ] + + cflags = [ "-Wconversion" ] public_deps = [ + "${chip_root}/src/app/icd/server:icd-server-config", + "${chip_root}/src/credentials/tests:cert_test_vectors", "${chip_root}/src/crypto/tests:tests.lib", "${chip_root}/src/lib/core", "${chip_root}/src/lib/support", "${chip_root}/src/lib/support:test_utils", "${chip_root}/src/lib/support:testing", - "${chip_root}/src/lib/support:testing_nlunit", + "${chip_root}/src/lib/support/tests:pw-test-macros", "${chip_root}/src/messaging/tests:helpers", "${chip_root}/src/protocols", "${chip_root}/src/protocols/secure_channel", + "${chip_root}/src/protocols/secure_channel:check-in-counter", "${chip_root}/src/transport/raw/tests:helpers", - "${nlunit_test_root}:nlunit-test", + "${dir_pw_unit_test}", ] - cflags = [ "-Wconversion" ] - if (chip_enable_icd_server) { public_deps += [ "${chip_root}/src/app/icd/server:configuration-data" ] } diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 68d6ddd177eeb8..24aaffce0dbcb4 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -34,10 +35,8 @@ #include #include #include -#include -#include +#include #include -#include #include #include #include @@ -55,9 +54,9 @@ using namespace chip::Protocols; using namespace chip::Crypto; namespace chip { -namespace { +class TestCASESecurePairingDelegate; -class TestContext : public Test::LoopbackMessagingContext +class TestCASESession : public Test::LoopbackMessagingContext, public ::testing::Test { public: // Performs shared setup for all tests in the test suite @@ -70,16 +69,23 @@ class TestContext : public Test::LoopbackMessagingContext ConfigInitializeNodes(false); chip::Test::LoopbackMessagingContext::SetUp(); } + virtual void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } + + void ServiceEvents(); + void SecurePairingHandshakeTestCommon(SessionManager & sessionManager, CASESession & pairingCommissioner, + TestCASESecurePairingDelegate & delegateCommissioner); + + void SimulateUpdateNOCInvalidatePendingEstablishment(); }; -void ServiceEvents(TestContext & ctx) +void TestCASESession::ServiceEvents() { // Takes a few rounds of this because handling IO messages may schedule work, // and scheduled work may queue messages for sending... for (int i = 0; i < 3; ++i) { - ctx.DrainAndServiceIO(); + DrainAndServiceIO(); chip::DeviceLayer::PlatformMgr().ScheduleWork( [](intptr_t) -> void { chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); }, (intptr_t) nullptr); @@ -90,12 +96,11 @@ void ServiceEvents(TestContext & ctx) class TemporarySessionManager { public: - TemporarySessionManager(nlTestSuite * suite, TestContext & ctx) : mCtx(ctx) + TemporarySessionManager(TestCASESession & ctx) : mCtx(ctx) { - NL_TEST_ASSERT(suite, - CHIP_NO_ERROR == - mSessionManager.Init(&ctx.GetSystemLayer(), &ctx.GetTransportMgr(), &ctx.GetMessageCounterManager(), - &mStorage, &ctx.GetFabricTable(), ctx.GetSessionKeystore())); + EXPECT_EQ(CHIP_NO_ERROR, + mSessionManager.Init(&ctx.GetSystemLayer(), &ctx.GetTransportMgr(), &ctx.GetMessageCounterManager(), &mStorage, + &ctx.GetFabricTable(), ctx.GetSessionKeystore())); // The setup here is really weird: we are using one session manager for // the actual messages we send (the PASE handshake, so the // unauthenticated sessions) and a different one for allocating the PASE @@ -115,7 +120,7 @@ class TemporarySessionManager operator SessionManager &() { return mSessionManager; } private: - TestContext & mCtx; + TestCASESession & mCtx; TestPersistentStorageDelegate mStorage; SessionManager mSessionManager; }; @@ -334,22 +339,22 @@ CHIP_ERROR InitCredentialSets() return CHIP_NO_ERROR; } -void TestContext::SetUpTestSuite() +void TestCASESession::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()); - VerifyOrDieWithMsg((err = InitFabricTable(gCommissionerFabrics, &gCommissionerStorageDelegate, /* opKeyStore = */ nullptr, - &gCommissionerOpCertStore)) == CHIP_NO_ERROR, - AppServer, "InitFabricTable failed: %" CHIP_ERROR_FORMAT, err.Format()); - VerifyOrDieWithMsg((err = InitCredentialSets()) == CHIP_NO_ERROR, AppServer, "InitCredentialSets failed: %" CHIP_ERROR_FORMAT, - err.Format()); + + ASSERT_EQ(chip::DeviceLayer::PlatformMgr().InitChipStack(), CHIP_NO_ERROR); + + ASSERT_EQ( + InitFabricTable(gCommissionerFabrics, &gCommissionerStorageDelegate, /* opKeyStore = */ nullptr, &gCommissionerOpCertStore), + CHIP_NO_ERROR); + + ASSERT_EQ(InitCredentialSets(), CHIP_NO_ERROR); + chip::DeviceLayer::SetSystemLayerForTesting(&GetSystemLayer()); } -void TestContext::TearDownTestSuite() +void TestCASESession::TearDownTestSuite() { chip::DeviceLayer::SetSystemLayerForTesting(nullptr); gDeviceOperationalKeystore.Shutdown(); @@ -362,52 +367,27 @@ void TestContext::TearDownTestSuite() LoopbackMessagingContext::TearDownTestSuite(); } -} // anonymous namespace - -// Specifically for SimulateUpdateNOCInvalidatePendingEstablishment, we need it to be static so that the class below can -// be a friend to CASESession so that test can get access to CASESession::State and test method that are not public. To -// keep the rest of this file consistent we brought all other tests into this class. -class TestCASESession +TEST_F(TestCASESession, SecurePairingWaitTest) { -public: - static void SecurePairingWaitTest(nlTestSuite * inSuite, void * inContext); - static void SecurePairingStartTest(nlTestSuite * inSuite, void * inContext); - static void SecurePairingHandshakeTest(nlTestSuite * inSuite, void * inContext); - static void SecurePairingHandshakeServerTest(nlTestSuite * inSuite, void * inContext); - static void ClientReceivesBusyTest(nlTestSuite * inSuite, void * inContext); - static void Sigma1ParsingTest(nlTestSuite * inSuite, void * inContext); - static void DestinationIdTest(nlTestSuite * inSuite, void * inContext); - static void SessionResumptionStorage(nlTestSuite * inSuite, void * inContext); -#if CONFIG_BUILD_FOR_HOST_UNIT_TEST - static void SimulateUpdateNOCInvalidatePendingEstablishment(nlTestSuite * inSuite, void * inContext); -#endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST - static void Sigma1BadDestinationIdTest(nlTestSuite * inSuite, void * inContext); -}; - -void TestCASESession::SecurePairingWaitTest(nlTestSuite * inSuite, void * inContext) -{ - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); - + TemporarySessionManager sessionManager(*this); // Test all combinations of invalid parameters TestCASESecurePairingDelegate delegate; - FabricTable fabrics; + // Making this static to reduce stack usage, as some platforms have limits on stack size. + static FabricTable fabrics; CASESession caseSession; - NL_TEST_ASSERT(inSuite, caseSession.GetSecureSessionType() == SecureSession::Type::kCASE); + EXPECT_EQ(caseSession.GetSecureSessionType(), SecureSession::Type::kCASE); caseSession.SetGroupDataProvider(&gDeviceGroupDataProvider); - NL_TEST_ASSERT(inSuite, - caseSession.PrepareForSessionEstablishment(sessionManager, nullptr, nullptr, nullptr, nullptr, ScopedNodeId(), - Optional::Missing()) == - CHIP_ERROR_INVALID_ARGUMENT); - NL_TEST_ASSERT(inSuite, - caseSession.PrepareForSessionEstablishment(sessionManager, nullptr, nullptr, nullptr, &delegate, ScopedNodeId(), - Optional::Missing()) == - CHIP_ERROR_INVALID_ARGUMENT); - NL_TEST_ASSERT(inSuite, - caseSession.PrepareForSessionEstablishment(sessionManager, &fabrics, nullptr, nullptr, &delegate, ScopedNodeId(), - Optional::Missing()) == CHIP_NO_ERROR); + EXPECT_EQ(caseSession.PrepareForSessionEstablishment(sessionManager, nullptr, nullptr, nullptr, nullptr, ScopedNodeId(), + Optional::Missing()), + CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(caseSession.PrepareForSessionEstablishment(sessionManager, nullptr, nullptr, nullptr, &delegate, ScopedNodeId(), + Optional::Missing()), + CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(caseSession.PrepareForSessionEstablishment(sessionManager, &fabrics, nullptr, nullptr, &delegate, ScopedNodeId(), + Optional::Missing()), + CHIP_NO_ERROR); // Calling Clear() here since ASAN will have an issue if FabricTable destructor is called before CASESession's // destructor. We could reorder FabricTable and CaseSession, but this makes it a little more clear what we are @@ -415,42 +395,37 @@ void TestCASESession::SecurePairingWaitTest(nlTestSuite * inSuite, void * inCont caseSession.Clear(); } -void TestCASESession::SecurePairingStartTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, SecurePairingStartTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); - + TemporarySessionManager sessionManager(*this); // Test all combinations of invalid parameters TestCASESecurePairingDelegate delegate; CASESession pairing; pairing.SetGroupDataProvider(&gCommissionerGroupDataProvider); - ExchangeContext * context = ctx.NewUnauthenticatedExchangeToBob(&pairing); + ExchangeContext * context = NewUnauthenticatedExchangeToBob(&pairing); - NL_TEST_ASSERT(inSuite, - pairing.EstablishSession(sessionManager, nullptr, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, nullptr, - nullptr, nullptr, nullptr, - Optional::Missing()) != CHIP_NO_ERROR); - ServiceEvents(ctx); + EXPECT_NE(pairing.EstablishSession(sessionManager, nullptr, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, nullptr, + nullptr, nullptr, nullptr, Optional::Missing()), + CHIP_NO_ERROR); + ServiceEvents(); - NL_TEST_ASSERT(inSuite, - pairing.EstablishSession(sessionManager, &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, nullptr, nullptr, nullptr, nullptr, - Optional::Missing()) != CHIP_NO_ERROR); - ServiceEvents(ctx); + EXPECT_NE(pairing.EstablishSession(sessionManager, &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, + nullptr, nullptr, nullptr, nullptr, Optional::Missing()), + CHIP_NO_ERROR); + ServiceEvents(); - NL_TEST_ASSERT(inSuite, - pairing.EstablishSession(sessionManager, &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, context, nullptr, nullptr, - &delegate, Optional::Missing()) == CHIP_NO_ERROR); - ServiceEvents(ctx); + EXPECT_EQ(pairing.EstablishSession(sessionManager, &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, + context, nullptr, nullptr, &delegate, Optional::Missing()), + CHIP_NO_ERROR); + ServiceEvents(); - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); // There should have been two message sent: Sigma1 and an ack. - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == 2); + EXPECT_EQ(loopback.mSentMessageCount, 2u); - ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); - NL_TEST_ASSERT(inSuite, rm->TestGetCountRetransTable() == 0); + ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); loopback.mMessageSendError = CHIP_ERROR_BAD_REQUEST; @@ -459,22 +434,19 @@ void TestCASESession::SecurePairingStartTest(nlTestSuite * inSuite, void * inCon loopback.mSentMessageCount = 0; loopback.mMessageSendError = CHIP_ERROR_BAD_REQUEST; - ExchangeContext * context1 = ctx.NewUnauthenticatedExchangeToBob(&pairing1); + ExchangeContext * context1 = NewUnauthenticatedExchangeToBob(&pairing1); - NL_TEST_ASSERT(inSuite, - pairing1.EstablishSession( - sessionManager, &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, context1, - nullptr, nullptr, &delegate, Optional::Missing()) == CHIP_ERROR_BAD_REQUEST); - ServiceEvents(ctx); + EXPECT_EQ(pairing1.EstablishSession(sessionManager, &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, + context1, nullptr, nullptr, &delegate, Optional::Missing()), + CHIP_ERROR_BAD_REQUEST); + ServiceEvents(); loopback.mMessageSendError = CHIP_NO_ERROR; } -void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, SessionManager & sessionManager, - CASESession & pairingCommissioner, TestCASESecurePairingDelegate & delegateCommissioner) +void TestCASESession::SecurePairingHandshakeTestCommon(SessionManager & sessionManager, CASESession & pairingCommissioner, + TestCASESecurePairingDelegate & delegateCommissioner) { - TestContext & ctx = *reinterpret_cast(inContext); - // Test all combinations of invalid parameters TestCASESecurePairingDelegate delegateAccessory; CASESession pairingAccessory; @@ -483,39 +455,36 @@ void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, S ReliableMessageProtocolConfig nonSleepyCommissionerRmpConfig( System::Clock::Milliseconds32(5000), System::Clock::Milliseconds32(300), System::Clock::Milliseconds16(4000)); - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.mSentMessageCount = 0; - NL_TEST_ASSERT(inSuite, - ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::CASE_Sigma1, - &pairingAccessory) == CHIP_NO_ERROR); + EXPECT_EQ(GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::CASE_Sigma1, + &pairingAccessory), + CHIP_NO_ERROR); - ExchangeContext * contextCommissioner = ctx.NewUnauthenticatedExchangeToBob(&pairingCommissioner); + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(&pairingCommissioner); pairingAccessory.SetGroupDataProvider(&gDeviceGroupDataProvider); - NL_TEST_ASSERT(inSuite, - pairingAccessory.PrepareForSessionEstablishment(sessionManager, &gDeviceFabrics, nullptr, nullptr, - &delegateAccessory, ScopedNodeId(), - MakeOptional(verySleepyAccessoryRmpConfig)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - pairingCommissioner.EstablishSession(sessionManager, &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner, - nullptr, nullptr, &delegateCommissioner, - MakeOptional(nonSleepyCommissionerRmpConfig)) == CHIP_NO_ERROR); - ServiceEvents(ctx); - - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == sTestCaseMessageCount); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, pairingAccessory.GetRemoteMRPConfig().mIdleRetransTimeout == System::Clock::Milliseconds32(5000)); - NL_TEST_ASSERT(inSuite, pairingAccessory.GetRemoteMRPConfig().mActiveRetransTimeout == System::Clock::Milliseconds32(300)); - NL_TEST_ASSERT(inSuite, pairingAccessory.GetRemoteMRPConfig().mActiveThresholdTime == System::Clock::Milliseconds16(4000)); - NL_TEST_ASSERT(inSuite, pairingCommissioner.GetRemoteMRPConfig().mIdleRetransTimeout == System::Clock::Milliseconds32(360000)); - NL_TEST_ASSERT(inSuite, - pairingCommissioner.GetRemoteMRPConfig().mActiveRetransTimeout == System::Clock::Milliseconds32(100000)); - NL_TEST_ASSERT(inSuite, pairingCommissioner.GetRemoteMRPConfig().mActiveThresholdTime == System::Clock::Milliseconds16(300)); + EXPECT_EQ(pairingAccessory.PrepareForSessionEstablishment(sessionManager, &gDeviceFabrics, nullptr, nullptr, &delegateAccessory, + ScopedNodeId(), MakeOptional(verySleepyAccessoryRmpConfig)), + CHIP_NO_ERROR); + EXPECT_EQ(pairingCommissioner.EstablishSession( + sessionManager, &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner, + nullptr, nullptr, &delegateCommissioner, MakeOptional(nonSleepyCommissionerRmpConfig)), + CHIP_NO_ERROR); + ServiceEvents(); + + EXPECT_EQ(loopback.mSentMessageCount, sTestCaseMessageCount); + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 1u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 1u); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 0u); + EXPECT_EQ(pairingAccessory.GetRemoteMRPConfig().mIdleRetransTimeout, System::Clock::Milliseconds32(5000)); + EXPECT_EQ(pairingAccessory.GetRemoteMRPConfig().mActiveRetransTimeout, System::Clock::Milliseconds32(300)); + EXPECT_EQ(pairingAccessory.GetRemoteMRPConfig().mActiveThresholdTime, System::Clock::Milliseconds16(4000)); + EXPECT_EQ(pairingCommissioner.GetRemoteMRPConfig().mIdleRetransTimeout, System::Clock::Milliseconds32(360000)); + EXPECT_EQ(pairingCommissioner.GetRemoteMRPConfig().mActiveRetransTimeout, System::Clock::Milliseconds32(100000)); + EXPECT_EQ(pairingCommissioner.GetRemoteMRPConfig().mActiveThresholdTime, System::Clock::Milliseconds16(300)); #if CONFIG_BUILD_FOR_HOST_UNIT_TEST // Confirming that FabricTable sending a notification that fabric was updated doesn't affect // already established connections. @@ -523,26 +492,24 @@ void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, S // This is compiled for host tests which is enough test coverage gCommissionerFabrics.SendUpdateFabricNotificationForTest(gCommissionerFabricIndex); gDeviceFabrics.SendUpdateFabricNotificationForTest(gDeviceFabricIndex); - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == sTestCaseMessageCount); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 0); + EXPECT_EQ(loopback.mSentMessageCount, sTestCaseMessageCount); + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 1u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 1u); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 0u); #endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST } -void TestCASESession::SecurePairingHandshakeTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, SecurePairingHandshakeTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); - + TemporarySessionManager sessionManager(*this); TestCASESecurePairingDelegate delegateCommissioner; CASESession pairingCommissioner; pairingCommissioner.SetGroupDataProvider(&gCommissionerGroupDataProvider); - SecurePairingHandshakeTestCommon(inSuite, inContext, sessionManager, pairingCommissioner, delegateCommissioner); + SecurePairingHandshakeTestCommon(sessionManager, pairingCommissioner, delegateCommissioner); } -void TestCASESession::SecurePairingHandshakeServerTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, SecurePairingHandshakeServerTest) { // TODO: Add cases for mismatching IPK config between initiator/responder @@ -551,47 +518,43 @@ void TestCASESession::SecurePairingHandshakeServerTest(nlTestSuite * inSuite, vo auto * pairingCommissioner = chip::Platform::New(); pairingCommissioner->SetGroupDataProvider(&gCommissionerGroupDataProvider); - TestContext & ctx = *reinterpret_cast(inContext); - - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.mSentMessageCount = 0; // Use the same session manager on both CASE client and server sides to validate that both // components may work simultaneously on a single device. - NL_TEST_ASSERT(inSuite, - gPairingServer.ListenForSessionEstablishment(&ctx.GetExchangeManager(), &ctx.GetSecureSessionManager(), - &gDeviceFabrics, nullptr, nullptr, - &gDeviceGroupDataProvider) == CHIP_NO_ERROR); + EXPECT_EQ(gPairingServer.ListenForSessionEstablishment(&GetExchangeManager(), &GetSecureSessionManager(), &gDeviceFabrics, + nullptr, nullptr, &gDeviceGroupDataProvider), + CHIP_NO_ERROR); - ExchangeContext * contextCommissioner = ctx.NewUnauthenticatedExchangeToBob(pairingCommissioner); + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(pairingCommissioner); - NL_TEST_ASSERT(inSuite, - pairingCommissioner->EstablishSession(ctx.GetSecureSessionManager(), &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner, - nullptr, nullptr, &delegateCommissioner, - Optional::Missing()) == CHIP_NO_ERROR); - ServiceEvents(ctx); + EXPECT_EQ(pairingCommissioner->EstablishSession( + GetSecureSessionManager(), &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, + contextCommissioner, nullptr, nullptr, &delegateCommissioner, Optional::Missing()), + CHIP_NO_ERROR); + ServiceEvents(); - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == sTestCaseMessageCount); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 1); + EXPECT_EQ(loopback.mSentMessageCount, sTestCaseMessageCount); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 1u); // Validate that secure session is created SessionHolder & holder = delegateCommissioner.GetSessionHolder(); - NL_TEST_ASSERT(inSuite, bool(holder)); + EXPECT_TRUE(bool(holder)); - NL_TEST_ASSERT(inSuite, (holder->GetPeer() == chip::ScopedNodeId{ Node01_01, gCommissionerFabricIndex })); + EXPECT_EQ(holder->GetPeer(), (chip::ScopedNodeId{ Node01_01, gCommissionerFabricIndex })); auto * pairingCommissioner1 = chip::Platform::New(); pairingCommissioner1->SetGroupDataProvider(&gCommissionerGroupDataProvider); - ExchangeContext * contextCommissioner1 = ctx.NewUnauthenticatedExchangeToBob(pairingCommissioner1); + ExchangeContext * contextCommissioner1 = NewUnauthenticatedExchangeToBob(pairingCommissioner1); - NL_TEST_ASSERT(inSuite, - pairingCommissioner1->EstablishSession(ctx.GetSecureSessionManager(), &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner1, - nullptr, nullptr, &delegateCommissioner, - Optional::Missing()) == CHIP_NO_ERROR); + EXPECT_EQ(pairingCommissioner1->EstablishSession(GetSecureSessionManager(), &gCommissionerFabrics, + ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner1, + nullptr, nullptr, &delegateCommissioner, + Optional::Missing()), + CHIP_NO_ERROR); - ServiceEvents(ctx); + ServiceEvents(); chip::Platform::Delete(pairingCommissioner); chip::Platform::Delete(pairingCommissioner1); @@ -599,52 +562,49 @@ void TestCASESession::SecurePairingHandshakeServerTest(nlTestSuite * inSuite, vo gPairingServer.Shutdown(); } -void TestCASESession::ClientReceivesBusyTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, ClientReceivesBusyTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); - + TemporarySessionManager sessionManager(*this); TestCASESecurePairingDelegate delegateCommissioner1, delegateCommissioner2; CASESession pairingCommissioner1, pairingCommissioner2; pairingCommissioner1.SetGroupDataProvider(&gCommissionerGroupDataProvider); pairingCommissioner2.SetGroupDataProvider(&gCommissionerGroupDataProvider); - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.mSentMessageCount = 0; - NL_TEST_ASSERT(inSuite, - gPairingServer.ListenForSessionEstablishment(&ctx.GetExchangeManager(), &ctx.GetSecureSessionManager(), - &gDeviceFabrics, nullptr, nullptr, - &gDeviceGroupDataProvider) == CHIP_NO_ERROR); + EXPECT_EQ(gPairingServer.ListenForSessionEstablishment(&GetExchangeManager(), &GetSecureSessionManager(), &gDeviceFabrics, + nullptr, nullptr, &gDeviceGroupDataProvider), + CHIP_NO_ERROR); - ExchangeContext * contextCommissioner1 = ctx.NewUnauthenticatedExchangeToBob(&pairingCommissioner1); - ExchangeContext * contextCommissioner2 = ctx.NewUnauthenticatedExchangeToBob(&pairingCommissioner2); + ExchangeContext * contextCommissioner1 = NewUnauthenticatedExchangeToBob(&pairingCommissioner1); + ExchangeContext * contextCommissioner2 = NewUnauthenticatedExchangeToBob(&pairingCommissioner2); - NL_TEST_ASSERT(inSuite, - pairingCommissioner1.EstablishSession(sessionManager, &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner1, - nullptr, nullptr, &delegateCommissioner1, NullOptional) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - pairingCommissioner2.EstablishSession(sessionManager, &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner2, - nullptr, nullptr, &delegateCommissioner2, NullOptional) == CHIP_NO_ERROR); + EXPECT_EQ(pairingCommissioner1.EstablishSession(sessionManager, &gCommissionerFabrics, + ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner1, + nullptr, nullptr, &delegateCommissioner1, NullOptional), + CHIP_NO_ERROR); + EXPECT_EQ(pairingCommissioner2.EstablishSession(sessionManager, &gCommissionerFabrics, + ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner2, + nullptr, nullptr, &delegateCommissioner2, NullOptional), + CHIP_NO_ERROR); - ServiceEvents(ctx); + ServiceEvents(); // We should have one full handshake and one Sigma1 + Busy + ack. If that // ever changes (e.g. because our server starts supporting multiple parallel // handshakes), this test needs to be fixed so that the server is still // responding BUSY to the client. - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == sTestCaseMessageCount + 3); - NL_TEST_ASSERT(inSuite, delegateCommissioner1.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner2.mNumPairingComplete == 0); + EXPECT_EQ(loopback.mSentMessageCount, sTestCaseMessageCount + 3); + EXPECT_EQ(delegateCommissioner1.mNumPairingComplete, 1u); + EXPECT_EQ(delegateCommissioner2.mNumPairingComplete, 0u); - NL_TEST_ASSERT(inSuite, delegateCommissioner1.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner2.mNumPairingErrors == 1); + EXPECT_EQ(delegateCommissioner1.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner2.mNumPairingErrors, 1u); - NL_TEST_ASSERT(inSuite, delegateCommissioner1.mNumBusyResponses == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner2.mNumBusyResponses == 1); + EXPECT_EQ(delegateCommissioner1.mNumBusyResponses, 0u); + EXPECT_EQ(delegateCommissioner2.mNumBusyResponses, 1u); gPairingServer.Shutdown(); } @@ -673,7 +633,7 @@ struct Sigma1Params static constexpr bool expectSuccess = true; }; -void TestCASESession::DestinationIdTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, DestinationIdTest) { // Validate example test vector from CASE section of spec @@ -708,20 +668,20 @@ void TestCASESession::DestinationIdTest(nlTestSuite * inSuite, void * inContext) CHIP_ERROR err = GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, kNodeIdFromSpec, destinationIdSpan); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == err); - NL_TEST_ASSERT(inSuite, destinationIdSpan.size() == sizeof(destinationIdBuf)); - NL_TEST_ASSERT(inSuite, destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(destinationIdSpan.size(), sizeof(destinationIdBuf)); + EXPECT_TRUE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); memset(destinationIdSpan.data(), 0, destinationIdSpan.size()); // Test changing input: should yield different - err = GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), - ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, - kNodeIdFromSpec + 1, // <--- Change node ID - destinationIdSpan); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == err); - NL_TEST_ASSERT(inSuite, destinationIdSpan.size() == sizeof(destinationIdBuf)); - NL_TEST_ASSERT(inSuite, !destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); + EXPECT_EQ(GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), + ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, + kNodeIdFromSpec + 1, // <--- Change node ID + destinationIdSpan), + CHIP_NO_ERROR); + EXPECT_EQ(destinationIdSpan.size(), sizeof(destinationIdBuf)); + EXPECT_FALSE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); } template @@ -776,12 +736,11 @@ static CHIP_ERROR EncodeSigma1(MutableByteSpan & buf) } // A macro, so we can tell which test failed based on line number. -#define TestSigma1Parsing(inSuite, mem, bufferSize, params) \ +#define TestSigma1Parsing(mem, bufferSize, params) \ do \ { \ MutableByteSpan buf(mem.Get(), bufferSize); \ - CHIP_ERROR err = EncodeSigma1(buf); \ - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); \ + EXPECT_EQ(EncodeSigma1(buf), CHIP_NO_ERROR); \ \ TLV::ContiguousBufferTLVReader reader; \ reader.Init(buf); \ @@ -794,12 +753,12 @@ static CHIP_ERROR EncodeSigma1(MutableByteSpan & buf) ByteSpan resumptionId; \ ByteSpan initiatorResumeMIC; \ CASESession session; \ - err = session.ParseSigma1(reader, initiatorRandom, initiatorSessionId, destinationId, initiatorEphPubKey, \ - resumptionRequested, resumptionId, initiatorResumeMIC); \ - NL_TEST_ASSERT(inSuite, (err == CHIP_NO_ERROR) == params::expectSuccess); \ + EXPECT_EQ(session.ParseSigma1(reader, initiatorRandom, initiatorSessionId, destinationId, initiatorEphPubKey, \ + resumptionRequested, resumptionId, initiatorResumeMIC) == CHIP_NO_ERROR, \ + params::expectSuccess); \ if (params::expectSuccess) \ { \ - NL_TEST_ASSERT(inSuite, resumptionRequested == (params::resumptionIdLen != 0 && params::initiatorResumeMICLen != 0)); \ + EXPECT_EQ(resumptionRequested, params::resumptionIdLen != 0 && params::initiatorResumeMICLen != 0); \ /* Add other verification tests here as desired */ \ } \ } while (0) @@ -889,30 +848,29 @@ struct Sigma1SessionIdTooBig : public BadSigma1ParamsBase static constexpr uint32_t initiatorSessionId = UINT16_MAX + 1; }; -void TestCASESession::Sigma1ParsingTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, Sigma1ParsingTest) { // 1280 bytes must be enough by definition. constexpr size_t bufferSize = 1280; chip::Platform::ScopedMemoryBuffer mem; - NL_TEST_ASSERT(inSuite, mem.Calloc(bufferSize)); - - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1Params); - - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1NoStructEnd); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1WrongTags); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooLongRandom); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooShortRandom); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooLongDest); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooShortDest); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooLongPubkey); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooShortPubkey); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1WithResumption); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooLongResumptionId); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooShortResumptionId); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooLongResumeMIC); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooShortResumeMIC); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1SessionIdMax); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1SessionIdTooBig); + EXPECT_TRUE(mem.Calloc(bufferSize)); + + TestSigma1Parsing(mem, bufferSize, Sigma1Params); + TestSigma1Parsing(mem, bufferSize, Sigma1NoStructEnd); + TestSigma1Parsing(mem, bufferSize, Sigma1WrongTags); + TestSigma1Parsing(mem, bufferSize, Sigma1TooLongRandom); + TestSigma1Parsing(mem, bufferSize, Sigma1TooShortRandom); + TestSigma1Parsing(mem, bufferSize, Sigma1TooLongDest); + TestSigma1Parsing(mem, bufferSize, Sigma1TooShortDest); + TestSigma1Parsing(mem, bufferSize, Sigma1TooLongPubkey); + TestSigma1Parsing(mem, bufferSize, Sigma1TooShortPubkey); + TestSigma1Parsing(mem, bufferSize, Sigma1WithResumption); + TestSigma1Parsing(mem, bufferSize, Sigma1TooLongResumptionId); + TestSigma1Parsing(mem, bufferSize, Sigma1TooShortResumptionId); + TestSigma1Parsing(mem, bufferSize, Sigma1TooLongResumeMIC); + TestSigma1Parsing(mem, bufferSize, Sigma1TooShortResumeMIC); + TestSigma1Parsing(mem, bufferSize, Sigma1SessionIdMax); + TestSigma1Parsing(mem, bufferSize, Sigma1SessionIdTooBig); } struct SessionResumptionTestStorage : SessionResumptionStorage @@ -962,7 +920,7 @@ struct SessionResumptionTestStorage : SessionResumptionStorage Crypto::P256ECDHDerivedSecret * mSharedSecret = nullptr; }; -void TestCASESession::SessionResumptionStorage(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, SessionResumptionStorage) { // Test the SessionResumptionStorage external interface. // @@ -973,7 +931,6 @@ void TestCASESession::SessionResumptionStorage(nlTestSuite * inSuite, void * inC // if the peers have mismatched session resumption information, we should // fall back to CASE. - TestContext & ctx = *reinterpret_cast(inContext); TestCASESecurePairingDelegate delegateCommissioner; chip::SessionResumptionStorage::ResumptionIdStorage resumptionIdA; chip::SessionResumptionStorage::ResumptionIdStorage resumptionIdB; @@ -982,19 +939,19 @@ void TestCASESession::SessionResumptionStorage(nlTestSuite * inSuite, void * inC // Create our fabric-scoped node IDs. const FabricInfo * fabricInfo = gCommissionerFabrics.FindFabricWithIndex(gCommissionerFabricIndex); - NL_TEST_ASSERT(inSuite, fabricInfo != nullptr); + ASSERT_NE(fabricInfo, nullptr); ScopedNodeId initiator = fabricInfo->GetScopedNodeIdForNode(Node01_02); ScopedNodeId responder = fabricInfo->GetScopedNodeIdForNode(Node01_01); // Generate a resumption IDs. - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(resumptionIdA.data(), resumptionIdA.size())); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(resumptionIdB.data(), resumptionIdB.size())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(resumptionIdA.data(), resumptionIdA.size()), CHIP_NO_ERROR); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(resumptionIdB.data(), resumptionIdB.size()), CHIP_NO_ERROR); // Generate a shared secrets. sharedSecretA.SetLength(sharedSecretA.Capacity()); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(sharedSecretA.Bytes(), sharedSecretA.Length())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(sharedSecretA.Bytes(), sharedSecretA.Length()), CHIP_NO_ERROR); sharedSecretB.SetLength(sharedSecretB.Capacity()); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(sharedSecretB.Bytes(), sharedSecretB.Length())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(sharedSecretB.Bytes(), sharedSecretB.Length()), CHIP_NO_ERROR); struct { @@ -1034,38 +991,37 @@ void TestCASESession::SessionResumptionStorage(nlTestSuite * inSuite, void * inC }, }; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); for (size_t i = 0; i < sizeof(testVectors) / sizeof(testVectors[0]); ++i) { auto * pairingCommissioner = chip::Platform::New(); pairingCommissioner->SetGroupDataProvider(&gCommissionerGroupDataProvider); loopback.mSentMessageCount = 0; - NL_TEST_ASSERT(inSuite, - gPairingServer.ListenForSessionEstablishment(&ctx.GetExchangeManager(), &ctx.GetSecureSessionManager(), - &gDeviceFabrics, &testVectors[i].responderStorage, nullptr, - &gDeviceGroupDataProvider) == CHIP_NO_ERROR); - ExchangeContext * contextCommissioner = ctx.NewUnauthenticatedExchangeToBob(pairingCommissioner); + EXPECT_EQ(gPairingServer.ListenForSessionEstablishment(&GetExchangeManager(), &GetSecureSessionManager(), &gDeviceFabrics, + &testVectors[i].responderStorage, nullptr, + &gDeviceGroupDataProvider), + CHIP_NO_ERROR); + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(pairingCommissioner); auto establishmentReturnVal = pairingCommissioner->EstablishSession( - ctx.GetSecureSessionManager(), &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, + GetSecureSessionManager(), &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner, &testVectors[i].initiatorStorage, nullptr, &delegateCommissioner, Optional::Missing()); - ServiceEvents(ctx); - NL_TEST_ASSERT(inSuite, establishmentReturnVal == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == testVectors[i].expectedSentMessageCount); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == i + 1); + ServiceEvents(); + EXPECT_EQ(establishmentReturnVal, CHIP_NO_ERROR); + EXPECT_EQ(loopback.mSentMessageCount, testVectors[i].expectedSentMessageCount); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, i + 1); SessionHolder & holder = delegateCommissioner.GetSessionHolder(); - NL_TEST_ASSERT(inSuite, bool(holder)); - NL_TEST_ASSERT(inSuite, holder->GetPeer() == fabricInfo->GetScopedNodeIdForNode(Node01_01)); + EXPECT_TRUE(bool(holder)); + EXPECT_EQ(holder->GetPeer(), fabricInfo->GetScopedNodeIdForNode(Node01_01)); chip::Platform::Delete(pairingCommissioner); + gPairingServer.Shutdown(); } } #if CONFIG_BUILD_FOR_HOST_UNIT_TEST -void TestCASESession::SimulateUpdateNOCInvalidatePendingEstablishment(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestCASESession, SimulateUpdateNOCInvalidatePendingEstablishment) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); - + TemporarySessionManager sessionManager(*this); TestCASESecurePairingDelegate delegateCommissioner; CASESession pairingCommissioner; pairingCommissioner.SetGroupDataProvider(&gCommissionerGroupDataProvider); @@ -1073,70 +1029,65 @@ void TestCASESession::SimulateUpdateNOCInvalidatePendingEstablishment(nlTestSuit TestCASESecurePairingDelegate delegateAccessory; CASESession pairingAccessory; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.mSentMessageCount = 0; - NL_TEST_ASSERT(inSuite, - ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::CASE_Sigma1, - &pairingAccessory) == CHIP_NO_ERROR); + EXPECT_EQ(GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::CASE_Sigma1, + &pairingAccessory), + CHIP_NO_ERROR); // In order for all the test iterations below, we need to stop the CASE sigma handshake in the middle such // that the CASE session is in the process of being established. pairingCommissioner.SetStopSigmaHandshakeAt(MakeOptional(CASESession::State::kSentSigma1)); - ExchangeContext * contextCommissioner = ctx.NewUnauthenticatedExchangeToBob(&pairingCommissioner); + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(&pairingCommissioner); pairingAccessory.SetGroupDataProvider(&gDeviceGroupDataProvider); - NL_TEST_ASSERT(inSuite, - pairingAccessory.PrepareForSessionEstablishment( - sessionManager, &gDeviceFabrics, nullptr, nullptr, &delegateAccessory, ScopedNodeId(), - Optional::Missing()) == CHIP_NO_ERROR); + EXPECT_EQ(pairingAccessory.PrepareForSessionEstablishment(sessionManager, &gDeviceFabrics, nullptr, nullptr, &delegateAccessory, + ScopedNodeId(), Optional::Missing()), + CHIP_NO_ERROR); gDeviceFabrics.SendUpdateFabricNotificationForTest(gDeviceFabricIndex); - ServiceEvents(ctx); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); + ServiceEvents(); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); - NL_TEST_ASSERT(inSuite, - pairingCommissioner.EstablishSession(sessionManager, &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner, - nullptr, nullptr, &delegateCommissioner, - Optional::Missing()) == CHIP_NO_ERROR); - ServiceEvents(ctx); + EXPECT_EQ(pairingCommissioner.EstablishSession( + sessionManager, &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner, + nullptr, nullptr, &delegateCommissioner, Optional::Missing()), + CHIP_NO_ERROR); + ServiceEvents(); // At this point the CASESession is in the process of establishing. Confirm that there are no errors and there are session // has not been established. - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 0); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 0); + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 0u); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 0u); // Simulating an update to the Fabric NOC for gCommissionerFabrics fabric table. // Confirm that CASESession on commisioner side has reported an error. gCommissionerFabrics.SendUpdateFabricNotificationForTest(gCommissionerFabricIndex); - ServiceEvents(ctx); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 1); + ServiceEvents(); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 1u); // Simulating an update to the Fabric NOC for gDeviceFabrics fabric table. // Confirm that CASESession on accessory side has reported an error. gDeviceFabrics.SendUpdateFabricNotificationForTest(gDeviceFabricIndex); - ServiceEvents(ctx); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 1); + ServiceEvents(); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 1u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 1u); // Sanity check that pairing did not complete. - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 0); + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 0u); } #endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST -namespace { class ExpectErrorExchangeDelegate : public ExchangeDelegate { public: - ExpectErrorExchangeDelegate(nlTestSuite * suite, uint16_t expectedProtocolCode) : - mSuite(suite), mExpectedProtocolCode(expectedProtocolCode) - {} + ExpectErrorExchangeDelegate(uint16_t expectedProtocolCode) : mExpectedProtocolCode(expectedProtocolCode) {} private: CHIP_ERROR OnMessageReceived(ExchangeContext * ec, const PayloadHeader & payloadHeader, @@ -1144,15 +1095,14 @@ class ExpectErrorExchangeDelegate : public ExchangeDelegate { using namespace SecureChannel; - NL_TEST_ASSERT(mSuite, payloadHeader.HasMessageType(MsgType::StatusReport)); + EXPECT_TRUE(payloadHeader.HasMessageType(MsgType::StatusReport)); SecureChannel::StatusReport statusReport; - CHIP_ERROR err = statusReport.Parse(std::move(buf)); - NL_TEST_ASSERT(mSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(statusReport.Parse(std::move(buf)), CHIP_NO_ERROR); - NL_TEST_ASSERT(mSuite, statusReport.GetProtocolId() == SecureChannel::Id); - NL_TEST_ASSERT(mSuite, statusReport.GetGeneralCode() == GeneralStatusCode::kFailure); - NL_TEST_ASSERT(mSuite, statusReport.GetProtocolCode() == mExpectedProtocolCode); + EXPECT_EQ(statusReport.GetProtocolId(), SecureChannel::Id); + EXPECT_EQ(statusReport.GetGeneralCode(), GeneralStatusCode::kFailure); + EXPECT_EQ(statusReport.GetProtocolCode(), mExpectedProtocolCode); return CHIP_NO_ERROR; } @@ -1160,105 +1110,49 @@ class ExpectErrorExchangeDelegate : public ExchangeDelegate Messaging::ExchangeMessageDispatch & GetMessageDispatch() override { return SessionEstablishmentExchangeDispatch::Instance(); } - nlTestSuite * mSuite; uint16_t mExpectedProtocolCode; }; -} // anonymous namespace -void TestCASESession::Sigma1BadDestinationIdTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, Sigma1BadDestinationIdTest) { using SecureChannel::MsgType; - TestContext & ctx = *reinterpret_cast(inContext); - - SessionManager & sessionManager = ctx.GetSecureSessionManager(); + SessionManager & sessionManager = GetSecureSessionManager(); constexpr size_t bufferSize = 600; System::PacketBufferHandle data = chip::System::PacketBufferHandle::New(bufferSize); - NL_TEST_ASSERT(inSuite, !data.IsNull()); + ASSERT_FALSE(data.IsNull()); MutableByteSpan buf(data->Start(), data->AvailableDataLength()); // This uses a bogus destination id that is not going to match anything in practice. - CHIP_ERROR err = EncodeSigma1(buf); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(EncodeSigma1(buf), CHIP_NO_ERROR); data->SetDataLength(static_cast(buf.size())); - Optional session = sessionManager.CreateUnauthenticatedSession(ctx.GetAliceAddress(), GetDefaultMRPConfig()); - NL_TEST_ASSERT(inSuite, session.HasValue()); + Optional session = sessionManager.CreateUnauthenticatedSession(GetAliceAddress(), GetDefaultMRPConfig()); + EXPECT_TRUE(session.HasValue()); TestCASESecurePairingDelegate caseDelegate; CASESession caseSession; caseSession.SetGroupDataProvider(&gDeviceGroupDataProvider); - err = caseSession.PrepareForSessionEstablishment(sessionManager, &gDeviceFabrics, nullptr, nullptr, &caseDelegate, - ScopedNodeId(), NullOptional); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(caseSession.PrepareForSessionEstablishment(sessionManager, &gDeviceFabrics, nullptr, nullptr, &caseDelegate, + ScopedNodeId(), NullOptional), + CHIP_NO_ERROR); - err = ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(MsgType::CASE_Sigma1, &caseSession); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(MsgType::CASE_Sigma1, &caseSession), CHIP_NO_ERROR); - ExpectErrorExchangeDelegate delegate(inSuite, SecureChannel::kProtocolCodeNoSharedRoot); - ExchangeContext * exchange = ctx.GetExchangeManager().NewContext(session.Value(), &delegate); - NL_TEST_ASSERT(inSuite, exchange != nullptr); + ExpectErrorExchangeDelegate delegate(SecureChannel::kProtocolCodeNoSharedRoot); + ExchangeContext * exchange = GetExchangeManager().NewContext(session.Value(), &delegate); + ASSERT_NE(exchange, nullptr); - err = exchange->SendMessage(MsgType::CASE_Sigma1, std::move(data), SendMessageFlags::kExpectResponse); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(exchange->SendMessage(MsgType::CASE_Sigma1, std::move(data), SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); - ServiceEvents(ctx); + ServiceEvents(); - NL_TEST_ASSERT(inSuite, caseDelegate.mNumPairingErrors == 1); - NL_TEST_ASSERT(inSuite, caseDelegate.mNumPairingComplete == 0); + EXPECT_EQ(caseDelegate.mNumPairingErrors, 1u); + EXPECT_EQ(caseDelegate.mNumPairingComplete, 0u); - ctx.GetExchangeManager().UnregisterUnsolicitedMessageHandlerForType(MsgType::CASE_Sigma1); + GetExchangeManager().UnregisterUnsolicitedMessageHandlerForType(MsgType::CASE_Sigma1); caseSession.Clear(); } } // namespace chip - -// Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("WaitInit", chip::TestCASESession::SecurePairingWaitTest), - NL_TEST_DEF("Start", chip::TestCASESession::SecurePairingStartTest), - NL_TEST_DEF("Handshake", chip::TestCASESession::SecurePairingHandshakeTest), - NL_TEST_DEF("ServerHandshake", chip::TestCASESession::SecurePairingHandshakeServerTest), - NL_TEST_DEF("ClientReceivesBusy", chip::TestCASESession::ClientReceivesBusyTest), - NL_TEST_DEF("Sigma1Parsing", chip::TestCASESession::Sigma1ParsingTest), - NL_TEST_DEF("DestinationId", chip::TestCASESession::DestinationIdTest), - NL_TEST_DEF("SessionResumptionStorage", chip::TestCASESession::SessionResumptionStorage), -#if CONFIG_BUILD_FOR_HOST_UNIT_TEST - // This is compiled for host tests which is enough test coverage to ensure updating NOC invalidates - // CASESession that are in the process of establishing. - NL_TEST_DEF("InvalidatePendingSessionEstablishment", chip::TestCASESession::SimulateUpdateNOCInvalidatePendingEstablishment), -#endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST - NL_TEST_DEF("Sigma1BadDestinationId", chip::TestCASESession::Sigma1BadDestinationIdTest), - - NL_TEST_SENTINEL() -}; -// clang-format on - -// clang-format off -static nlTestSuite sSuite = -{ - "Test-CHIP-SecurePairing-CASE", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; -// clang-format on - -/** - * Main - */ -int TestCASESessionTest() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestCASESessionTest) diff --git a/src/protocols/secure_channel/tests/TestCheckInCounter.cpp b/src/protocols/secure_channel/tests/TestCheckInCounter.cpp index e4a71777d17b97..57dbd4b3496cdd 100644 --- a/src/protocols/secure_channel/tests/TestCheckInCounter.cpp +++ b/src/protocols/secure_channel/tests/TestCheckInCounter.cpp @@ -56,7 +56,6 @@ void VerifyCheckInCounterValues(uint32_t startValue, uint32_t expectedValue, Che EXPECT_EQ(counter.GetValue(), startValue); // Test operation - CHIP_ERROR err = CHIP_NO_ERROR; switch (operation) { case CheckInCounterOperations::kInvalidateHalf: { @@ -68,7 +67,6 @@ void VerifyCheckInCounterValues(uint32_t startValue, uint32_t expectedValue, Che break; } default: { - err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; FAIL(); } }; diff --git a/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp b/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp index 82e755b783b4b8..59dcf3080a8ec3 100644 --- a/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp +++ b/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp @@ -15,16 +15,15 @@ * limitations under the License. */ +#include #include #include -#include -#include // DefaultSessionResumptionStorage is a partial implementation. // Use SimpleSessionResumptionStorage, which extends it, to test. #include -void TestSave(nlTestSuite * inSuite, void * inContext) +TEST(TestDefaultSessionResumptionStorage, TestSave) { chip::SimpleSessionResumptionStorage sessionStorage; chip::TestPersistentStorageDelegate storage; @@ -40,14 +39,11 @@ void TestSave(nlTestSuite * inSuite, void * inContext) // Populate test vectors. for (size_t i = 0; i < ArraySize(vectors); ++i) { - NL_TEST_ASSERT( - inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(vectors[i].resumptionId.data(), vectors[i].resumptionId.size())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(vectors[i].resumptionId.data(), vectors[i].resumptionId.size()), CHIP_NO_ERROR); *vectors[i].resumptionId.data() = static_cast(i); // set first byte to our index to ensure uniqueness for the FindByResumptionId call vectors[i].sharedSecret.SetLength(vectors[i].sharedSecret.Capacity()); - NL_TEST_ASSERT(inSuite, - CHIP_NO_ERROR == - chip::Crypto::DRBG_get_bytes(vectors[i].sharedSecret.Bytes(), vectors[i].sharedSecret.Length())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(vectors[i].sharedSecret.Bytes(), vectors[i].sharedSecret.Length()), CHIP_NO_ERROR); vectors[i].node = chip::ScopedNodeId(static_cast(i + 1), static_cast(i + 1)); vectors[i].cats.values[0] = static_cast(rand()); vectors[i].cats.values[1] = static_cast(rand()); @@ -57,9 +53,8 @@ void TestSave(nlTestSuite * inSuite, void * inContext) // Fill storage. for (size_t i = 0; i < CHIP_CONFIG_CASE_SESSION_RESUME_CACHE_SIZE; ++i) { - NL_TEST_ASSERT(inSuite, - sessionStorage.Save(vectors[i].node, vectors[i].resumptionId, vectors[i].sharedSecret, vectors[i].cats) == - CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.Save(vectors[i].node, vectors[i].resumptionId, vectors[i].sharedSecret, vectors[i].cats), + CHIP_NO_ERROR); } // Verify behavior for over-fill. @@ -69,9 +64,9 @@ void TestSave(nlTestSuite * inSuite, void * inContext) // case should be modified to match. { size_t last = ArraySize(vectors) - 1; - NL_TEST_ASSERT(inSuite, - sessionStorage.Save(vectors[last].node, vectors[last].resumptionId, vectors[last].sharedSecret, - vectors[last].cats) == CHIP_NO_ERROR); + EXPECT_EQ( + sessionStorage.Save(vectors[last].node, vectors[last].resumptionId, vectors[last].sharedSecret, vectors[last].cats), + CHIP_NO_ERROR); // Copy our data to our test vector index 0 to match // what is now in storage. vectors[0].node = vectors[last].node; @@ -89,28 +84,24 @@ void TestSave(nlTestSuite * inSuite, void * inContext) chip::CATValues outCats; // Verify retrieval by node. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByScopedNodeId(vector.node, outResumptionId, outSharedSecret, outCats) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(vector.resumptionId.data(), outResumptionId.data(), vector.resumptionId.size()) == 0); - NL_TEST_ASSERT(inSuite, - memcmp(vector.sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vector.sharedSecret.Length()) == 0); - NL_TEST_ASSERT(inSuite, vector.cats.values[0] == outCats.values[0]); - NL_TEST_ASSERT(inSuite, vector.cats.values[1] == outCats.values[1]); - NL_TEST_ASSERT(inSuite, vector.cats.values[2] == outCats.values[2]); + EXPECT_EQ(sessionStorage.FindByScopedNodeId(vector.node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_EQ(memcmp(vector.resumptionId.data(), outResumptionId.data(), vector.resumptionId.size()), 0); + EXPECT_EQ(memcmp(vector.sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vector.sharedSecret.Length()), 0); + EXPECT_EQ(vector.cats.values[0], outCats.values[0]); + EXPECT_EQ(vector.cats.values[1], outCats.values[1]); + EXPECT_EQ(vector.cats.values[2], outCats.values[2]); // Validate retrieval by resumption ID. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByResumptionId(vector.resumptionId, outNode, outSharedSecret, outCats) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, vector.node == outNode); - NL_TEST_ASSERT(inSuite, - memcmp(vector.sharedSecret.Bytes(), outSharedSecret.ConstBytes(), vector.sharedSecret.Length()) == 0); - NL_TEST_ASSERT(inSuite, vector.cats.values[0] == outCats.values[0]); - NL_TEST_ASSERT(inSuite, vector.cats.values[1] == outCats.values[1]); - NL_TEST_ASSERT(inSuite, vector.cats.values[2] == outCats.values[2]); + EXPECT_EQ(sessionStorage.FindByResumptionId(vector.resumptionId, outNode, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_EQ(vector.node, outNode); + EXPECT_EQ(memcmp(vector.sharedSecret.Bytes(), outSharedSecret.ConstBytes(), vector.sharedSecret.Length()), 0); + EXPECT_EQ(vector.cats.values[0], outCats.values[0]); + EXPECT_EQ(vector.cats.values[1], outCats.values[1]); + EXPECT_EQ(vector.cats.values[2], outCats.values[2]); } } -void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) +TEST(TestDefaultSessionResumptionStorage, TestInPlaceSave) { chip::SimpleSessionResumptionStorage sessionStorage; chip::TestPersistentStorageDelegate storage; @@ -139,14 +130,11 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) // Populate test vectors. for (size_t i = 0; i < ArraySize(vectors); ++i) { - NL_TEST_ASSERT( - inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(vectors[i].resumptionId.data(), vectors[i].resumptionId.size())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(vectors[i].resumptionId.data(), vectors[i].resumptionId.size()), CHIP_NO_ERROR); *vectors[i].resumptionId.data() = static_cast(i); // set first byte to our index to ensure uniqueness for the FindByResumptionId call vectors[i].sharedSecret.SetLength(vectors[i].sharedSecret.Capacity()); - NL_TEST_ASSERT(inSuite, - CHIP_NO_ERROR == - chip::Crypto::DRBG_get_bytes(vectors[i].sharedSecret.Bytes(), vectors[i].sharedSecret.Length())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(vectors[i].sharedSecret.Bytes(), vectors[i].sharedSecret.Length()), CHIP_NO_ERROR); vectors[i].node = nodes[i % ArraySize(nodes)]; vectors[i].cats.values[0] = static_cast(rand()); vectors[i].cats.values[1] = static_cast(rand()); @@ -156,9 +144,8 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) // Add one entry for each node. for (size_t i = 0; i < ArraySize(nodes); ++i) { - NL_TEST_ASSERT(inSuite, - sessionStorage.Save(vectors[i].node, vectors[i].resumptionId, vectors[i].sharedSecret, vectors[i].cats) == - CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.Save(vectors[i].node, vectors[i].resumptionId, vectors[i].sharedSecret, vectors[i].cats), + CHIP_NO_ERROR); } // Read back and verify values. @@ -170,37 +157,27 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) chip::CATValues outCats; // Verify retrieval by node. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByScopedNodeId(vectors[i].node, outResumptionId, outSharedSecret, outCats) == - CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - memcmp(vectors[i].resumptionId.data(), outResumptionId.data(), vectors[i].resumptionId.size()) == 0); - NL_TEST_ASSERT( - inSuite, - memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()) == 0); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[0] == outCats.values[0]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[1] == outCats.values[1]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[2] == outCats.values[2]); + EXPECT_EQ(sessionStorage.FindByScopedNodeId(vectors[i].node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_EQ(memcmp(vectors[i].resumptionId.data(), outResumptionId.data(), vectors[i].resumptionId.size()), 0); + EXPECT_EQ(memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()), 0); + EXPECT_EQ(vectors[i].cats.values[0], outCats.values[0]); + EXPECT_EQ(vectors[i].cats.values[1], outCats.values[1]); + EXPECT_EQ(vectors[i].cats.values[2], outCats.values[2]); // Validate retrieval by resumption ID. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByResumptionId(vectors[i].resumptionId, outNode, outSharedSecret, outCats) == - CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, vectors[i].node == outNode); - NL_TEST_ASSERT( - inSuite, - memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()) == 0); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[0] == outCats.values[0]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[1] == outCats.values[1]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[2] == outCats.values[2]); + EXPECT_EQ(sessionStorage.FindByResumptionId(vectors[i].resumptionId, outNode, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_EQ(vectors[i].node, outNode); + EXPECT_EQ(memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()), 0); + EXPECT_EQ(vectors[i].cats.values[0], outCats.values[0]); + EXPECT_EQ(vectors[i].cats.values[1], outCats.values[1]); + EXPECT_EQ(vectors[i].cats.values[2], outCats.values[2]); } // Now add all test vectors. This should overwrite each node's record // many times. for (auto & vector : vectors) { - NL_TEST_ASSERT(inSuite, - sessionStorage.Save(vector.node, vector.resumptionId, vector.sharedSecret, vector.cats) == CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.Save(vector.node, vector.resumptionId, vector.sharedSecret, vector.cats), CHIP_NO_ERROR); } // Read back and verify that only the last record for each node was retained. @@ -212,36 +189,27 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) chip::CATValues outCats; // Verify retrieval by node. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByScopedNodeId(vectors[i].node, outResumptionId, outSharedSecret, outCats) == - CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - memcmp(vectors[i].resumptionId.data(), outResumptionId.data(), vectors[i].resumptionId.size()) == 0); - NL_TEST_ASSERT( - inSuite, - memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()) == 0); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[0] == outCats.values[0]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[1] == outCats.values[1]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[2] == outCats.values[2]); + EXPECT_EQ(sessionStorage.FindByScopedNodeId(vectors[i].node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_EQ(memcmp(vectors[i].resumptionId.data(), outResumptionId.data(), vectors[i].resumptionId.size()), 0); + EXPECT_EQ(memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()), 0); + EXPECT_EQ(vectors[i].cats.values[0], outCats.values[0]); + EXPECT_EQ(vectors[i].cats.values[1], outCats.values[1]); + EXPECT_EQ(vectors[i].cats.values[2], outCats.values[2]); // Validate retrieval by resumption ID. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByResumptionId(vectors[i].resumptionId, outNode, outSharedSecret, outCats) == - CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, vectors[i].node == outNode); - NL_TEST_ASSERT( - inSuite, - memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()) == 0); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[0] == outCats.values[0]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[1] == outCats.values[1]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[2] == outCats.values[2]); + EXPECT_EQ(sessionStorage.FindByResumptionId(vectors[i].resumptionId, outNode, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_EQ(vectors[i].node, outNode); + EXPECT_EQ(memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()), 0); + EXPECT_EQ(vectors[i].cats.values[0], outCats.values[0]); + EXPECT_EQ(vectors[i].cats.values[1], outCats.values[1]); + EXPECT_EQ(vectors[i].cats.values[2], outCats.values[2]); } // Remove all records for all fabrics. If all three tables of (index, state, // links) are in sync, deleting for each fabric should clean error free. for (const auto & node : nodes) { - NL_TEST_ASSERT(inSuite, sessionStorage.DeleteAll(node.GetFabricIndex()) == CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.DeleteAll(node.GetFabricIndex()), CHIP_NO_ERROR); } // Verify that no entries can be located any longer for any node or @@ -254,12 +222,10 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) chip::CATValues outCats; // Verify all records for all nodes are gone. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByScopedNodeId(vector.node, outResumptionId, outSharedSecret, outCats) != CHIP_NO_ERROR); + EXPECT_NE(sessionStorage.FindByScopedNodeId(vector.node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); // Verify all records for all resumption IDs are gone. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByResumptionId(vector.resumptionId, outNode, outSharedSecret, outCats) != CHIP_NO_ERROR); + EXPECT_NE(sessionStorage.FindByResumptionId(vector.resumptionId, outNode, outSharedSecret, outCats), CHIP_NO_ERROR); } // Verify no state table persistent storage entries were leaked. @@ -267,7 +233,7 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) { uint16_t size = 0; auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(node).KeyName(), nullptr, size); - NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(rv, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } // Verify no link table persistent storage entries were leaked. for (auto & vector : vectors) @@ -275,11 +241,11 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) uint16_t size = 0; auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(vector.resumptionId).KeyName(), nullptr, size); - NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(rv, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } } -void TestDelete(nlTestSuite * inSuite, void * inContext) +TEST(TestDefaultSessionResumptionStorage, TestDelete) { chip::SimpleSessionResumptionStorage sessionStorage; chip::TestPersistentStorageDelegate storage; @@ -293,13 +259,12 @@ void TestDelete(nlTestSuite * inSuite, void * inContext) // Create a shared secret. We can use the same one for all entries. sharedSecret.SetLength(sharedSecret.Capacity()); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length()), CHIP_NO_ERROR); // Populate test vectors. for (size_t i = 0; i < ArraySize(vectors); ++i) { - NL_TEST_ASSERT( - inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(vectors[i].resumptionId.data(), vectors[i].resumptionId.size())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(vectors[i].resumptionId.data(), vectors[i].resumptionId.size()), CHIP_NO_ERROR); *vectors[i].resumptionId.data() = static_cast(i); // set first byte to our index to ensure uniqueness for the delete test vectors[i].node = chip::ScopedNodeId(static_cast(i + 1), static_cast(i + 1)); @@ -308,8 +273,7 @@ void TestDelete(nlTestSuite * inSuite, void * inContext) // Fill storage. for (auto & vector : vectors) { - NL_TEST_ASSERT(inSuite, - sessionStorage.Save(vector.node, vector.resumptionId, sharedSecret, chip::CATValues{}) == CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.Save(vector.node, vector.resumptionId, sharedSecret, chip::CATValues{}), CHIP_NO_ERROR); } // Delete values in turn from storage and verify they are removed. @@ -319,11 +283,9 @@ void TestDelete(nlTestSuite * inSuite, void * inContext) chip::SessionResumptionStorage::ResumptionIdStorage outResumptionId; chip::Crypto::P256ECDHDerivedSecret outSharedSecret; chip::CATValues outCats; - NL_TEST_ASSERT(inSuite, sessionStorage.Delete(vector.node) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByScopedNodeId(vector.node, outResumptionId, outSharedSecret, outCats) != CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByResumptionId(vector.resumptionId, outNode, outSharedSecret, outCats) != CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.Delete(vector.node), CHIP_NO_ERROR); + EXPECT_NE(sessionStorage.FindByScopedNodeId(vector.node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_NE(sessionStorage.FindByResumptionId(vector.resumptionId, outNode, outSharedSecret, outCats), CHIP_NO_ERROR); } // Verify no state or link table persistent storage entries were leaked. @@ -333,17 +295,17 @@ void TestDelete(nlTestSuite * inSuite, void * inContext) { auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(vector.node).KeyName(), nullptr, size); - NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(rv, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } { auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(vector.resumptionId).KeyName(), nullptr, size); - NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(rv, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } } } -void TestDeleteAll(nlTestSuite * inSuite, void * inContext) +TEST(TestDefaultSessionResumptionStorage, TestDeleteAll) { chip::SimpleSessionResumptionStorage sessionStorage; chip::TestPersistentStorageDelegate storage; @@ -361,7 +323,7 @@ void TestDeleteAll(nlTestSuite * inSuite, void * inContext) // Create a shared secret. We can use the same one for all entries. sharedSecret.SetLength(sharedSecret.Capacity()); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length()), CHIP_NO_ERROR); // Populate test vectors. for (size_t i = 0; i < sizeof(vectors) / sizeof(vectors[0]); ++i) @@ -369,10 +331,9 @@ void TestDeleteAll(nlTestSuite * inSuite, void * inContext) vectors[i].fabricIndex = static_cast(i + 1); for (size_t j = 0; j < sizeof(vectors[0].nodes) / sizeof(vectors[0].nodes[0]); ++j) { - NL_TEST_ASSERT( - inSuite, - CHIP_NO_ERROR == - chip::Crypto::DRBG_get_bytes(vectors[i].nodes[j].resumptionId.data(), vectors[i].nodes[j].resumptionId.size())); + EXPECT_EQ( + chip::Crypto::DRBG_get_bytes(vectors[i].nodes[j].resumptionId.data(), vectors[i].nodes[j].resumptionId.size()), + CHIP_NO_ERROR); vectors[i].nodes[j].node = chip::ScopedNodeId(static_cast(j), vectors[i].fabricIndex); } } @@ -382,8 +343,7 @@ void TestDeleteAll(nlTestSuite * inSuite, void * inContext) { for (auto & node : vector.nodes) { - NL_TEST_ASSERT(inSuite, - sessionStorage.Save(node.node, node.resumptionId, sharedSecret, chip::CATValues{}) == CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.Save(node.node, node.resumptionId, sharedSecret, chip::CATValues{}), CHIP_NO_ERROR); } } @@ -397,16 +357,14 @@ void TestDeleteAll(nlTestSuite * inSuite, void * inContext) // Verify fabric node entries exist. for (const auto & node : vector.nodes) { - NL_TEST_ASSERT( - inSuite, sessionStorage.FindByScopedNodeId(node.node, outResumptionId, outSharedSecret, outCats) == CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.FindByScopedNodeId(node.node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); } // Delete fabric. - NL_TEST_ASSERT(inSuite, sessionStorage.DeleteAll(vector.fabricIndex) == CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.DeleteAll(vector.fabricIndex), CHIP_NO_ERROR); // Verify fabric node entries no longer exist. for (const auto & node : vector.nodes) { - NL_TEST_ASSERT( - inSuite, sessionStorage.FindByScopedNodeId(node.node, outResumptionId, outSharedSecret, outCats) != CHIP_NO_ERROR); + EXPECT_NE(sessionStorage.FindByScopedNodeId(node.node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); } } // Verify no state or link table persistent storage entries were leaked. @@ -418,53 +376,13 @@ void TestDeleteAll(nlTestSuite * inSuite, void * inContext) { auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(node.node).KeyName(), nullptr, size); - NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(rv, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } { auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(node.resumptionId).KeyName(), nullptr, size); - NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(rv, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } } } } - -// Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("TestSave", TestSave), - NL_TEST_DEF("TestInPlaceSave", TestInPlaceSave), - NL_TEST_DEF("TestDelete", TestDelete), - NL_TEST_DEF("TestDeleteAll", TestDeleteAll), - - NL_TEST_SENTINEL() -}; -// clang-format on - -// clang-format off -static nlTestSuite sSuite = -{ - "Test-CHIP-DefaultSessionResumptionStorage", - &sTests[0], - nullptr, - nullptr, -}; -// clang-format on - -/** - * Main - */ -int TestDefaultSessionResumptionStorage() -{ - // Run test suit against one context - nlTestRunner(&sSuite, nullptr); - - return (nlTestRunnerStats(&sSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestDefaultSessionResumptionStorage) diff --git a/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp b/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp index c2e71591acda14..41b6539ecf0773 100644 --- a/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp +++ b/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp @@ -23,8 +23,7 @@ #include #include -#include -#include + #include #include #include @@ -35,8 +34,8 @@ #include #include +#include #include -#include #include @@ -48,8 +47,6 @@ using namespace chip::Transport; using namespace chip::Messaging; using namespace chip::Protocols; -using TestContext = chip::Test::LoopbackMessagingContext; - const char PAYLOAD[] = "Hello!"; class MockAppDelegate : public ExchangeDelegate @@ -67,109 +64,55 @@ class MockAppDelegate : public ExchangeDelegate int ReceiveHandlerCallCount = 0; }; -void MessageCounterSyncProcess(nlTestSuite * inSuite, void * inContext) +struct TestMessageCounterManager : public chip::Test::LoopbackMessagingContext, public ::testing::Test { - TestContext & ctx = *reinterpret_cast(inContext); + static void SetUpTestSuite() { chip::Test::LoopbackMessagingContext::SetUpTestSuite(); } + static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } - CHIP_ERROR err = CHIP_NO_ERROR; + void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } + void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } +}; + +TEST_F(TestMessageCounterManager, MessageCounterSyncProcess) +{ - SessionHandle localSession = ctx.GetSessionBobToAlice(); - SessionHandle peerSession = ctx.GetSessionAliceToBob(); + SessionHandle localSession = GetSessionBobToAlice(); + SessionHandle peerSession = GetSessionAliceToBob(); - Transport::SecureSession * localState = ctx.GetSecureSessionManager().GetSecureSession(localSession); - Transport::SecureSession * peerState = ctx.GetSecureSessionManager().GetSecureSession(peerSession); + Transport::SecureSession * localState = GetSecureSessionManager().GetSecureSession(localSession); + Transport::SecureSession * peerState = GetSecureSessionManager().GetSecureSession(peerSession); localState->GetSessionMessageCounter().GetPeerMessageCounter().Reset(); - err = ctx.GetMessageCounterManager().SendMsgCounterSyncReq(localSession, localState); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(GetMessageCounterManager().SendMsgCounterSyncReq(localSession, localState), CHIP_NO_ERROR); MessageCounter & peerCounter = peerState->GetSessionMessageCounter().GetLocalMessageCounter(); PeerMessageCounter & localCounter = localState->GetSessionMessageCounter().GetPeerMessageCounter(); - NL_TEST_ASSERT(inSuite, localCounter.IsSynchronized()); - NL_TEST_ASSERT(inSuite, localCounter.GetCounter() == peerCounter.Value()); + EXPECT_TRUE(localCounter.IsSynchronized()); + EXPECT_EQ(localCounter.GetCounter(), peerCounter.Value()); } -void CheckReceiveMessage(nlTestSuite * inSuite, void * inContext) +TEST_F(TestMessageCounterManager, CheckReceiveMessage) { - TestContext & ctx = *reinterpret_cast(inContext); - CHIP_ERROR err = CHIP_NO_ERROR; - - SessionHandle peerSession = ctx.GetSessionAliceToBob(); - Transport::SecureSession * peerState = ctx.GetSecureSessionManager().GetSecureSession(peerSession); + SessionHandle peerSession = GetSessionAliceToBob(); + Transport::SecureSession * peerState = GetSecureSessionManager().GetSecureSession(peerSession); peerState->GetSessionMessageCounter().GetPeerMessageCounter().Reset(); MockAppDelegate callback; - ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(chip::Protocols::Echo::MsgType::EchoRequest, &callback); + GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(chip::Protocols::Echo::MsgType::EchoRequest, &callback); uint16_t payload_len = sizeof(PAYLOAD); System::PacketBufferHandle msgBuf = MessagePacketBuffer::NewWithData(PAYLOAD, payload_len); - NL_TEST_ASSERT(inSuite, !msgBuf.IsNull()); + ASSERT_FALSE(msgBuf.IsNull()); - Messaging::ExchangeContext * ec = ctx.NewExchangeToAlice(nullptr); - NL_TEST_ASSERT(inSuite, ec != nullptr); + Messaging::ExchangeContext * ec = NewExchangeToAlice(nullptr); + ASSERT_NE(ec, nullptr); - err = ec->SendMessage(chip::Protocols::Echo::MsgType::EchoRequest, std::move(msgBuf), - Messaging::SendFlags{ Messaging::SendMessageFlags::kNoAutoRequestAck }); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, peerState->GetSessionMessageCounter().GetPeerMessageCounter().IsSynchronized()); - NL_TEST_ASSERT(inSuite, callback.ReceiveHandlerCallCount == 1); + EXPECT_EQ(ec->SendMessage(chip::Protocols::Echo::MsgType::EchoRequest, std::move(msgBuf), + Messaging::SendFlags{ Messaging::SendMessageFlags::kNoAutoRequestAck }), + CHIP_NO_ERROR); + EXPECT_TRUE(peerState->GetSessionMessageCounter().GetPeerMessageCounter().IsSynchronized()); + EXPECT_EQ(callback.ReceiveHandlerCallCount, 1); } // Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("Test MessageCounterManager::MessageCounterSyncProcess", MessageCounterSyncProcess), - NL_TEST_DEF("Test MessageCounterManager::ReceiveMessage", CheckReceiveMessage), - NL_TEST_SENTINEL() -}; -// clang-format on - -int Initialize(void * aContext); -int Finalize(void * aContext); - -// clang-format off -nlTestSuite sSuite = -{ - "Test-MessageCounterManager", - &sTests[0], - Initialize, - Finalize -}; -// clang-format on - -/** - * Initialize the test suite. - */ -int Initialize(void * aContext) -{ - auto * ctx = static_cast(aContext); - VerifyOrReturnError(ctx->Init(&sSuite) == CHIP_NO_ERROR, FAILURE); - - return SUCCESS; -} - -/** - * Finalize the test suite. - */ -int Finalize(void * aContext) -{ - reinterpret_cast(aContext)->Shutdown(); - return SUCCESS; -} - } // namespace - -/** - * Main - */ -int TestMessageCounterManager() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestMessageCounterManager); diff --git a/src/protocols/secure_channel/tests/TestPASESession.cpp b/src/protocols/secure_channel/tests/TestPASESession.cpp index 896f721579334d..5b3f957d51bf84 100644 --- a/src/protocols/secure_channel/tests/TestPASESession.cpp +++ b/src/protocols/secure_channel/tests/TestPASESession.cpp @@ -22,15 +22,13 @@ */ #include -#include +#include #include #include #include #include #include -#include -#include #include #include #include @@ -85,7 +83,8 @@ constexpr Spake2pVerifierSerialized sTestSpake2p01_SerializedVerifier = { 0xB7, 0xC0, 0x7F, 0xCC, 0x06, 0x27, 0xA1, 0xB8, 0x57, 0x3A, 0x14, 0x9F, 0xCD, 0x1F, 0xA4, 0x66, 0xCF }; -class TestContext : public chip::Test::LoopbackMessagingContext +class TestSecurePairingDelegate; +class TestPASESession : public chip::Test::LoopbackMessagingContext, public ::testing::Test { public: // Performs shared setup for all tests in the test suite @@ -99,6 +98,11 @@ class TestContext : public chip::Test::LoopbackMessagingContext } void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } + + void SecurePairingHandshakeTestCommon(SessionManager & sessionManager, PASESession & pairingCommissioner, + Optional mrpCommissionerConfig, + Optional mrpAccessoryConfig, + TestSecurePairingDelegate & delegateCommissioner); }; class PASETestLoopbackTransportDelegate : public Test::LoopbackTransportDelegate @@ -134,12 +138,11 @@ class MockAppDelegate : public ExchangeDelegate class TemporarySessionManager { public: - TemporarySessionManager(nlTestSuite * suite, TestContext & ctx) : mCtx(ctx) + TemporarySessionManager(TestPASESession & ctx) : mCtx(ctx) { - NL_TEST_ASSERT(suite, - CHIP_NO_ERROR == - mSessionManager.Init(&ctx.GetSystemLayer(), &ctx.GetTransportMgr(), &ctx.GetMessageCounterManager(), - &mStorage, &ctx.GetFabricTable(), ctx.GetSessionKeystore())); + EXPECT_EQ(CHIP_NO_ERROR, + mSessionManager.Init(&ctx.GetSystemLayer(), &ctx.GetTransportMgr(), &ctx.GetMessageCounterManager(), &mStorage, + &ctx.GetFabricTable(), ctx.GetSessionKeystore())); // The setup here is really weird: we are using one session manager for // the actual messages we send (the PASE handshake, so the // unauthenticated sessions) and a different one for allocating the PASE @@ -159,122 +162,114 @@ class TemporarySessionManager operator SessionManager &() { return mSessionManager; } private: - TestContext & mCtx; + TestPASESession & mCtx; TestPersistentStorageDelegate mStorage; SessionManager mSessionManager; }; using namespace System::Clock::Literals; -void SecurePairingWaitTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingWaitTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); // Test all combinations of invalid parameters TestSecurePairingDelegate delegate; PASESession pairing; - NL_TEST_ASSERT(inSuite, pairing.GetSecureSessionType() == SecureSession::Type::kPASE); + EXPECT_EQ(pairing.GetSecureSessionType(), SecureSession::Type::kPASE); - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); - NL_TEST_ASSERT(inSuite, - pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, ByteSpan(), - Optional::Missing(), - &delegate) == CHIP_ERROR_INVALID_ARGUMENT); - ctx.DrainAndServiceIO(); - - NL_TEST_ASSERT(inSuite, - pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, - ByteSpan(reinterpret_cast("saltSalt"), 8), - Optional::Missing(), - nullptr) == CHIP_ERROR_INVALID_ARGUMENT); - ctx.DrainAndServiceIO(); - - NL_TEST_ASSERT(inSuite, - pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, - ByteSpan(reinterpret_cast("saltSalt"), 8), - Optional::Missing(), - &delegate) == CHIP_ERROR_INVALID_ARGUMENT); - ctx.DrainAndServiceIO(); - - NL_TEST_ASSERT(inSuite, - pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, - ByteSpan(sTestSpake2p01_Salt), Optional::Missing(), - &delegate) == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + EXPECT_EQ(pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, ByteSpan(), + Optional::Missing(), &delegate), + CHIP_ERROR_INVALID_ARGUMENT); + DrainAndServiceIO(); + + EXPECT_EQ(pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, + ByteSpan(reinterpret_cast("saltSalt"), 8), + Optional::Missing(), nullptr), + CHIP_ERROR_INVALID_ARGUMENT); + DrainAndServiceIO(); + + EXPECT_EQ(pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, + ByteSpan(reinterpret_cast("saltSalt"), 8), + Optional::Missing(), &delegate), + CHIP_ERROR_INVALID_ARGUMENT); + DrainAndServiceIO(); + + EXPECT_EQ(pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, + ByteSpan(sTestSpake2p01_Salt), Optional::Missing(), &delegate), + CHIP_NO_ERROR); + DrainAndServiceIO(); } -void SecurePairingStartTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingStartTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); // Test all combinations of invalid parameters TestSecurePairingDelegate delegate; PASESession pairing; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); - ExchangeContext * context = ctx.NewUnauthenticatedExchangeToBob(&pairing); + ExchangeContext * context = NewUnauthenticatedExchangeToBob(&pairing); - NL_TEST_ASSERT(inSuite, - pairing.Pair(sessionManager, sTestSpake2p01_PinCode, Optional::Missing(), nullptr, - nullptr) != CHIP_NO_ERROR); + EXPECT_NE( + pairing.Pair(sessionManager, sTestSpake2p01_PinCode, Optional::Missing(), nullptr, nullptr), + CHIP_NO_ERROR); loopback.Reset(); - NL_TEST_ASSERT(inSuite, - pairing.Pair(sessionManager, sTestSpake2p01_PinCode, Optional::Missing(), context, - &delegate) == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + EXPECT_EQ(pairing.Pair(sessionManager, sTestSpake2p01_PinCode, Optional::Missing(), context, + &delegate), + CHIP_NO_ERROR); + DrainAndServiceIO(); // There should have been two messages sent: PBKDFParamRequest and an ack. - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == 2); + EXPECT_EQ(loopback.mSentMessageCount, 2u); - ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); - NL_TEST_ASSERT(inSuite, rm->TestGetCountRetransTable() == 0); + ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); loopback.Reset(); loopback.mSentMessageCount = 0; loopback.mMessageSendError = CHIP_ERROR_BAD_REQUEST; PASESession pairing1; - ExchangeContext * context1 = ctx.NewUnauthenticatedExchangeToBob(&pairing1); - NL_TEST_ASSERT(inSuite, - pairing1.Pair(sessionManager, sTestSpake2p01_PinCode, Optional::Missing(), - context1, &delegate) == CHIP_ERROR_BAD_REQUEST); - ctx.DrainAndServiceIO(); + ExchangeContext * context1 = NewUnauthenticatedExchangeToBob(&pairing1); + EXPECT_EQ(pairing1.Pair(sessionManager, sTestSpake2p01_PinCode, Optional::Missing(), context1, + &delegate), + CHIP_ERROR_BAD_REQUEST); + DrainAndServiceIO(); loopback.mMessageSendError = CHIP_NO_ERROR; } -void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, SessionManager & sessionManager, - PASESession & pairingCommissioner, - Optional mrpCommissionerConfig, - Optional mrpAccessoryConfig, - TestSecurePairingDelegate & delegateCommissioner) +void TestPASESession::SecurePairingHandshakeTestCommon(SessionManager & sessionManager, PASESession & pairingCommissioner, + Optional mrpCommissionerConfig, + Optional mrpAccessoryConfig, + TestSecurePairingDelegate & delegateCommissioner) { - TestContext & ctx = *reinterpret_cast(inContext); TestSecurePairingDelegate delegateAccessory; PASESession pairingAccessory; PASETestLoopbackTransportDelegate delegate; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.SetLoopbackTransportDelegate(&delegate); loopback.mSentMessageCount = 0; - ExchangeContext * contextCommissioner = ctx.NewUnauthenticatedExchangeToBob(&pairingCommissioner); + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(&pairingCommissioner); if (loopback.mNumMessagesToDrop != 0) { - ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); ReliableMessageContext * rc = contextCommissioner->GetReliableMessageContext(); - NL_TEST_ASSERT(inSuite, rm != nullptr); - NL_TEST_ASSERT(inSuite, rc != nullptr); + ASSERT_NE(rm, nullptr); + ASSERT_NE(rc, nullptr); // Adding an if-else to avoid affecting non-ICD tests #if CHIP_CONFIG_ENABLE_ICD_SERVER == 1 @@ -293,20 +288,19 @@ void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, S #endif // CHIP_CONFIG_ENABLE_ICD_SERVER } - NL_TEST_ASSERT(inSuite, - ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType( - Protocols::SecureChannel::MsgType::PBKDFParamRequest, &pairingAccessory) == CHIP_NO_ERROR); + EXPECT_EQ(GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::PBKDFParamRequest, + &pairingAccessory), + CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - pairingAccessory.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, - ByteSpan(sTestSpake2p01_Salt), mrpAccessoryConfig, - &delegateAccessory) == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + EXPECT_EQ(pairingAccessory.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, + ByteSpan(sTestSpake2p01_Salt), mrpAccessoryConfig, &delegateAccessory), + CHIP_NO_ERROR); + DrainAndServiceIO(); - NL_TEST_ASSERT(inSuite, - pairingCommissioner.Pair(sessionManager, sTestSpake2p01_PinCode, mrpCommissionerConfig, contextCommissioner, - &delegateCommissioner) == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + EXPECT_EQ(pairingCommissioner.Pair(sessionManager, sTestSpake2p01_PinCode, mrpCommissionerConfig, contextCommissioner, + &delegateCommissioner), + CHIP_NO_ERROR); + DrainAndServiceIO(); while (delegate.mMessageDropped) { @@ -323,145 +317,127 @@ void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, S // Wait some time so the dropped message will be retransmitted when we drain the IO. chip::test_utils::SleepMillis(waitTimeout.count()); delegate.mMessageDropped = false; - ReliableMessageMgr::Timeout(&ctx.GetSystemLayer(), ctx.GetExchangeManager().GetReliableMessageMgr()); - ctx.DrainAndServiceIO(); + ReliableMessageMgr::Timeout(&GetSystemLayer(), GetExchangeManager().GetReliableMessageMgr()); + DrainAndServiceIO(); }; // Standalone acks also increment the mSentMessageCount. But some messages could be acked // via piggybacked acks. So we cannot check for a specific value of mSentMessageCount. // Let's make sure atleast number is >= than the minimum messages required to complete the // handshake. - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount >= sTestPaseMessageCount); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 1); + EXPECT_GE(loopback.mSentMessageCount, sTestPaseMessageCount); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 1u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 1u); if (mrpCommissionerConfig.HasValue()) { - NL_TEST_ASSERT(inSuite, - pairingAccessory.GetRemoteMRPConfig().mIdleRetransTimeout == - mrpCommissionerConfig.Value().mIdleRetransTimeout); - NL_TEST_ASSERT(inSuite, - pairingAccessory.GetRemoteMRPConfig().mActiveRetransTimeout == - mrpCommissionerConfig.Value().mActiveRetransTimeout); + EXPECT_EQ(pairingAccessory.GetRemoteMRPConfig().mIdleRetransTimeout, mrpCommissionerConfig.Value().mIdleRetransTimeout); + EXPECT_EQ(pairingAccessory.GetRemoteMRPConfig().mActiveRetransTimeout, mrpCommissionerConfig.Value().mActiveRetransTimeout); } if (mrpAccessoryConfig.HasValue()) { - NL_TEST_ASSERT(inSuite, - pairingCommissioner.GetRemoteMRPConfig().mIdleRetransTimeout == - mrpAccessoryConfig.Value().mIdleRetransTimeout); - NL_TEST_ASSERT(inSuite, - pairingCommissioner.GetRemoteMRPConfig().mActiveRetransTimeout == - mrpAccessoryConfig.Value().mActiveRetransTimeout); + EXPECT_EQ(pairingCommissioner.GetRemoteMRPConfig().mIdleRetransTimeout, mrpAccessoryConfig.Value().mIdleRetransTimeout); + EXPECT_EQ(pairingCommissioner.GetRemoteMRPConfig().mActiveRetransTimeout, mrpAccessoryConfig.Value().mActiveRetransTimeout); } // Now evict the PASE sessions. auto session = pairingCommissioner.CopySecureSession(); - NL_TEST_ASSERT(inSuite, session.HasValue()); + EXPECT_TRUE(session.HasValue()); session.Value()->AsSecureSession()->MarkForEviction(); session = pairingAccessory.CopySecureSession(); - NL_TEST_ASSERT(inSuite, session.HasValue()); + EXPECT_TRUE(session.HasValue()); session.Value()->AsSecureSession()->MarkForEviction(); // Evicting a session async notifies the PASESession's delegate. Normally // that notification is what would delete the PASESession, but in our case // that will happen as soon as things come off the stack. So make sure to // process the async bits before that happens. - ctx.DrainAndServiceIO(); + DrainAndServiceIO(); // And check that this did not result in any new notifications. - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 1); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 1u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 1u); loopback.SetLoopbackTransportDelegate(nullptr); } -void SecurePairingHandshakeTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingHandshakeTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestSecurePairingDelegate delegateCommissioner; PASESession pairingCommissioner; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); - SecurePairingHandshakeTestCommon(inSuite, inContext, sessionManager, pairingCommissioner, - Optional::Missing(), + SecurePairingHandshakeTestCommon(sessionManager, pairingCommissioner, Optional::Missing(), Optional::Missing(), delegateCommissioner); } -void SecurePairingHandshakeWithCommissionerMRPTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingHandshakeWithCommissionerMRPTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestSecurePairingDelegate delegateCommissioner; PASESession pairingCommissioner; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); ReliableMessageProtocolConfig config(1000_ms32, 10000_ms32, 4000_ms16); - SecurePairingHandshakeTestCommon(inSuite, inContext, sessionManager, pairingCommissioner, - Optional::Value(config), + SecurePairingHandshakeTestCommon(sessionManager, pairingCommissioner, Optional::Value(config), Optional::Missing(), delegateCommissioner); } -void SecurePairingHandshakeWithDeviceMRPTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingHandshakeWithDeviceMRPTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestSecurePairingDelegate delegateCommissioner; PASESession pairingCommissioner; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); ReliableMessageProtocolConfig config(1000_ms32, 10000_ms32, 4000_ms16); - SecurePairingHandshakeTestCommon(inSuite, inContext, sessionManager, pairingCommissioner, - Optional::Missing(), + SecurePairingHandshakeTestCommon(sessionManager, pairingCommissioner, Optional::Missing(), Optional::Value(config), delegateCommissioner); } -void SecurePairingHandshakeWithAllMRPTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingHandshakeWithAllMRPTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestSecurePairingDelegate delegateCommissioner; PASESession pairingCommissioner; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); ReliableMessageProtocolConfig commissionerConfig(1000_ms32, 10000_ms32, 4000_ms16); ReliableMessageProtocolConfig deviceConfig(2000_ms32, 7000_ms32, 4000_ms16); - SecurePairingHandshakeTestCommon(inSuite, inContext, sessionManager, pairingCommissioner, + SecurePairingHandshakeTestCommon(sessionManager, pairingCommissioner, Optional::Value(commissionerConfig), Optional::Value(deviceConfig), delegateCommissioner); } -void SecurePairingHandshakeWithPacketLossTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingHandshakeWithPacketLossTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestSecurePairingDelegate delegateCommissioner; PASESession pairingCommissioner; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); loopback.mNumMessagesToDrop = 2; - SecurePairingHandshakeTestCommon(inSuite, inContext, sessionManager, pairingCommissioner, - Optional::Missing(), + SecurePairingHandshakeTestCommon(sessionManager, pairingCommissioner, Optional::Missing(), Optional::Missing(), delegateCommissioner); - NL_TEST_ASSERT(inSuite, loopback.mDroppedMessageCount == 2); - NL_TEST_ASSERT(inSuite, loopback.mNumMessagesToDrop == 0); + EXPECT_EQ(loopback.mDroppedMessageCount, 2u); + EXPECT_EQ(loopback.mNumMessagesToDrop, 0u); } -void SecurePairingFailedHandshake(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingFailedHandshake) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestSecurePairingDelegate delegateCommissioner; PASESession pairingCommissioner; @@ -469,98 +445,60 @@ void SecurePairingFailedHandshake(nlTestSuite * inSuite, void * inContext) TestSecurePairingDelegate delegateAccessory; PASESession pairingAccessory; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); loopback.mSentMessageCount = 0; - ExchangeContext * contextCommissioner = ctx.NewUnauthenticatedExchangeToBob(&pairingCommissioner); + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(&pairingCommissioner); - ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); ReliableMessageContext * rc = contextCommissioner->GetReliableMessageContext(); - NL_TEST_ASSERT(inSuite, rm != nullptr); - NL_TEST_ASSERT(inSuite, rc != nullptr); + ASSERT_NE(rm, nullptr); + ASSERT_NE(rc, nullptr); contextCommissioner->GetSessionHandle()->AsUnauthenticatedSession()->SetRemoteSessionParameters(ReliableMessageProtocolConfig({ 64_ms32, // CHIP_CONFIG_MRP_LOCAL_IDLE_RETRY_INTERVAL 64_ms32, // CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL })); - NL_TEST_ASSERT(inSuite, - ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType( - Protocols::SecureChannel::MsgType::PBKDFParamRequest, &pairingAccessory) == CHIP_NO_ERROR); - - NL_TEST_ASSERT(inSuite, - pairingAccessory.WaitForPairing( - sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, ByteSpan(sTestSpake2p01_Salt), - Optional::Missing(), &delegateAccessory) == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - - NL_TEST_ASSERT(inSuite, - pairingCommissioner.Pair(sessionManager, 4321, Optional::Missing(), - contextCommissioner, &delegateCommissioner) == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 0); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 1); + EXPECT_EQ(GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::PBKDFParamRequest, + &pairingAccessory), + CHIP_NO_ERROR); + + EXPECT_EQ(pairingAccessory.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, + ByteSpan(sTestSpake2p01_Salt), Optional::Missing(), + &delegateAccessory), + CHIP_NO_ERROR); + DrainAndServiceIO(); + + EXPECT_EQ(pairingCommissioner.Pair(sessionManager, 4321, Optional::Missing(), + contextCommissioner, &delegateCommissioner), + CHIP_NO_ERROR); + DrainAndServiceIO(); + + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 0u); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 1u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 1u); } -void PASEVerifierSerializeTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, PASEVerifierSerializeTest) { Spake2pVerifier verifier; - NL_TEST_ASSERT(inSuite, verifier.Deserialize(ByteSpan(sTestSpake2p01_SerializedVerifier)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(&verifier, &sTestSpake2p01_PASEVerifier, sizeof(Spake2pVerifier)) == 0); + EXPECT_EQ(verifier.Deserialize(ByteSpan(sTestSpake2p01_SerializedVerifier)), CHIP_NO_ERROR); + EXPECT_EQ(memcmp(&verifier, &sTestSpake2p01_PASEVerifier, sizeof(Spake2pVerifier)), 0); Spake2pVerifierSerialized serializedVerifier; MutableByteSpan serializedVerifierSpan(serializedVerifier); - NL_TEST_ASSERT(inSuite, verifier.Serialize(serializedVerifierSpan) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, serializedVerifierSpan.size() == kSpake2p_VerifierSerialized_Length); - NL_TEST_ASSERT(inSuite, memcmp(serializedVerifier, sTestSpake2p01_SerializedVerifier, kSpake2p_VerifierSerialized_Length) == 0); + EXPECT_EQ(verifier.Serialize(serializedVerifierSpan), CHIP_NO_ERROR); + EXPECT_EQ(serializedVerifierSpan.size(), kSpake2p_VerifierSerialized_Length); + EXPECT_EQ(memcmp(serializedVerifier, sTestSpake2p01_SerializedVerifier, kSpake2p_VerifierSerialized_Length), 0); Spake2pVerifierSerialized serializedVerifier2; MutableByteSpan serializedVerifier2Span(serializedVerifier2); - NL_TEST_ASSERT(inSuite, chip::Crypto::DRBG_get_bytes(serializedVerifier, kSpake2p_VerifierSerialized_Length) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, verifier.Deserialize(ByteSpan(serializedVerifier)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, verifier.Serialize(serializedVerifier2Span) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(serializedVerifier, serializedVerifier2, kSpake2p_VerifierSerialized_Length) == 0); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(serializedVerifier, kSpake2p_VerifierSerialized_Length), CHIP_NO_ERROR); + EXPECT_EQ(verifier.Deserialize(ByteSpan(serializedVerifier)), CHIP_NO_ERROR); + EXPECT_EQ(verifier.Serialize(serializedVerifier2Span), CHIP_NO_ERROR); + EXPECT_EQ(memcmp(serializedVerifier, serializedVerifier2, kSpake2p_VerifierSerialized_Length), 0); } - -// Test Suite - -static const nlTest sTests[] = { - NL_TEST_DEF("WaitInit", SecurePairingWaitTest), - NL_TEST_DEF("Start", SecurePairingStartTest), - NL_TEST_DEF("Handshake", SecurePairingHandshakeTest), - NL_TEST_DEF("Handshake with Commissioner MRP Parameters", SecurePairingHandshakeWithCommissionerMRPTest), - NL_TEST_DEF("Handshake with Device MRP Parameters", SecurePairingHandshakeWithDeviceMRPTest), - NL_TEST_DEF("Handshake with Both MRP Parameters", SecurePairingHandshakeWithAllMRPTest), - NL_TEST_DEF("Handshake with packet loss", SecurePairingHandshakeWithPacketLossTest), - NL_TEST_DEF("Failed Handshake", SecurePairingFailedHandshake), - NL_TEST_DEF("PASE Verifier Serialize", PASEVerifierSerializeTest), - NL_TEST_SENTINEL(), -}; - -// clang-format off -static nlTestSuite sSuite = -{ - "Test-CHIP-SecurePairing-PASE", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; -// clang-format on - -} // anonymous namespace - -/** - * Main - */ -int TestPASESession() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestPASESession) +} // namespace diff --git a/src/protocols/secure_channel/tests/TestPairingSession.cpp b/src/protocols/secure_channel/tests/TestPairingSession.cpp index 4a3fe88d55c7aa..5a12f61fc5c69e 100644 --- a/src/protocols/secure_channel/tests/TestPairingSession.cpp +++ b/src/protocols/secure_channel/tests/TestPairingSession.cpp @@ -22,11 +22,11 @@ */ #include -#include +#include #include #include -#include + #include #include #include @@ -36,9 +36,16 @@ using namespace chip; using namespace chip::System::Clock; -class TestPairingSession : public PairingSession +class TestPairingSession : public PairingSession, public ::testing::Test { public: + static void SetUpTestSuite() + { + CHIP_ERROR error = chip::Platform::MemoryInit(); + ASSERT_EQ(error, CHIP_NO_ERROR); + } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } + Transport::SecureSession::Type GetSecureSessionType() const override { return Transport::SecureSession::Type::kPASE; } ScopedNodeId GetPeer() const override { return ScopedNodeId(); } ScopedNodeId GetLocalScopedNodeId() const override { return ScopedNodeId(); } @@ -56,10 +63,8 @@ class TestPairingSession : public PairingSession } }; -void PairingSessionEncodeDecodeMRPParams(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPairingSession, PairingSessionEncodeDecodeMRPParams) { - TestPairingSession session; - ReliableMessageProtocolConfig config(Milliseconds32(100), Milliseconds32(200), Milliseconds16(4000)); System::PacketBufferHandle buf = System::PacketBufferHandle::New(64, 0); @@ -67,108 +72,48 @@ void PairingSessionEncodeDecodeMRPParams(nlTestSuite * inSuite, void * inContext writer.Init(buf.Retain()); TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified; - NL_TEST_ASSERT(inSuite, - writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType) == CHIP_NO_ERROR); + EXPECT_EQ(writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, PairingSession::EncodeSessionParameters(TLV::ContextTag(1), config, writer) == CHIP_NO_ERROR); + EXPECT_EQ(PairingSession::EncodeSessionParameters(TLV::ContextTag(1), config, writer), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, writer.EndContainer(outerContainerType) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, writer.Finalize(&buf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.EndContainer(outerContainerType), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&buf), CHIP_NO_ERROR); System::PacketBufferTLVReader reader; TLV::TLVType containerType = TLV::kTLVType_Structure; reader.Init(std::move(buf)); - NL_TEST_ASSERT(inSuite, reader.Next(containerType, TLV::AnonymousTag()) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reader.EnterContainer(containerType) == CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(containerType, TLV::AnonymousTag()), CHIP_NO_ERROR); + EXPECT_EQ(reader.EnterContainer(containerType), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reader.Next() == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, session.DecodeMRPParametersIfPresent(TLV::ContextTag(1), reader) == CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(), CHIP_NO_ERROR); + EXPECT_EQ(DecodeMRPParametersIfPresent(TLV::ContextTag(1), reader), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, session.GetRemoteMRPConfig() == config); + EXPECT_EQ(GetRemoteMRPConfig(), config); } -void PairingSessionTryDecodeMissingMRPParams(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPairingSession, PairingSessionTryDecodeMissingMRPParams) { - TestPairingSession session; - System::PacketBufferHandle buf = System::PacketBufferHandle::New(64, 0); System::PacketBufferTLVWriter writer; writer.Init(buf.Retain()); TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified; - NL_TEST_ASSERT(inSuite, - writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, writer.Put(TLV::ContextTag(1), static_cast(0x1234)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, writer.EndContainer(outerContainerType) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, writer.Finalize(&buf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType), CHIP_NO_ERROR); + EXPECT_EQ(writer.Put(TLV::ContextTag(1), static_cast(0x1234)), CHIP_NO_ERROR); + EXPECT_EQ(writer.EndContainer(outerContainerType), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&buf), CHIP_NO_ERROR); System::PacketBufferTLVReader reader; TLV::TLVType containerType = TLV::kTLVType_Structure; reader.Init(std::move(buf)); - NL_TEST_ASSERT(inSuite, reader.Next(containerType, TLV::AnonymousTag()) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reader.EnterContainer(containerType) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reader.Next() == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, session.DecodeMRPParametersIfPresent(TLV::ContextTag(2), reader) == CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(containerType, TLV::AnonymousTag()), CHIP_NO_ERROR); + EXPECT_EQ(reader.EnterContainer(containerType), CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(), CHIP_NO_ERROR); + EXPECT_EQ(DecodeMRPParametersIfPresent(TLV::ContextTag(2), reader), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, session.GetRemoteMRPConfig() == GetDefaultMRPConfig()); + EXPECT_EQ(GetRemoteMRPConfig(), GetDefaultMRPConfig()); } // Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("Encode and Decode MRP params", PairingSessionEncodeDecodeMRPParams), - NL_TEST_DEF("Decode missing MRP params", PairingSessionTryDecodeMissingMRPParams), - - NL_TEST_SENTINEL() -}; -// clang-format on - -/** - * Set up the test suite. - */ -int TestPairingSession_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int TestPairingSession_Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -// clang-format off -static nlTestSuite sSuite = -{ - "Test-CHIP-PairingSession", - &sTests[0], - TestPairingSession_Setup, - TestPairingSession_Teardown -}; -// clang-format on - -/** - * Main - */ -int TestPairingSessionInit() -{ - // Run test suit against one context - nlTestRunner(&sSuite, nullptr); - - return (nlTestRunnerStats(&sSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestPairingSessionInit) diff --git a/src/protocols/secure_channel/tests/TestSimpleSessionResumptionStorage.cpp b/src/protocols/secure_channel/tests/TestSimpleSessionResumptionStorage.cpp index cb511f6993c57d..ee107f695542a9 100644 --- a/src/protocols/secure_channel/tests/TestSimpleSessionResumptionStorage.cpp +++ b/src/protocols/secure_channel/tests/TestSimpleSessionResumptionStorage.cpp @@ -15,8 +15,7 @@ * limitations under the License. */ -#include -#include +#include #include #include @@ -26,27 +25,27 @@ constexpr chip::NodeId node1 = 12344321; constexpr chip::FabricIndex fabric2 = 14; constexpr chip::NodeId node2 = 11223344; -void TestLink(nlTestSuite * inSuite, void * inContext) +TEST(TestSimpleSessionResumptionStorage, TestLink) { chip::TestPersistentStorageDelegate storage; chip::SimpleSessionResumptionStorage sessionStorage; sessionStorage.Init(&storage); chip::SimpleSessionResumptionStorage::ResumptionIdStorage resumptionId; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(resumptionId.data(), resumptionId.size())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(resumptionId.data(), resumptionId.size()), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.SaveLink(resumptionId, chip::ScopedNodeId(node1, fabric1))); + EXPECT_EQ(sessionStorage.SaveLink(resumptionId, chip::ScopedNodeId(node1, fabric1)), CHIP_NO_ERROR); chip::ScopedNodeId node; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.LoadLink(resumptionId, node)); - NL_TEST_ASSERT(inSuite, node == chip::ScopedNodeId(node1, fabric1)); + EXPECT_EQ(sessionStorage.LoadLink(resumptionId, node), CHIP_NO_ERROR); + EXPECT_EQ(node, chip::ScopedNodeId(node1, fabric1)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.DeleteLink(resumptionId)); + EXPECT_EQ(sessionStorage.DeleteLink(resumptionId), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND == sessionStorage.LoadLink(resumptionId, node)); + EXPECT_EQ(sessionStorage.LoadLink(resumptionId, node), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } -void TestState(nlTestSuite * inSuite, void * inContext) +TEST(TestSimpleSessionResumptionStorage, TestState) { chip::TestPersistentStorageDelegate storage; chip::SimpleSessionResumptionStorage sessionStorage; @@ -55,31 +54,30 @@ void TestState(nlTestSuite * inSuite, void * inContext) chip::ScopedNodeId node(node1, fabric1); chip::SimpleSessionResumptionStorage::ResumptionIdStorage resumptionId; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(resumptionId.data(), resumptionId.size())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(resumptionId.data(), resumptionId.size()), CHIP_NO_ERROR); chip::Crypto::P256ECDHDerivedSecret sharedSecret; sharedSecret.SetLength(sharedSecret.Capacity()); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length()), CHIP_NO_ERROR); chip::CATValues peerCATs; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.SaveState(node, resumptionId, sharedSecret, peerCATs)); + EXPECT_EQ(sessionStorage.SaveState(node, resumptionId, sharedSecret, peerCATs), CHIP_NO_ERROR); chip::SimpleSessionResumptionStorage::ResumptionIdStorage resumptionId2; chip::Crypto::P256ECDHDerivedSecret sharedSecret2; chip::CATValues peerCATs2; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.LoadState(node, resumptionId2, sharedSecret2, peerCATs2)); - NL_TEST_ASSERT(inSuite, resumptionId == resumptionId2); - NL_TEST_ASSERT(inSuite, memcmp(sharedSecret.Bytes(), sharedSecret2.Bytes(), sharedSecret.Length()) == 0); + EXPECT_EQ(sessionStorage.LoadState(node, resumptionId2, sharedSecret2, peerCATs2), CHIP_NO_ERROR); + EXPECT_EQ(resumptionId, resumptionId2); + EXPECT_EQ(memcmp(sharedSecret.Bytes(), sharedSecret2.Bytes(), sharedSecret.Length()), 0); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.DeleteState(node)); + EXPECT_EQ(sessionStorage.DeleteState(node), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND == - sessionStorage.LoadState(node, resumptionId2, sharedSecret2, peerCATs2)); + EXPECT_EQ(sessionStorage.LoadState(node, resumptionId2, sharedSecret2, peerCATs2), + CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } -void TestIndex(nlTestSuite * inSuite, void * inContext) +TEST(TestSimpleSessionResumptionStorage, TestIndex) { chip::TestPersistentStorageDelegate storage; chip::SimpleSessionResumptionStorage sessionStorage; @@ -88,63 +86,26 @@ void TestIndex(nlTestSuite * inSuite, void * inContext) chip::ScopedNodeId node(node1, fabric1); chip::DefaultSessionResumptionStorage::SessionIndex index0o; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.LoadIndex(index0o)); - NL_TEST_ASSERT(inSuite, index0o.mSize == 0); + EXPECT_EQ(sessionStorage.LoadIndex(index0o), CHIP_NO_ERROR); + EXPECT_EQ(index0o.mSize, 0u); chip::DefaultSessionResumptionStorage::SessionIndex index1; index1.mSize = 0; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.SaveIndex(index1)); + EXPECT_EQ(sessionStorage.SaveIndex(index1), CHIP_NO_ERROR); chip::DefaultSessionResumptionStorage::SessionIndex index1o; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.LoadIndex(index1o)); - NL_TEST_ASSERT(inSuite, index1o.mSize == 0); + EXPECT_EQ(sessionStorage.LoadIndex(index1o), CHIP_NO_ERROR); + EXPECT_EQ(index1o.mSize, 0u); chip::DefaultSessionResumptionStorage::SessionIndex index2; index2.mSize = 2; index2.mNodes[0] = chip::ScopedNodeId(node1, fabric1); index2.mNodes[1] = chip::ScopedNodeId(node2, fabric2); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.SaveIndex(index2)); + EXPECT_EQ(CHIP_NO_ERROR, sessionStorage.SaveIndex(index2)); chip::DefaultSessionResumptionStorage::SessionIndex index2o; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.LoadIndex(index2o)); - NL_TEST_ASSERT(inSuite, index2o.mSize == 2); - NL_TEST_ASSERT(inSuite, index2o.mNodes[0] == chip::ScopedNodeId(node1, fabric1)); - NL_TEST_ASSERT(inSuite, index2o.mNodes[1] == chip::ScopedNodeId(node2, fabric2)); + EXPECT_EQ(CHIP_NO_ERROR, sessionStorage.LoadIndex(index2o)); + EXPECT_EQ(index2o.mSize, 2u); + EXPECT_EQ(index2o.mNodes[0], chip::ScopedNodeId(node1, fabric1)); + EXPECT_EQ(index2o.mNodes[1], chip::ScopedNodeId(node2, fabric2)); } // Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("TestLink", TestLink), - NL_TEST_DEF("TestState", TestState), - NL_TEST_DEF("TestIndex", TestState), - - NL_TEST_SENTINEL() -}; -// clang-format on - -// clang-format off -static nlTestSuite sSuite = -{ - "Test-CHIP-SimpleSessionResumptionStorage", - &sTests[0], - nullptr, - nullptr, -}; -// clang-format on - -/** - * Main - */ -int TestSimpleSessionResumptionStorage() -{ - // Run test suit against one context - nlTestRunner(&sSuite, nullptr); - - return (nlTestRunnerStats(&sSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestSimpleSessionResumptionStorage) diff --git a/src/protocols/secure_channel/tests/TestStatusReport.cpp b/src/protocols/secure_channel/tests/TestStatusReport.cpp index 093453029b156b..65bc639dcca7c3 100644 --- a/src/protocols/secure_channel/tests/TestStatusReport.cpp +++ b/src/protocols/secure_channel/tests/TestStatusReport.cpp @@ -19,19 +19,29 @@ #include #include #include -#include + #include #include #include #include -#include +#include using namespace chip; using namespace chip::Protocols; using namespace chip::Protocols::SecureChannel; -void TestStatusReport_NoData(nlTestSuite * inSuite, void * inContext) +struct TestStatusReport : public ::testing::Test +{ + static void SetUpTestSuite() + { + CHIP_ERROR error = chip::Platform::MemoryInit(); + ASSERT_EQ(error, CHIP_NO_ERROR); + } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestStatusReport, NoData) { GeneralStatusCode generalCode = GeneralStatusCode::kSuccess; auto protocolId = SecureChannel::Id; @@ -44,20 +54,19 @@ void TestStatusReport_NoData(nlTestSuite * inSuite, void * inContext) testReport.WriteToBuffer(bbuf); System::PacketBufferHandle msgBuf = bbuf.Finalize(); - NL_TEST_ASSERT(inSuite, !msgBuf.IsNull()); + ASSERT_FALSE(msgBuf.IsNull()); StatusReport reportToParse; - CHIP_ERROR err = reportToParse.Parse(std::move(msgBuf)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reportToParse.GetGeneralCode() == generalCode); - NL_TEST_ASSERT(inSuite, reportToParse.GetProtocolId() == protocolId); - NL_TEST_ASSERT(inSuite, reportToParse.GetProtocolCode() == protocolCode); + EXPECT_EQ(reportToParse.Parse(std::move(msgBuf)), CHIP_NO_ERROR); + EXPECT_EQ(reportToParse.GetGeneralCode(), generalCode); + EXPECT_EQ(reportToParse.GetProtocolId(), protocolId); + EXPECT_EQ(reportToParse.GetProtocolCode(), protocolCode); const System::PacketBufferHandle & data = reportToParse.GetProtocolData(); - NL_TEST_ASSERT(inSuite, data.IsNull()); + EXPECT_TRUE(data.IsNull()); } -void TestStatusReport_WithData(nlTestSuite * inSuite, void * inContext) +TEST_F(TestStatusReport, WithData) { GeneralStatusCode generalCode = GeneralStatusCode::kFailure; auto protocolId = SecureChannel::Id; @@ -73,39 +82,34 @@ void TestStatusReport_WithData(nlTestSuite * inSuite, void * inContext) testReport.WriteToBuffer(bbuf); System::PacketBufferHandle msgBuf = bbuf.Finalize(); - NL_TEST_ASSERT(inSuite, !msgBuf.IsNull()); + ASSERT_FALSE(msgBuf.IsNull()); StatusReport reportToParse; - CHIP_ERROR err = reportToParse.Parse(std::move(msgBuf)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reportToParse.GetGeneralCode() == generalCode); - NL_TEST_ASSERT(inSuite, reportToParse.GetProtocolId() == protocolId); - NL_TEST_ASSERT(inSuite, reportToParse.GetProtocolCode() == protocolCode); + EXPECT_EQ(reportToParse.Parse(std::move(msgBuf)), CHIP_NO_ERROR); + EXPECT_EQ(reportToParse.GetGeneralCode(), generalCode); + EXPECT_EQ(reportToParse.GetProtocolId(), protocolId); + EXPECT_EQ(reportToParse.GetProtocolCode(), protocolCode); const System::PacketBufferHandle & rcvData = reportToParse.GetProtocolData(); - if (rcvData.IsNull()) - { - NL_TEST_ASSERT(inSuite, false); - return; - } - NL_TEST_ASSERT(inSuite, rcvData->DataLength() == dataLen); - NL_TEST_ASSERT(inSuite, !memcmp(rcvData->Start(), data, dataLen)); + ASSERT_FALSE(rcvData.IsNull()); + EXPECT_EQ(rcvData->DataLength(), dataLen); + EXPECT_EQ(memcmp(rcvData->Start(), data, dataLen), 0); } -void TestBadStatusReport(nlTestSuite * inSuite, void * inContext) +TEST_F(TestStatusReport, TestBadStatusReport) { StatusReport report; System::PacketBufferHandle badMsg = System::PacketBufferHandle::New(10); CHIP_ERROR err = report.Parse(std::move(badMsg)); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); StatusReport report2; badMsg = nullptr; err = report2.Parse(std::move(badMsg)); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); } -void TestMakeBusyStatusReport(nlTestSuite * inSuite, void * inContext) +TEST_F(TestStatusReport, TestMakeBusyStatusReport) { GeneralStatusCode generalCode = GeneralStatusCode::kBusy; auto protocolId = SecureChannel::Id; @@ -113,81 +117,22 @@ void TestMakeBusyStatusReport(nlTestSuite * inSuite, void * inContext) System::Clock::Milliseconds16 minimumWaitTime = System::Clock::Milliseconds16(5000); System::PacketBufferHandle handle = StatusReport::MakeBusyStatusReportMessage(minimumWaitTime); - NL_TEST_ASSERT(inSuite, !handle.IsNull()); + ASSERT_FALSE(handle.IsNull()); StatusReport reportToParse; - CHIP_ERROR err = reportToParse.Parse(std::move(handle)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == err); - NL_TEST_ASSERT(inSuite, reportToParse.GetGeneralCode() == generalCode); - NL_TEST_ASSERT(inSuite, reportToParse.GetProtocolId() == protocolId); - NL_TEST_ASSERT(inSuite, reportToParse.GetProtocolCode() == protocolCode); + EXPECT_EQ(reportToParse.Parse(std::move(handle)), CHIP_NO_ERROR); + EXPECT_EQ(reportToParse.GetGeneralCode(), generalCode); + EXPECT_EQ(reportToParse.GetProtocolId(), protocolId); + EXPECT_EQ(reportToParse.GetProtocolCode(), protocolCode); const System::PacketBufferHandle & rcvData = reportToParse.GetProtocolData(); - NL_TEST_ASSERT(inSuite, !rcvData.IsNull()); - NL_TEST_ASSERT(inSuite, rcvData->DataLength() == sizeof(minimumWaitTime)); + ASSERT_FALSE(rcvData.IsNull()); + EXPECT_EQ(rcvData->DataLength(), sizeof(minimumWaitTime)); uint16_t readMinimumWaitTime = 0; Encoding::LittleEndian::Reader reader(rcvData->Start(), rcvData->DataLength()); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == reader.Read16(&readMinimumWaitTime).StatusCode()); - NL_TEST_ASSERT(inSuite, System::Clock::Milliseconds16(readMinimumWaitTime) == minimumWaitTime); + EXPECT_EQ(reader.Read16(&readMinimumWaitTime).StatusCode(), CHIP_NO_ERROR); + EXPECT_EQ(System::Clock::Milliseconds16(readMinimumWaitTime), minimumWaitTime); } // Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("TestStatusReport_NoData", TestStatusReport_NoData), - NL_TEST_DEF("TestStatusReport_WithData", TestStatusReport_WithData), - NL_TEST_DEF("TestBadStatusReport", TestBadStatusReport), - NL_TEST_DEF("TestMakeBusyStatusReport", TestMakeBusyStatusReport), - - NL_TEST_SENTINEL() -}; -// clang-format on - -/** - * Set up the test suite. - */ -static int TestSetup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -static int TestTeardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -// clang-format off -static nlTestSuite sSuite = -{ - "Test-CHIP-StatusReport", - &sTests[0], - TestSetup, - TestTeardown, -}; -// clang-format on - -/** - * Main - */ -int TestStatusReport() -{ - // Run test suit against one context - nlTestRunner(&sSuite, nullptr); - - return (nlTestRunnerStats(&sSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestStatusReport) diff --git a/src/system/tests/BUILD.gn b/src/system/tests/BUILD.gn index 2f2fd4de0a6a6d..01965170ab9b0c 100644 --- a/src/system/tests/BUILD.gn +++ b/src/system/tests/BUILD.gn @@ -46,6 +46,7 @@ chip_test_suite("tests") { public_deps = [ "${chip_root}/src/inet", + "${chip_root}/src/lib/support/tests:pw-test-macros", "${chip_root}/src/platform", "${chip_root}/src/system", ] diff --git a/src/system/tests/TestSystemPacketBuffer.cpp b/src/system/tests/TestSystemPacketBuffer.cpp index c71ad542d6225a..bf1456487307a3 100644 --- a/src/system/tests/TestSystemPacketBuffer.cpp +++ b/src/system/tests/TestSystemPacketBuffer.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include #include @@ -192,16 +193,6 @@ class TestSystemPacketBuffer : public ::testing::Test void CheckSetStart(); }; -/* - * Run fixture's class function as a test. - */ -#define TEST_F_FROM_FIXTURE(test_fixture, test_name) \ - TEST_F(test_fixture, test_name) \ - { \ - test_name(); \ - } \ - void test_fixture::test_name() - /** * Allocate memory for a test buffer and configure according to test buffer configuration. */ diff --git a/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt b/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt index 925be3fdd2b499..6c038b398d914f 100644 --- a/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt +++ b/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt @@ -1,2 +1 @@ -AppTestsNL -SecureChannelTestsNL +AppTestsNL \ No newline at end of file