From 007e11d084abbf88d0d14816d13e15515bf26cb0 Mon Sep 17 00:00:00 2001 From: Amine Alami <43780877+Alami-Amine@users.noreply.github.com> Date: Wed, 1 May 2024 15:10:59 +0200 Subject: [PATCH 1/3] pw_unit_test migration: lib support batch 5 (#33238) * pw_unit_test migration: lib support batch 5 * pw_unit_test migration: lib support batch 4 (#33199) * pw_unit_test migration: lib support batch 4 * fix merge error BUILD.gn * pw_unit_test migration: lib support batch 5 * newline * removing commented-out code * convert TestCHIPArgParser test --- src/BUILD.gn | 1 - src/lib/support/tests/BUILD.gn | 39 +-- src/lib/support/tests/TestCHIPArgParser.cpp | 214 +++++-------- src/lib/support/tests/TestPool.cpp | 293 ++++++++---------- src/lib/support/tests/TestStateMachine.cpp | 123 +++----- .../tests/TestThreadOperationalDataset.cpp | 200 +++++------- .../unit-tests/test_components_nl.txt | 1 - 7 files changed, 342 insertions(+), 529 deletions(-) diff --git a/src/BUILD.gn b/src/BUILD.gn index 8fedfa15e43fd8..aa657786cd2469 100644 --- a/src/BUILD.gn +++ b/src/BUILD.gn @@ -99,7 +99,6 @@ if (chip_build_tests) { "${chip_root}/src/credentials/tests", "${chip_root}/src/lib/format/tests", "${chip_root}/src/lib/support/tests", - "${chip_root}/src/lib/support/tests:tests_nltest", "${chip_root}/src/protocols/secure_channel/tests", "${chip_root}/src/protocols/secure_channel/tests:tests_nltest", "${chip_root}/src/system/tests", diff --git a/src/lib/support/tests/BUILD.gn b/src/lib/support/tests/BUILD.gn index 485402003fd4dd..565eb85097d133 100644 --- a/src/lib/support/tests/BUILD.gn +++ b/src/lib/support/tests/BUILD.gn @@ -40,6 +40,7 @@ chip_test_suite("tests") { "TestJsonToTlv.cpp", "TestJsonToTlvToJson.cpp", "TestPersistedCounter.cpp", + "TestPool.cpp", "TestPrivateHeap.cpp", "TestSafeInt.cpp", "TestSafeString.cpp", @@ -47,10 +48,12 @@ chip_test_suite("tests") { "TestScopedBuffer.cpp", "TestSorting.cpp", "TestSpan.cpp", + "TestStateMachine.cpp", "TestStaticSupportSmartPtr.cpp", "TestStringBuilder.cpp", "TestStringSplitter.cpp", "TestTestPersistentStorageDelegate.cpp", + "TestThreadOperationalDataset.cpp", "TestTimeUtils.cpp", "TestTlvJson.cpp", "TestTlvToJson.cpp", @@ -58,42 +61,12 @@ chip_test_suite("tests") { "TestVariant.cpp", "TestZclString.cpp", ] - sources = [] - - cflags = [ - "-Wconversion", - - # TODO(#21255): work-around for SimpleStateMachine constructor issue. - "-Wno-uninitialized", - - # TestStringSplitter intentionally validates string overflows. - "-Wno-stringop-truncation", - ] - - public_deps = [ - "${chip_root}/src/credentials", - "${chip_root}/src/lib/core", - "${chip_root}/src/lib/support:static-support", - "${chip_root}/src/lib/support:testing", - "${chip_root}/src/lib/support/jsontlv", - "${chip_root}/src/platform", - ] -} - -chip_test_suite_using_nltest("tests_nltest") { - output_name = "libSupportTestsNL" - - test_sources = [ - "TestPool.cpp", - "TestStateMachine.cpp", - "TestThreadOperationalDataset.cpp", - ] - sources = [] - if (current_os != "mbed") { test_sources += [ "TestCHIPArgParser.cpp" ] } + sources = [] + cflags = [ "-Wconversion", @@ -109,9 +82,7 @@ chip_test_suite_using_nltest("tests_nltest") { "${chip_root}/src/lib/core", "${chip_root}/src/lib/support:static-support", "${chip_root}/src/lib/support:testing", - "${chip_root}/src/lib/support:testing_nlunit", "${chip_root}/src/lib/support/jsontlv", "${chip_root}/src/platform", - "${nlunit_test_root}:nlunit-test", ] } diff --git a/src/lib/support/tests/TestCHIPArgParser.cpp b/src/lib/support/tests/TestCHIPArgParser.cpp index c54e0223ca7e07..426758aff1e5c8 100644 --- a/src/lib/support/tests/TestCHIPArgParser.cpp +++ b/src/lib/support/tests/TestCHIPArgParser.cpp @@ -22,17 +22,16 @@ #include #include +#include + #include #include #include #include #include #include -#include #include -#if CHIP_CONFIG_ENABLE_ARG_PARSER - using namespace chip::ArgParser; static bool HandleOption(const char * progName, OptionSet * optSet, int id, const char * name, const char * arg); @@ -40,71 +39,68 @@ static bool HandleNonOptionArgs(const char * progName, int argc, char * const ar static void HandleArgError(const char * msg, ...); static void ClearCallbackRecords(); -#define DEBUG_TESTS 0 - -#define QuitWithError(MSG) \ - do \ - { \ - fprintf(stderr, "%s FAILED (line %d): ", __FUNCTION__, __LINE__); \ - fputs(MSG, stderr); \ - fputs("\n", stderr); \ - exit(EXIT_FAILURE); \ - } while (0) +class TestCHIPArgParser : public ::testing::Test +{ +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() + { + ClearCallbackRecords(); + chip::Platform::MemoryShutdown(); + } +}; -#define VerifyOrQuit(TST, MSG) \ - do \ - { \ - if (!(TST)) \ - { \ - QuitWithError(MSG); \ - } \ - } while (0) +#define DEBUG_TESTS 0 #define VerifyHandleOptionCallback(INDEX, EXPECT_PROG_NAME, EXPECT_OPTSET, EXPECT_ID, EXPECT_NAME, EXPECT_ARG) \ do \ { \ CallbackRecord & rec = sCallbackRecords[INDEX]; \ const char * arg = EXPECT_ARG; \ - VerifyOrQuit(rec.Type == CallbackRecord::kHandleOption, "Invalid callback type (expected HandleOption)"); \ - VerifyOrQuit(strcmp(rec.ProgName, EXPECT_PROG_NAME) == 0, "Invalid value for HandleOption argument: progName"); \ - VerifyOrQuit(rec.OptSet == EXPECT_OPTSET, "Invalid value for HandleOption argument: optSet"); \ - VerifyOrQuit(rec.Id == EXPECT_ID, "Invalid value for HandleOption argument: id"); \ - VerifyOrQuit(strcmp(rec.Name, EXPECT_NAME) == 0, "Invalid value for HandleOption argument: name"); \ + ASSERT_EQ(rec.Type, CallbackRecord::kHandleOption) << "Invalid callback type (expected HandleOption)"; \ + ASSERT_STREQ(rec.ProgName, EXPECT_PROG_NAME) << "Invalid value for HandleOption argument: progName"; \ + ASSERT_EQ(rec.OptSet, EXPECT_OPTSET) << "Invalid value for HandleOption argument: optSet"; \ + ASSERT_EQ(rec.Id, EXPECT_ID) << "Invalid value for HandleOption argument: id"; \ + ASSERT_STREQ(rec.Name, EXPECT_NAME) << "Invalid value for HandleOption argument: name"; \ if (arg != NULL) \ - VerifyOrQuit(strcmp(rec.Arg, arg) == 0, "Invalid value for HandleOption argument: arg"); \ + { \ + ASSERT_STREQ(rec.Arg, arg) << "Invalid value for HandleOption argument: arg"; \ + } \ else \ - VerifyOrQuit(rec.Arg == NULL, "Invalid value for HandleOption argument: arg"); \ + { \ + ASSERT_EQ(rec.Arg, nullptr) << "Invalid value for HandleOption argument: arg"; \ + } \ } while (0) #define VerifyHandleNonOptionArgsCallback(INDEX, EXPECT_PROG_NAME, EXPECT_ARGC) \ do \ { \ CallbackRecord & rec = sCallbackRecords[INDEX]; \ - VerifyOrQuit(rec.Type == CallbackRecord::kHandleNonOptionArgs, "Invalid callback type (expected HandleNonOptionArgs)"); \ - VerifyOrQuit(strcmp(rec.ProgName, EXPECT_PROG_NAME) == 0, "Invalid value for HandleNonOptionArgs argument: progName"); \ - VerifyOrQuit(rec.Argc == EXPECT_ARGC, "Invalid value for HandleNonOptionArgs argument: argc"); \ + ASSERT_EQ(rec.Type, CallbackRecord::kHandleNonOptionArgs) << "Invalid callback type (expected HandleNonOptionArgs)"; \ + ASSERT_STREQ(rec.ProgName, EXPECT_PROG_NAME) << "Invalid value for HandleNonOptionArgs argument: progName"; \ + ASSERT_EQ(rec.Argc, EXPECT_ARGC) << "Invalid value for HandleNonOptionArgs argument: argc"; \ } while (0) #define VerifyNonOptionArg(INDEX, EXPECT_ARG) \ do \ { \ CallbackRecord & rec = sCallbackRecords[INDEX]; \ - VerifyOrQuit(rec.Type == CallbackRecord::kNonOptionArg, "Invalid callback type (expected NonOptionArg)"); \ - VerifyOrQuit(strcmp(rec.Arg, EXPECT_ARG) == 0, "Invalid value for NonOptionArg"); \ + ASSERT_EQ(rec.Type, CallbackRecord::kNonOptionArg) << "Invalid callback type (expected NonOptionArg)"; \ + ASSERT_STREQ(rec.Arg, EXPECT_ARG) << "Invalid value for NonOptionArg"; \ } while (0) #define VerifyPrintArgErrorCallback(INDEX) \ do \ { \ CallbackRecord & rec = sCallbackRecords[INDEX]; \ - VerifyOrQuit(rec.Type == CallbackRecord::kArgError, "Invalid callback type (expected ArgError)"); \ + ASSERT_EQ(rec.Type, CallbackRecord::kArgError) << "Invalid callback type (expected ArgError)"; \ } while (0) #define VerifyArgErrorContains(INDEX, EXPECT_TEXT) \ do \ { \ CallbackRecord & rec = sCallbackRecords[INDEX]; \ - VerifyOrQuit(strstr(rec.Error, EXPECT_TEXT) != NULL, "Expected text not found in error output"); \ + ASSERT_NE(strstr(rec.Error, EXPECT_TEXT), nullptr) << "Expected text not found in error output"; \ } while (0) struct CallbackRecord @@ -212,7 +208,7 @@ TestArgv DupeArgs(const char * argv[], int argc_as_int) } // namespace -static void SimpleParseTest_SingleLongOption() +TEST_F(TestCHIPArgParser, SimpleParseTest_SingleLongOption) { bool res; @@ -232,13 +228,13 @@ static void SimpleParseTest_SingleLongOption() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs); - VerifyOrQuit(res == true, "ParseArgs() returned false"); - VerifyOrQuit(sCallbackRecordCount == 2, "Invalid value returned for sCallbackRecordCount"); + ASSERT_TRUE(res) << "ParseArgs() returned false"; + ASSERT_EQ(sCallbackRecordCount, 2u) << "Invalid value returned for sCallbackRecordCount"; VerifyHandleOptionCallback(0, __FUNCTION__, &sOptionSetA, '1', "--foo", nullptr); VerifyHandleNonOptionArgsCallback(1, __FUNCTION__, 0); } -static void SimpleParseTest_SingleShortOption() +TEST_F(TestCHIPArgParser, SimpleParseTest_SingleShortOption) { bool res; @@ -258,13 +254,13 @@ static void SimpleParseTest_SingleShortOption() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs); - VerifyOrQuit(res == true, "ParseArgs() returned false"); - VerifyOrQuit(sCallbackRecordCount == 2, "Invalid value returned for sCallbackRecordCount"); + ASSERT_TRUE(res) << "ParseArgs() returned false"; + ASSERT_EQ(sCallbackRecordCount, 2u) << "Invalid value returned for sCallbackRecordCount"; VerifyHandleOptionCallback(0, __FUNCTION__, &sOptionSetB, 's', "-s", nullptr); VerifyHandleNonOptionArgsCallback(1, __FUNCTION__, 0); } -static void SimpleParseTest_SingleLongOptionWithValue() +TEST_F(TestCHIPArgParser, SimpleParseTest_SingleLongOptionWithValue) { bool res; @@ -284,13 +280,13 @@ static void SimpleParseTest_SingleLongOptionWithValue() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs); - VerifyOrQuit(res == true, "ParseArgs() returned false"); - VerifyOrQuit(sCallbackRecordCount == 2, "Invalid value returned for sCallbackRecordCount"); + ASSERT_TRUE(res) << "ParseArgs() returned false"; + ASSERT_EQ(sCallbackRecordCount, 2u) << "Invalid value returned for sCallbackRecordCount"; VerifyHandleOptionCallback(0, __FUNCTION__, &sOptionSetB, 1000, "--run", "run-value"); VerifyHandleNonOptionArgsCallback(1, __FUNCTION__, 0); } -static void SimpleParseTest_SingleShortOptionWithValue() +TEST_F(TestCHIPArgParser, SimpleParseTest_SingleShortOptionWithValue) { bool res; @@ -310,13 +306,13 @@ static void SimpleParseTest_SingleShortOptionWithValue() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs); - VerifyOrQuit(res == true, "ParseArgs() returned false"); - VerifyOrQuit(sCallbackRecordCount == 2, "Invalid value returned for sCallbackRecordCount"); + ASSERT_TRUE(res) << "ParseArgs() returned false"; + ASSERT_EQ(sCallbackRecordCount, 2u) << "Invalid value returned for sCallbackRecordCount"; VerifyHandleOptionCallback(0, __FUNCTION__, &sOptionSetA, 'Z', "-Z", "baz-value"); VerifyHandleNonOptionArgsCallback(1, __FUNCTION__, 0); } -static void SimpleParseTest_VariousShortAndLongWithArgs() +TEST_F(TestCHIPArgParser, SimpleParseTest_VariousShortAndLongWithArgs) { bool res; @@ -345,8 +341,8 @@ static void SimpleParseTest_VariousShortAndLongWithArgs() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs); - VerifyOrQuit(res == true, "ParseArgs() returned false"); - VerifyOrQuit(sCallbackRecordCount == 12, "Invalid value returned for sCallbackRecordCount"); + ASSERT_TRUE(res) << "ParseArgs() returned false"; + ASSERT_EQ(sCallbackRecordCount, 12u) << "Invalid value returned for sCallbackRecordCount"; VerifyHandleOptionCallback(0, __FUNCTION__, &sOptionSetA, '1', "--foo", nullptr); VerifyHandleOptionCallback(1, __FUNCTION__, &sOptionSetB, 1000, "--run", "run-value"); VerifyHandleOptionCallback(2, __FUNCTION__, &sOptionSetB, 's', "-s", nullptr); @@ -361,7 +357,7 @@ static void SimpleParseTest_VariousShortAndLongWithArgs() VerifyNonOptionArg(11, "non-opt-arg-4"); } -static void UnknownOptionTest_UnknownShortOption() +TEST_F(TestCHIPArgParser, UnknownOptionTest_UnknownShortOption) { bool res; @@ -385,8 +381,8 @@ static void UnknownOptionTest_UnknownShortOption() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs); - VerifyOrQuit(res == false, "ParseArgs() returned true"); - VerifyOrQuit(sCallbackRecordCount == 3, "Invalid value returned for sCallbackRecordCount"); + ASSERT_FALSE(res) << "ParseArgs() returned true"; + ASSERT_EQ(sCallbackRecordCount, 3u) << "Invalid value returned for sCallbackRecordCount"; VerifyHandleOptionCallback(0, __FUNCTION__, &sOptionSetA, '1', "--foo", nullptr); VerifyHandleOptionCallback(1, __FUNCTION__, &sOptionSetB, 1000, "--run", "run-value"); VerifyPrintArgErrorCallback(2); @@ -394,7 +390,7 @@ static void UnknownOptionTest_UnknownShortOption() VerifyArgErrorContains(2, "-q"); } -static void UnknownOptionTest_UnknownLongOption() +TEST_F(TestCHIPArgParser, UnknownOptionTest_UnknownLongOption) { bool res; @@ -418,8 +414,8 @@ static void UnknownOptionTest_UnknownLongOption() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs); - VerifyOrQuit(res == false, "ParseArgs() returned true"); - VerifyOrQuit(sCallbackRecordCount == 3, "Invalid value returned for sCallbackRecordCount"); + ASSERT_FALSE(res) << "ParseArgs() returned true"; + ASSERT_EQ(sCallbackRecordCount, 3u) << "Invalid value returned for sCallbackRecordCount"; VerifyHandleOptionCallback(0, __FUNCTION__, &sOptionSetA, '1', "--foo", nullptr); VerifyHandleOptionCallback(1, __FUNCTION__, &sOptionSetB, 1000, "--run", "run-value"); VerifyPrintArgErrorCallback(2); @@ -427,7 +423,7 @@ static void UnknownOptionTest_UnknownLongOption() VerifyArgErrorContains(2, "--bad"); } -static void UnknownOptionTest_UnknownShortOptionAfterKnown() +TEST_F(TestCHIPArgParser, UnknownOptionTest_UnknownShortOptionAfterKnown) { bool res; @@ -451,8 +447,8 @@ static void UnknownOptionTest_UnknownShortOptionAfterKnown() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs); - VerifyOrQuit(res == false, "ParseArgs() returned true"); - VerifyOrQuit(sCallbackRecordCount == 4, "Invalid value returned for sCallbackRecordCount"); + ASSERT_FALSE(res) << "ParseArgs() returned true"; + ASSERT_EQ(sCallbackRecordCount, 4u) << "Invalid value returned for sCallbackRecordCount"; VerifyHandleOptionCallback(0, __FUNCTION__, &sOptionSetA, '1', "--foo", nullptr); VerifyHandleOptionCallback(1, __FUNCTION__, &sOptionSetB, 1000, "--run", "run-value"); VerifyHandleOptionCallback(2, __FUNCTION__, &sOptionSetA, '1', "-1", nullptr); @@ -461,7 +457,7 @@ static void UnknownOptionTest_UnknownShortOptionAfterKnown() VerifyArgErrorContains(3, "-Q"); } -static void UnknownOptionTest_UnknownShortOptionBeforeKnown() +TEST_F(TestCHIPArgParser, UnknownOptionTest_UnknownShortOptionBeforeKnown) { bool res; @@ -481,14 +477,14 @@ static void UnknownOptionTest_UnknownShortOptionBeforeKnown() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs); - VerifyOrQuit(res == false, "ParseArgs() returned true"); - VerifyOrQuit(sCallbackRecordCount == 1, "Invalid value returned for sCallbackRecordCount"); + ASSERT_FALSE(res) << "ParseArgs() returned true"; + ASSERT_EQ(sCallbackRecordCount, 1u) << "Invalid value returned for sCallbackRecordCount"; VerifyPrintArgErrorCallback(0); VerifyArgErrorContains(0, "Unknown"); VerifyArgErrorContains(0, "-Q"); } -static void UnknownOptionTest_UnknownShortOptionAfterArgs() +TEST_F(TestCHIPArgParser, UnknownOptionTest_UnknownShortOptionAfterArgs) { bool res; @@ -510,14 +506,14 @@ static void UnknownOptionTest_UnknownShortOptionAfterArgs() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs); - VerifyOrQuit(res == false, "ParseArgs() returned true"); - VerifyOrQuit(sCallbackRecordCount == 1, "Invalid value returned for sCallbackRecordCount"); + ASSERT_FALSE(res) << "ParseArgs() returned true"; + ASSERT_EQ(sCallbackRecordCount, 1u) << "Invalid value returned for sCallbackRecordCount"; VerifyPrintArgErrorCallback(0); VerifyArgErrorContains(0, "Unknown"); VerifyArgErrorContains(0, "-Q"); } -static void UnknownOptionTest_UnknownLongOptionAfterArgs() +TEST_F(TestCHIPArgParser, UnknownOptionTest_UnknownLongOptionAfterArgs) { bool res; @@ -539,15 +535,14 @@ static void UnknownOptionTest_UnknownLongOptionAfterArgs() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs); - VerifyOrQuit(res == false, "ParseArgs() returned true"); - VerifyOrQuit(sCallbackRecordCount == 1, "Invalid value returned for sCallbackRecordCount"); + ASSERT_FALSE(res) << "ParseArgs() returned true"; + ASSERT_EQ(sCallbackRecordCount, 1u) << "Invalid value returned for sCallbackRecordCount"; VerifyPrintArgErrorCallback(0); VerifyArgErrorContains(0, "Unknown"); VerifyArgErrorContains(0, "--barf"); } -#ifndef CHIP_CONFIG_NON_POSIX_LONG_OPT -static void UnknownOptionTest_IgnoreUnknownLongOption() +TEST_F(TestCHIPArgParser, UnknownOptionTest_IgnoreUnknownLongOption) { bool res; @@ -570,18 +565,17 @@ static void UnknownOptionTest_IgnoreUnknownLongOption() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs, true); - VerifyOrQuit(res == true, "ParseArgs() returned false"); + ASSERT_TRUE(res) << "ParseArgs() returned false"; - VerifyOrQuit(sCallbackRecordCount == 4, "Invalid value returned for sCallbackRecordCount"); + ASSERT_EQ(sCallbackRecordCount, 4u) << "Invalid value returned for sCallbackRecordCount"; VerifyHandleOptionCallback(0, __FUNCTION__, &sOptionSetA, 'Z', "-Z", "baz-value"); VerifyHandleNonOptionArgsCallback(1, __FUNCTION__, 2); VerifyNonOptionArg(2, "non-opt-arg-1"); VerifyNonOptionArg(3, "non-opt-arg-2"); } -#endif // !CHIP_CONFIG_NON_POSIX_LONG_OPT -static void UnknownOptionTest_IgnoreUnknownShortOption() +TEST_F(TestCHIPArgParser, UnknownOptionTest_IgnoreUnknownShortOption) { bool res; @@ -604,9 +598,9 @@ static void UnknownOptionTest_IgnoreUnknownShortOption() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs, true); - VerifyOrQuit(res == true, "ParseArgs() returned false"); + ASSERT_TRUE(res) << "ParseArgs() returned false"; - VerifyOrQuit(sCallbackRecordCount == 5, "Invalid value returned for sCallbackRecordCount"); + ASSERT_EQ(sCallbackRecordCount, 5u) << "Invalid value returned for sCallbackRecordCount"; VerifyHandleOptionCallback(0, __FUNCTION__, &sOptionSetA, '1', "-1", nullptr); VerifyHandleOptionCallback(1, __FUNCTION__, &sOptionSetA, 'Z', "-Z", "baz-value"); @@ -615,7 +609,7 @@ static void UnknownOptionTest_IgnoreUnknownShortOption() VerifyNonOptionArg(4, "non-opt-arg-2"); } -static void MissingValueTest_MissingShortOptionValue() +TEST_F(TestCHIPArgParser, MissingValueTest_MissingShortOptionValue) { bool res; @@ -635,14 +629,14 @@ static void MissingValueTest_MissingShortOptionValue() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs, true); - VerifyOrQuit(res == false, "ParseArgs() returned true"); - VerifyOrQuit(sCallbackRecordCount == 1, "Invalid value returned for sCallbackRecordCount"); + ASSERT_FALSE(res) << "ParseArgs() returned true"; + ASSERT_EQ(sCallbackRecordCount, 1u) << "Invalid value returned for sCallbackRecordCount"; VerifyPrintArgErrorCallback(0); VerifyArgErrorContains(0, "Missing"); VerifyArgErrorContains(0, "-Z"); } -static void MissingValueTest_MissingLongOptionValue() +TEST_F(TestCHIPArgParser, MissingValueTest_MissingLongOptionValue) { bool res; @@ -662,8 +656,8 @@ static void MissingValueTest_MissingLongOptionValue() TestArgv argsDup = DupeArgs(argv, argc); res = ParseArgs(__FUNCTION__, argc, argsDup.argv.Get(), optionSets, HandleNonOptionArgs, true); - VerifyOrQuit(res == false, "ParseArgs() returned true"); - VerifyOrQuit(sCallbackRecordCount == 1, "Invalid value returned for sCallbackRecordCount"); + ASSERT_FALSE(res) << "ParseArgs() returned true"; + ASSERT_EQ(sCallbackRecordCount, 1u) << "Invalid value returned for sCallbackRecordCount"; VerifyPrintArgErrorCallback(0); VerifyArgErrorContains(0, "Missing"); VerifyArgErrorContains(0, "--run"); @@ -692,7 +686,7 @@ static bool HandleOption(const char * progName, OptionSet * optSet, int id, cons printf("HandleOption called: progName:%s optSet:%08lX id:%d name:%s arg:%s\n", progName, (intptr_t) optSet, id, name, arg); #endif - VerifyOrQuit(sCallbackRecordCount < kMaxCallbackRecords, "Out of callback records"); + EXPECT_LT(sCallbackRecordCount, kMaxCallbackRecords) << "Out of callback records"; sCallbackRecords[sCallbackRecordCount].Type = CallbackRecord::kHandleOption; sCallbackRecords[sCallbackRecordCount].ProgName = chip::Platform::MemoryAllocString(progName, strlen(progName)); sCallbackRecords[sCallbackRecordCount].OptSet = optSet; @@ -717,7 +711,7 @@ static bool HandleNonOptionArgs(const char * progName, int argc, char * const ar // clang-format on #endif - VerifyOrQuit(sCallbackRecordCount < kMaxCallbackRecords, "Out of callback records"); + EXPECT_LT(sCallbackRecordCount, kMaxCallbackRecords) << "Out of callback records"; sCallbackRecords[sCallbackRecordCount].Type = CallbackRecord::kHandleNonOptionArgs; sCallbackRecords[sCallbackRecordCount].ProgName = chip::Platform::MemoryAllocString(progName, strlen(progName)); sCallbackRecords[sCallbackRecordCount].Argc = argc; @@ -725,7 +719,7 @@ static bool HandleNonOptionArgs(const char * progName, int argc, char * const ar for (int i = 0; i < argc; i++) { - VerifyOrQuit(sCallbackRecordCount < kMaxCallbackRecords, "Out of callback records"); + EXPECT_LT(sCallbackRecordCount, kMaxCallbackRecords) << "Out of callback records"; sCallbackRecords[sCallbackRecordCount].Type = CallbackRecord::kNonOptionArg; sCallbackRecords[sCallbackRecordCount].Arg = chip::Platform::MemoryAllocString(argv[i], strlen(argv[i])); sCallbackRecordCount++; @@ -740,7 +734,7 @@ static void ENFORCE_FORMAT(1, 2) HandleArgError(const char * msg, ...) int status; va_list ap; - VerifyOrQuit(sCallbackRecordCount < kMaxCallbackRecords, "Out of callback records"); + ASSERT_LT(sCallbackRecordCount, kMaxCallbackRecords) << "Out of callback records"; sCallbackRecords[sCallbackRecordCount].Type = CallbackRecord::kArgError; @@ -760,51 +754,3 @@ static void ENFORCE_FORMAT(1, 2) HandleArgError(const char * msg, ...) sCallbackRecordCount++; } - -int TestCHIPArgParser() -{ - if (chip::Platform::MemoryInit() != CHIP_NO_ERROR) - { - return EXIT_FAILURE; - } - - SimpleParseTest_SingleLongOption(); - SimpleParseTest_SingleShortOption(); - SimpleParseTest_SingleLongOptionWithValue(); - SimpleParseTest_SingleShortOptionWithValue(); - SimpleParseTest_VariousShortAndLongWithArgs(); - - UnknownOptionTest_UnknownShortOption(); - UnknownOptionTest_UnknownLongOption(); - UnknownOptionTest_UnknownShortOptionAfterArgs(); - UnknownOptionTest_UnknownShortOptionAfterKnown(); - UnknownOptionTest_UnknownShortOptionBeforeKnown(); - UnknownOptionTest_UnknownLongOptionAfterArgs(); - UnknownOptionTest_IgnoreUnknownShortOption(); - - /* Skip this test because the parser successfully captures all the options - but the error reporting is incorrect in this case due to long_opt limitations */ -#ifndef CHIP_CONFIG_NON_POSIX_LONG_OPT - UnknownOptionTest_IgnoreUnknownLongOption(); -#endif // !CHIP_CONFIG_NON_POSIX_LONG_OPT - - MissingValueTest_MissingShortOptionValue(); - MissingValueTest_MissingLongOptionValue(); - - ClearCallbackRecords(); - - printf("All tests succeeded\n"); - - chip::Platform::MemoryShutdown(); - - return (EXIT_SUCCESS); -} -#else // CHIP_CONFIG_ENABLE_ARG_PARSER -int TestCHIPArgParser(void) -{ - printf("No tests were run\n"); - return (EXIT_SUCCESS); -} -#endif // CHIP_CONFIG_ENABLE_ARG_PARSER - -CHIP_REGISTER_TEST_SUITE(TestCHIPArgParser); diff --git a/src/lib/support/tests/TestPool.cpp b/src/lib/support/tests/TestPool.cpp index 963a7b3c52f7ea..da76d7ebb70d7b 100644 --- a/src/lib/support/tests/TestPool.cpp +++ b/src/lib/support/tests/TestPool.cpp @@ -25,13 +25,11 @@ #include +#include + #include #include -#include #include - -#include - namespace chip { template @@ -51,60 +49,67 @@ namespace { using namespace chip; +class TestPool : public ::testing::Test +{ +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + template -void TestReleaseNull(nlTestSuite * inSuite, void * inContext) +void TestReleaseNull() { ObjectPool pool; pool.ReleaseObject(nullptr); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == 0); - NL_TEST_ASSERT(inSuite, pool.Allocated() == 0); + EXPECT_EQ(GetNumObjectsInUse(pool), 0u); + EXPECT_EQ(pool.Allocated(), 0u); } -void TestReleaseNullStatic(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPool, TestReleaseNullStatic) { - TestReleaseNull(inSuite, inContext); + TestReleaseNull(); } #if CHIP_SYSTEM_CONFIG_POOL_USE_HEAP -void TestReleaseNullDynamic(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPool, TestReleaseNullDynamic) { - TestReleaseNull(inSuite, inContext); + TestReleaseNull(); } #endif // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP template -void TestCreateReleaseObject(nlTestSuite * inSuite, void * inContext) +void TestCreateReleaseObject() { ObjectPool pool; uint32_t * obj[N]; - NL_TEST_ASSERT(inSuite, pool.Allocated() == 0); + EXPECT_EQ(pool.Allocated(), 0u); for (int t = 0; t < 2; ++t) { pool.ReleaseAll(); - NL_TEST_ASSERT(inSuite, pool.Allocated() == 0); + EXPECT_EQ(pool.Allocated(), 0u); for (size_t i = 0; i < N; ++i) { obj[i] = pool.CreateObject(); - NL_TEST_ASSERT(inSuite, obj[i] != nullptr); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == i + 1); - NL_TEST_ASSERT(inSuite, pool.Allocated() == i + 1); + ASSERT_NE(obj[i], nullptr); + EXPECT_EQ(GetNumObjectsInUse(pool), i + 1); + EXPECT_EQ(pool.Allocated(), i + 1); } } for (size_t i = 0; i < N; ++i) { pool.ReleaseObject(obj[i]); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == N - i - 1); - NL_TEST_ASSERT(inSuite, pool.Allocated() == N - i - 1); + EXPECT_EQ(GetNumObjectsInUse(pool), N - i - 1); + EXPECT_EQ(pool.Allocated(), N - i - 1); } } -void TestCreateReleaseObjectStatic(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPool, TestCreateReleaseObjectStatic) { constexpr const size_t kSize = 100; - TestCreateReleaseObject(inSuite, inContext); + TestCreateReleaseObject(); ObjectPool pool; uint32_t * obj[kSize]; @@ -112,44 +117,44 @@ void TestCreateReleaseObjectStatic(nlTestSuite * inSuite, void * inContext) for (size_t i = 0; i < kSize; ++i) { obj[i] = pool.CreateObject(); - NL_TEST_ASSERT(inSuite, obj[i] != nullptr); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == i + 1); - NL_TEST_ASSERT(inSuite, pool.Allocated() == i + 1); + ASSERT_NE(obj[i], nullptr); + EXPECT_EQ(GetNumObjectsInUse(pool), i + 1); + EXPECT_EQ(pool.Allocated(), i + 1); } uint32_t * fail = pool.CreateObject(); - NL_TEST_ASSERT(inSuite, fail == nullptr); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == kSize); - NL_TEST_ASSERT(inSuite, pool.Allocated() == kSize); - NL_TEST_ASSERT(inSuite, pool.Exhausted()); + EXPECT_EQ(fail, nullptr); + EXPECT_EQ(GetNumObjectsInUse(pool), kSize); + EXPECT_EQ(pool.Allocated(), kSize); + EXPECT_TRUE(pool.Exhausted()); pool.ReleaseObject(obj[55]); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == kSize - 1); - NL_TEST_ASSERT(inSuite, pool.Allocated() == kSize - 1); - NL_TEST_ASSERT(inSuite, !pool.Exhausted()); - NL_TEST_ASSERT(inSuite, obj[55] == pool.CreateObject()); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == kSize); - NL_TEST_ASSERT(inSuite, pool.Allocated() == kSize); - NL_TEST_ASSERT(inSuite, pool.Exhausted()); + EXPECT_EQ(GetNumObjectsInUse(pool), kSize - 1); + EXPECT_EQ(pool.Allocated(), kSize - 1); + EXPECT_FALSE(pool.Exhausted()); + EXPECT_EQ(obj[55], pool.CreateObject()); + EXPECT_EQ(GetNumObjectsInUse(pool), kSize); + EXPECT_EQ(pool.Allocated(), kSize); + EXPECT_TRUE(pool.Exhausted()); fail = pool.CreateObject(); - NL_TEST_ASSERT(inSuite, fail == nullptr); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == kSize); - NL_TEST_ASSERT(inSuite, pool.Allocated() == kSize); - NL_TEST_ASSERT(inSuite, pool.Exhausted()); + ASSERT_EQ(fail, nullptr); + EXPECT_EQ(GetNumObjectsInUse(pool), kSize); + EXPECT_EQ(pool.Allocated(), kSize); + EXPECT_TRUE(pool.Exhausted()); pool.ReleaseAll(); } #if CHIP_SYSTEM_CONFIG_POOL_USE_HEAP -void TestCreateReleaseObjectDynamic(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPool, TestCreateReleaseObjectDynamic) { - TestCreateReleaseObject(inSuite, inContext); + TestCreateReleaseObject(); } #endif // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP template -void TestCreateReleaseStruct(nlTestSuite * inSuite, void * inContext) +void TestCreateReleaseStruct() { struct S { @@ -166,17 +171,17 @@ void TestCreateReleaseStruct(nlTestSuite * inSuite, void * inContext) for (size_t i = 0; i < kSize; ++i) { objs2[i] = pool.CreateObject(objs1); - NL_TEST_ASSERT(inSuite, objs2[i] != nullptr); - NL_TEST_ASSERT(inSuite, pool.Allocated() == i + 1); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == i + 1); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == objs1.size()); + ASSERT_NE(objs2[i], nullptr); + EXPECT_EQ(pool.Allocated(), i + 1); + EXPECT_EQ(GetNumObjectsInUse(pool), i + 1); + EXPECT_EQ(GetNumObjectsInUse(pool), objs1.size()); } for (size_t i = 0; i < kSize; ++i) { pool.ReleaseObject(objs2[i]); - NL_TEST_ASSERT(inSuite, pool.Allocated() == kSize - i - 1); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == kSize - i - 1); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == objs1.size()); + EXPECT_EQ(pool.Allocated(), kSize - i - 1); + EXPECT_EQ(GetNumObjectsInUse(pool), kSize - i - 1); + EXPECT_EQ(GetNumObjectsInUse(pool), objs1.size()); } // Verify that ReleaseAll() calls the destructors. @@ -184,35 +189,35 @@ void TestCreateReleaseStruct(nlTestSuite * inSuite, void * inContext) { obj = pool.CreateObject(objs1); } - NL_TEST_ASSERT(inSuite, objs1.size() == kSize); - NL_TEST_ASSERT(inSuite, pool.Allocated() == kSize); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == kSize); + EXPECT_EQ(objs1.size(), kSize); + EXPECT_EQ(pool.Allocated(), kSize); + EXPECT_EQ(GetNumObjectsInUse(pool), kSize); printf("allocated = %u\n", static_cast(pool.Allocated())); printf("highwater = %u\n", static_cast(pool.HighWaterMark())); pool.ReleaseAll(); printf("allocated = %u\n", static_cast(pool.Allocated())); printf("highwater = %u\n", static_cast(pool.HighWaterMark())); - NL_TEST_ASSERT(inSuite, objs1.size() == 0); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(pool) == 0); - NL_TEST_ASSERT(inSuite, pool.Allocated() == 0); - NL_TEST_ASSERT(inSuite, pool.HighWaterMark() == kSize); + EXPECT_EQ(objs1.size(), 0u); + EXPECT_EQ(GetNumObjectsInUse(pool), 0u); + EXPECT_EQ(pool.Allocated(), 0u); + EXPECT_EQ(pool.HighWaterMark(), kSize); } -void TestCreateReleaseStructStatic(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPool, TestCreateReleaseStructStatic) { - TestCreateReleaseStruct(inSuite, inContext); + TestCreateReleaseStruct(); } #if CHIP_SYSTEM_CONFIG_POOL_USE_HEAP -void TestCreateReleaseStructDynamic(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPool, TestCreateReleaseStructDynamic) { - TestCreateReleaseStruct(inSuite, inContext); + TestCreateReleaseStruct(); } #endif // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP template -void TestForEachActiveObject(nlTestSuite * inSuite, void * inContext) +void TestForEachActiveObject() { struct S { @@ -229,37 +234,37 @@ void TestForEachActiveObject(nlTestSuite * inSuite, void * inContext) for (size_t i = 0; i < kSize; ++i) { objArray[i] = pool.CreateObject(i); - NL_TEST_ASSERT(inSuite, objArray[i] != nullptr); - NL_TEST_ASSERT(inSuite, objArray[i]->mId == i); + ASSERT_NE(objArray[i], nullptr); + EXPECT_EQ(objArray[i]->mId, i); objIds.insert(i); } // Default constructor of an iterator should be pointing to the pool end. { typename ObjectPoolIterator::Type defaultIterator; - NL_TEST_ASSERT(inSuite, defaultIterator == pool.end()); + EXPECT_EQ(defaultIterator, pool.end()); } // Verify that iteration visits all objects. size_t count = 0; { size_t sum = 0; - pool.ForEachActiveObject([&](S * object) { - NL_TEST_ASSERT(inSuite, object != nullptr); + pool.ForEachActiveObject([&](S * object) -> Loop { + EXPECT_NE(object, nullptr); if (object == nullptr) { - // NL_TEST_ASSERT doesn't stop running the test and we want to avoid nullptr dereference. + // Using EXPECT_NE instead of ASSERT_NE due to compilation errors when using ASSERT_NE return Loop::Continue; } - NL_TEST_ASSERT(inSuite, objIds.count(object->mId) == 1); + EXPECT_EQ(objIds.count(object->mId), 1u); objIds.erase(object->mId); ++count; sum += object->mId; return Loop::Continue; }); - NL_TEST_ASSERT(inSuite, count == kSize); - NL_TEST_ASSERT(inSuite, sum == kSize * (kSize - 1) / 2); - NL_TEST_ASSERT(inSuite, objIds.size() == 0); + EXPECT_EQ(count, kSize); + EXPECT_EQ(sum, kSize * (kSize - 1) / 2); + EXPECT_EQ(objIds.size(), 0u); } // Test begin/end iteration @@ -273,14 +278,14 @@ void TestForEachActiveObject(nlTestSuite * inSuite, void * inContext) size_t sum = 0; for (auto v = pool.begin(); v != pool.end(); ++v) { - NL_TEST_ASSERT(inSuite, objIds.count((*v)->mId) == 1); + EXPECT_EQ(objIds.count((*v)->mId), 1u); objIds.erase((*v)->mId); ++count; sum += (*v)->mId; } - NL_TEST_ASSERT(inSuite, count == kSize); - NL_TEST_ASSERT(inSuite, sum == kSize * (kSize - 1) / 2); - NL_TEST_ASSERT(inSuite, objIds.size() == 0); + EXPECT_EQ(count, kSize); + EXPECT_EQ(sum, kSize * (kSize - 1) / 2); + EXPECT_EQ(objIds.size(), 0u); } // Verify that returning Loop::Break stops iterating. @@ -289,8 +294,8 @@ void TestForEachActiveObject(nlTestSuite * inSuite, void * inContext) objIds.insert(object->mId); return ++count != kSize / 2 ? Loop::Continue : Loop::Break; }); - NL_TEST_ASSERT(inSuite, count == kSize / 2); - NL_TEST_ASSERT(inSuite, objIds.size() == kSize / 2); + EXPECT_EQ(count, kSize / 2); + EXPECT_EQ(objIds.size(), kSize / 2); // Verify that iteration can be nested. count = 0; @@ -311,8 +316,8 @@ void TestForEachActiveObject(nlTestSuite * inSuite, void * inContext) } return Loop::Continue; }); - NL_TEST_ASSERT(inSuite, count == (kSize - 1) * kSize / 2); - NL_TEST_ASSERT(inSuite, objIds.size() == 0); + EXPECT_EQ(count, (kSize - 1) * kSize / 2); + EXPECT_EQ(objIds.size(), 0u); // Verify that iteration can be nested for iterator types { @@ -346,8 +351,8 @@ void TestForEachActiveObject(nlTestSuite * inSuite, void * inContext) } } } - NL_TEST_ASSERT(inSuite, count == (kSize - 1) * kSize / 2); - NL_TEST_ASSERT(inSuite, objIds.size() == 0); + EXPECT_EQ(count, (kSize - 1) * kSize / 2); + EXPECT_EQ(objIds.size(), 0u); } count = 0; @@ -364,18 +369,18 @@ void TestForEachActiveObject(nlTestSuite * inSuite, void * inContext) } return Loop::Continue; }); - NL_TEST_ASSERT(inSuite, count == kSize); - NL_TEST_ASSERT(inSuite, objIds.size() == kSize / 2); + EXPECT_EQ(count, kSize); + EXPECT_EQ(objIds.size(), kSize / 2); for (size_t i = 0; i < kSize; ++i) { if ((i % 2) == 0) { - NL_TEST_ASSERT(inSuite, objArray[i] == nullptr); + EXPECT_EQ(objArray[i], nullptr); } else { - NL_TEST_ASSERT(inSuite, objArray[i] != nullptr); - NL_TEST_ASSERT(inSuite, objArray[i]->mId == i); + ASSERT_NE(objArray[i], nullptr); + EXPECT_EQ(objArray[i]->mId, i); } } @@ -385,19 +390,19 @@ void TestForEachActiveObject(nlTestSuite * inSuite, void * inContext) if ((object->mId % 2) == 1) { size_t id = object->mId - 1; - NL_TEST_ASSERT(inSuite, objArray[id] == nullptr); + EXPECT_EQ(objArray[id], nullptr); objArray[id] = pool.CreateObject(id); - NL_TEST_ASSERT(inSuite, objArray[id] != nullptr); + EXPECT_NE(objArray[id], nullptr); } return Loop::Continue; }); for (size_t i = 0; i < kSize; ++i) { - NL_TEST_ASSERT(inSuite, objArray[i] != nullptr); - NL_TEST_ASSERT(inSuite, objArray[i]->mId == i); + ASSERT_NE(objArray[i], nullptr); + EXPECT_EQ(objArray[i]->mId, i); } - NL_TEST_ASSERT(inSuite, count >= kSize / 2); - NL_TEST_ASSERT(inSuite, count <= kSize); + EXPECT_GE(count, kSize / 2); + EXPECT_LE(count, kSize); // Test begin/end iteration { @@ -417,25 +422,25 @@ void TestForEachActiveObject(nlTestSuite * inSuite, void * inContext) objIds.insert(object->mId); } } - NL_TEST_ASSERT(inSuite, count == kSize); - NL_TEST_ASSERT(inSuite, objIds.size() == kSize / 2); + EXPECT_EQ(count, kSize); + EXPECT_EQ(objIds.size(), kSize / 2); // validate we iterate only over active objects for (auto object : pool) { - NL_TEST_ASSERT(inSuite, (object->mId % 2) == 1); + EXPECT_EQ((object->mId % 2), 1u); } for (size_t i = 0; i < kSize; ++i) { if ((i % 2) == 0) { - NL_TEST_ASSERT(inSuite, objArray[i] == nullptr); + EXPECT_EQ(objArray[i], nullptr); } else { - NL_TEST_ASSERT(inSuite, objArray[i] != nullptr); - NL_TEST_ASSERT(inSuite, objArray[i]->mId == i); + ASSERT_NE(objArray[i], nullptr); + EXPECT_EQ(objArray[i]->mId, i); } } @@ -448,36 +453,36 @@ void TestForEachActiveObject(nlTestSuite * inSuite, void * inContext) continue; } size_t id = object->mId - 1; - NL_TEST_ASSERT(inSuite, objArray[id] == nullptr); + EXPECT_EQ(objArray[id], nullptr); objArray[id] = pool.CreateObject(id); - NL_TEST_ASSERT(inSuite, objArray[id] != nullptr); + EXPECT_NE(objArray[id], nullptr); } for (size_t i = 0; i < kSize; ++i) { - NL_TEST_ASSERT(inSuite, objArray[i] != nullptr); - NL_TEST_ASSERT(inSuite, objArray[i]->mId == i); + ASSERT_NE(objArray[i], nullptr); + EXPECT_EQ(objArray[i]->mId, i); } - NL_TEST_ASSERT(inSuite, count >= kSize / 2); - NL_TEST_ASSERT(inSuite, count <= kSize); + EXPECT_GE(count, kSize / 2); + EXPECT_LE(count, kSize); } pool.ReleaseAll(); } -void TestForEachActiveObjectStatic(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPool, TestForEachActiveObjectStatic) { - TestForEachActiveObject(inSuite, inContext); + TestForEachActiveObject(); } #if CHIP_SYSTEM_CONFIG_POOL_USE_HEAP -void TestForEachActiveObjectDynamic(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPool, TestForEachActiveObjectDynamic) { - TestForEachActiveObject(inSuite, inContext); + TestForEachActiveObject(); } #endif // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP template -void TestPoolInterface(nlTestSuite * inSuite, void * inContext) +void TestPoolInterface() { struct TestObject { @@ -503,84 +508,40 @@ void TestPoolInterface(nlTestSuite * inSuite, void * inContext) for (size_t i = 0; i < kSize; ++i) { objs2[i] = poolHolder.mTestObjectPoolInterface.CreateObject(&bits, i); - NL_TEST_ASSERT(inSuite, objs2[i] != nullptr); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(poolHolder.mTestObjectPoolInterface) == i + 1); - NL_TEST_ASSERT(inSuite, bits == (1ul << (i + 1)) - 1); + ASSERT_NE(objs2[i], nullptr); + EXPECT_EQ(GetNumObjectsInUse(poolHolder.mTestObjectPoolInterface), i + 1); + EXPECT_EQ(bits, (1ul << (i + 1)) - 1); } for (size_t i = 0; i < kSize; ++i) { poolHolder.mTestObjectPoolInterface.ReleaseObject(objs2[i]); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(poolHolder.mTestObjectPoolInterface) == kSize - i - 1); + EXPECT_EQ(GetNumObjectsInUse(poolHolder.mTestObjectPoolInterface), kSize - i - 1); } - NL_TEST_ASSERT(inSuite, bits == 0); + EXPECT_EQ(bits, 0u); // Verify that ReleaseAll() calls the destructors. for (size_t i = 0; i < kSize; ++i) { objs2[i] = poolHolder.mTestObjectPoolInterface.CreateObject(&bits, i); } - NL_TEST_ASSERT(inSuite, bits == (1ul << kSize) - 1); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(poolHolder.mTestObjectPoolInterface) == kSize); + EXPECT_EQ(bits, (1ul << kSize) - 1); + EXPECT_EQ(GetNumObjectsInUse(poolHolder.mTestObjectPoolInterface), kSize); poolHolder.mTestObjectPoolInterface.ReleaseAll(); - NL_TEST_ASSERT(inSuite, bits == 0); - NL_TEST_ASSERT(inSuite, GetNumObjectsInUse(poolHolder.mTestObjectPoolInterface) == 0); + EXPECT_EQ(bits, 0u); + EXPECT_EQ(GetNumObjectsInUse(poolHolder.mTestObjectPoolInterface), 0u); } -void TestPoolInterfaceStatic(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPool, TestPoolInterfaceStatic) { - TestPoolInterface(inSuite, inContext); + TestPoolInterface(); } #if CHIP_SYSTEM_CONFIG_POOL_USE_HEAP -void TestPoolInterfaceDynamic(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPool, TestPoolInterfaceDynamic) { - TestPoolInterface(inSuite, inContext); + TestPoolInterface(); } #endif // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP -int Setup(void * inContext) -{ - return ::chip::Platform::MemoryInit() == CHIP_NO_ERROR ? SUCCESS : FAILURE; -} - -int Teardown(void * inContext) -{ - ::chip::Platform::MemoryShutdown(); - return SUCCESS; -} - } // namespace - -#define NL_TEST_DEF_FN(fn) NL_TEST_DEF("Test " #fn, fn) -/** - * Test Suite. It lists all the test functions. - */ -static const nlTest sTests[] = { - // clang-format off - NL_TEST_DEF_FN(TestReleaseNullStatic), - NL_TEST_DEF_FN(TestCreateReleaseObjectStatic), - NL_TEST_DEF_FN(TestCreateReleaseStructStatic), - NL_TEST_DEF_FN(TestForEachActiveObjectStatic), - NL_TEST_DEF_FN(TestPoolInterfaceStatic), -#if CHIP_SYSTEM_CONFIG_POOL_USE_HEAP - NL_TEST_DEF_FN(TestReleaseNullDynamic), - NL_TEST_DEF_FN(TestCreateReleaseObjectDynamic), - NL_TEST_DEF_FN(TestCreateReleaseStructDynamic), - NL_TEST_DEF_FN(TestForEachActiveObjectDynamic), - NL_TEST_DEF_FN(TestPoolInterfaceDynamic), -#endif // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP - NL_TEST_SENTINEL() - // clang-format on -}; - -int TestPool() -{ - nlTestSuite theSuite = { "CHIP Pool tests", &sTests[0], Setup, Teardown }; - - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestPool); diff --git a/src/lib/support/tests/TestStateMachine.cpp b/src/lib/support/tests/TestStateMachine.cpp index cef020e019ff74..4b6af3a73d85cf 100644 --- a/src/lib/support/tests/TestStateMachine.cpp +++ b/src/lib/support/tests/TestStateMachine.cpp @@ -16,10 +16,10 @@ * limitations under the License. */ +#include + #include -#include #include -#include namespace { @@ -166,67 +166,67 @@ class SimpleStateMachine ~SimpleStateMachine() {} }; -void TestInit(nlTestSuite * inSuite, void * inContext) +TEST(TestStateMachine, TestInit) { // state machine initializes to State1 SimpleStateMachine fsm; - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); } -void TestIgnoredEvents(nlTestSuite * inSuite, void * inContext) +TEST(TestStateMachine, TestIgnoredEvents) { // in State1 - ignore Event1 and Event3 SimpleStateMachine fsm; fsm.mStateMachine.Dispatch(Event::Create()); - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); fsm.mStateMachine.Dispatch(Event::Create()); - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); // transition to State2 fsm.mStateMachine.Dispatch(Event::Create()); - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); // in State2 - ignore Event2 and Event3 fsm.mStateMachine.Dispatch(Event::Create()); - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); fsm.mStateMachine.Dispatch(Event::Create()); - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); } -void TestTransitions(nlTestSuite * inSuite, void * inContext) +TEST(TestStateMachine, TestTransitions) { // in State1 SimpleStateMachine fsm; // dispatch Event2 to transition to State2 fsm.mStateMachine.Dispatch(Event::Create()); - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); // dispatch Event1 to transition back to State1 fsm.mStateMachine.Dispatch(Event::Create()); - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); // dispatch Event2 to transition to State2 fsm.mStateMachine.Dispatch(Event::Create()); - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); // dispatch Event4 to transitions to State1. fsm.mStateMachine.Dispatch(Event::Create()); - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); } -void TestTransitionsDispatch(nlTestSuite * inSuite, void * inContext) +TEST(TestStateMachine, TestTransitionsDispatch) { // in State1 SimpleStateMachine fsm; // Dispatch Event4, which in turn dispatches Event2 from the transitions // table and ultimately places us in State2. fsm.mStateMachine.Dispatch(Event::Create()); - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); } -void TestNestedDispatch(nlTestSuite * inSuite, void * inContext) +TEST(TestStateMachine, TestNestedDispatch) { // in State1 SimpleStateMachine fsm; // Dispatch Event5, which places us into State3, which will dispatch // Event5 again from its Enter method to place us into State2. fsm.mStateMachine.Dispatch(Event::Create()); - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); // Make sure that Enter methods execute the correct number of times. // This helps verify that pattern matching is working correctly. // Specifically, we need to verify this case: State3 creates State2 @@ -238,74 +238,45 @@ void TestNestedDispatch(nlTestSuite * inSuite, void * inContext) // been constructed when the State3 Enter method executes a second // time. The state machine pattern matching has code to explicitly // prevent this double-execution. This is testing that. - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms1.mEntered == 0); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms1.mExited == 1); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms1.mLogged == 0); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms2.mEntered == 1); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms2.mExited == 0); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms2.mLogged == 1); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms3.mEntered == 1); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms3.mExited == 1); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms3.mLogged == 1); + EXPECT_EQ(fsm.mTransitions.mFactory.ms1.mEntered, 0u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms1.mExited, 1u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms1.mLogged, 0u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms2.mEntered, 1u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms2.mExited, 0u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms2.mLogged, 1u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms3.mEntered, 1u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms3.mExited, 1u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms3.mLogged, 1u); } -void TestMethodExec(nlTestSuite * inSuite, void * inContext) +TEST(TestStateMachine, TestMethodExec) { // in State1 SimpleStateMachine fsm; // transition to State2 fsm.mStateMachine.Dispatch(Event::Create()); - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); // verify expected method calls - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms1.mEntered == 0); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms1.mExited == 1); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms1.mLogged == 0); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms1.mPrevious == nullptr); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms2.mEntered == 1); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms2.mExited == 0); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms2.mLogged == 1); - NL_TEST_ASSERT(inSuite, strcmp(fsm.mTransitions.mFactory.ms2.mPrevious, "State1") == 0); + EXPECT_EQ(fsm.mTransitions.mFactory.ms1.mEntered, 0u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms1.mExited, 1u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms1.mLogged, 0u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms1.mPrevious, nullptr); + EXPECT_EQ(fsm.mTransitions.mFactory.ms2.mEntered, 1u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms2.mExited, 0u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms2.mLogged, 1u); + EXPECT_STREQ(fsm.mTransitions.mFactory.ms2.mPrevious, "State1"); // transition back to State1 fsm.mStateMachine.Dispatch(Event::Create()); - NL_TEST_ASSERT(inSuite, fsm.mStateMachine.GetState().Is()); + EXPECT_TRUE(fsm.mStateMachine.GetState().Is()); // verify expected method calls - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms1.mEntered == 1); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms1.mExited == 1); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms1.mLogged == 1); - NL_TEST_ASSERT(inSuite, strcmp(fsm.mTransitions.mFactory.ms1.mPrevious, "State2") == 0); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms2.mEntered == 1); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms2.mExited == 1); - NL_TEST_ASSERT(inSuite, fsm.mTransitions.mFactory.ms2.mLogged == 1); - NL_TEST_ASSERT(inSuite, strcmp(fsm.mTransitions.mFactory.ms2.mPrevious, "State1") == 0); -} - -int Setup(void * inContext) -{ - return SUCCESS; -} - -int Teardown(void * inContext) -{ - return SUCCESS; + EXPECT_EQ(fsm.mTransitions.mFactory.ms1.mEntered, 1u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms1.mExited, 1u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms1.mLogged, 1u); + EXPECT_STREQ(fsm.mTransitions.mFactory.ms1.mPrevious, "State2"); + EXPECT_EQ(fsm.mTransitions.mFactory.ms2.mEntered, 1u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms2.mExited, 1u); + EXPECT_EQ(fsm.mTransitions.mFactory.ms2.mLogged, 1u); + EXPECT_STREQ(fsm.mTransitions.mFactory.ms2.mPrevious, "State1"); } } // namespace - -static const nlTest sTests[] = { - NL_TEST_DEF("TestInit", TestInit), - NL_TEST_DEF("TestIgnoredEvents", TestIgnoredEvents), - NL_TEST_DEF("TestTransitions", TestTransitions), - NL_TEST_DEF("TestTransitionsDispatch", TestTransitionsDispatch), - NL_TEST_DEF("TestNestedDispatch", TestNestedDispatch), - NL_TEST_DEF("TestMethodExec", TestMethodExec), - NL_TEST_SENTINEL(), -}; - -int StateMachineTestSuite() -{ - nlTestSuite suite = { "CHIP State Machine tests", &sTests[0], Setup, Teardown }; - nlTestRunner(&suite, nullptr); - return nlTestRunnerStats(&suite); -} - -CHIP_REGISTER_TEST_SUITE(StateMachineTestSuite); diff --git a/src/lib/support/tests/TestThreadOperationalDataset.cpp b/src/lib/support/tests/TestThreadOperationalDataset.cpp index 27e18eac87e23e..d9e13c8c25705f 100644 --- a/src/lib/support/tests/TestThreadOperationalDataset.cpp +++ b/src/lib/support/tests/TestThreadOperationalDataset.cpp @@ -14,286 +14,252 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include -#include -#include +#include + +#include +#include namespace { using namespace chip; -void TestInit(nlTestSuite * inSuite, void * inContext) +class TestThreadOperationalDataset : public ::testing::Test +{ +public: + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } + + static Thread::OperationalDataset dataset; +}; + +Thread::OperationalDataset TestThreadOperationalDataset::dataset; + +TEST_F(TestThreadOperationalDataset, TestInit) { - Thread::OperationalDataset & dataset = *static_cast(inContext); uint8_t longerThanOperationalDatasetSize[255]{}; - NL_TEST_ASSERT(inSuite, dataset.Init(ByteSpan(longerThanOperationalDatasetSize)) == CHIP_ERROR_INVALID_ARGUMENT); - NL_TEST_ASSERT(inSuite, dataset.Init(ByteSpan()) == CHIP_NO_ERROR); + EXPECT_EQ(dataset.Init(ByteSpan(longerThanOperationalDatasetSize)), CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(dataset.Init(ByteSpan()), CHIP_NO_ERROR); { uint8_t data[] = { 0x01, 0x02, 0x03 }; - NL_TEST_ASSERT(inSuite, dataset.Init(ByteSpan(data)) == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(dataset.Init(ByteSpan(data)), CHIP_ERROR_INVALID_ARGUMENT); } { uint8_t data[] = { 0x01 }; - NL_TEST_ASSERT(inSuite, dataset.Init(ByteSpan(data)) == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(dataset.Init(ByteSpan(data)), CHIP_ERROR_INVALID_ARGUMENT); } } -void TestActiveTimestamp(nlTestSuite * inSuite, void * inContext) +TEST_F(TestThreadOperationalDataset, TestActiveTimestamp) { static constexpr uint64_t kActiveTimestampValue = 1; - Thread::OperationalDataset & dataset = *static_cast(inContext); - uint64_t activeTimestamp = 0; - NL_TEST_ASSERT(inSuite, dataset.SetActiveTimestamp(kActiveTimestampValue) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, dataset.GetActiveTimestamp(activeTimestamp) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, activeTimestamp == kActiveTimestampValue); + EXPECT_EQ(dataset.SetActiveTimestamp(kActiveTimestampValue), CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetActiveTimestamp(activeTimestamp), CHIP_NO_ERROR); + EXPECT_EQ(activeTimestamp, kActiveTimestampValue); } -void TestChannel(nlTestSuite * inSuite, void * inContext) +TEST_F(TestThreadOperationalDataset, TestChannel) { static constexpr uint16_t kChannelValue = 15; - Thread::OperationalDataset & dataset = *static_cast(inContext); - uint16_t channel = 0; - NL_TEST_ASSERT(inSuite, dataset.SetChannel(kChannelValue) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, dataset.GetChannel(channel) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, channel == kChannelValue); + EXPECT_EQ(dataset.SetChannel(kChannelValue), CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetChannel(channel), CHIP_NO_ERROR); + EXPECT_EQ(channel, kChannelValue); } -void TestExtendedPanId(nlTestSuite * inSuite, void * inContext) +TEST_F(TestThreadOperationalDataset, TestExtendedPanId) { static constexpr uint8_t kExtendedPanId[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77 }; - Thread::OperationalDataset & dataset = *static_cast(inContext); - uint8_t extendedPanId[Thread::kSizeExtendedPanId] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.SetExtendedPanId(kExtendedPanId) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, dataset.GetExtendedPanId(extendedPanId) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(extendedPanId, kExtendedPanId, sizeof(kExtendedPanId)) == 0); + EXPECT_EQ(dataset.SetExtendedPanId(kExtendedPanId), CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetExtendedPanId(extendedPanId), CHIP_NO_ERROR); + EXPECT_EQ(memcmp(extendedPanId, kExtendedPanId, sizeof(kExtendedPanId)), 0); ByteSpan span; - NL_TEST_ASSERT(inSuite, dataset.GetExtendedPanIdAsByteSpan(span) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, span.size() == sizeof(kExtendedPanId)); - NL_TEST_ASSERT(inSuite, memcmp(extendedPanId, span.data(), sizeof(kExtendedPanId)) == 0); + EXPECT_EQ(dataset.GetExtendedPanIdAsByteSpan(span), CHIP_NO_ERROR); + EXPECT_EQ(span.size(), sizeof(kExtendedPanId)); + EXPECT_EQ(memcmp(extendedPanId, span.data(), sizeof(kExtendedPanId)), 0); } -void TestMasterKey(nlTestSuite * inSuite, void * inContext) +TEST_F(TestThreadOperationalDataset, TestMasterKey) { static constexpr uint8_t kMasterKey[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; - Thread::OperationalDataset & dataset = *static_cast(inContext); - uint8_t masterKey[Thread::kSizeMasterKey] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.SetMasterKey(kMasterKey) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, dataset.GetMasterKey(masterKey) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(masterKey, kMasterKey, sizeof(kMasterKey)) == 0); + EXPECT_EQ(dataset.SetMasterKey(kMasterKey), CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetMasterKey(masterKey), CHIP_NO_ERROR); + EXPECT_EQ(memcmp(masterKey, kMasterKey, sizeof(kMasterKey)), 0); } -void TestMeshLocalPrefix(nlTestSuite * inSuite, void * inContext) +TEST_F(TestThreadOperationalDataset, TestMeshLocalPrefix) { static constexpr uint8_t kMeshLocalPrefix[] = { 0xfd, 0xde, 0xad, 0x00, 0xbe, 0xef, 0x00, 0x00 }; - Thread::OperationalDataset & dataset = *static_cast(inContext); - uint8_t meshLocalPrefix[Thread::kSizeMeshLocalPrefix] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.SetMeshLocalPrefix(kMeshLocalPrefix) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, dataset.GetMeshLocalPrefix(meshLocalPrefix) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(meshLocalPrefix, kMeshLocalPrefix, sizeof(kMeshLocalPrefix)) == 0); + EXPECT_EQ(dataset.SetMeshLocalPrefix(kMeshLocalPrefix), CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetMeshLocalPrefix(meshLocalPrefix), CHIP_NO_ERROR); + EXPECT_EQ(memcmp(meshLocalPrefix, kMeshLocalPrefix, sizeof(kMeshLocalPrefix)), 0); } -void TestNetworkName(nlTestSuite * inSuite, void * inContext) +TEST_F(TestThreadOperationalDataset, TestNetworkName) { static constexpr char kNetworkName[] = "ThreadNetwork"; - Thread::OperationalDataset & dataset = *static_cast(inContext); - char networkName[Thread::kSizeNetworkName + 1] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.SetNetworkName(kNetworkName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, dataset.GetNetworkName(networkName) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, strcmp(networkName, kNetworkName) == 0); + EXPECT_EQ(dataset.SetNetworkName(kNetworkName), CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetNetworkName(networkName), CHIP_NO_ERROR); + EXPECT_STREQ(networkName, kNetworkName); - NL_TEST_ASSERT(inSuite, dataset.SetNetworkName("0123456789abcdef") == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, dataset.SetNetworkName("0123456789abcdefg") == CHIP_ERROR_INVALID_STRING_LENGTH); - NL_TEST_ASSERT(inSuite, dataset.SetNetworkName("") == CHIP_ERROR_INVALID_STRING_LENGTH); + EXPECT_EQ(dataset.SetNetworkName("0123456789abcdef"), CHIP_NO_ERROR); + EXPECT_EQ(dataset.SetNetworkName("0123456789abcdefg"), CHIP_ERROR_INVALID_STRING_LENGTH); + EXPECT_EQ(dataset.SetNetworkName(""), CHIP_ERROR_INVALID_STRING_LENGTH); } -void TestPanId(nlTestSuite * inSuite, void * inContext) +TEST_F(TestThreadOperationalDataset, TestPanId) { static constexpr uint16_t kPanIdValue = 0x1234; - Thread::OperationalDataset & dataset = *static_cast(inContext); - uint16_t panid = 0; - NL_TEST_ASSERT(inSuite, dataset.SetPanId(kPanIdValue) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, dataset.GetPanId(panid) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, panid == kPanIdValue); + EXPECT_EQ(dataset.SetPanId(kPanIdValue), CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetPanId(panid), CHIP_NO_ERROR); + EXPECT_EQ(panid, kPanIdValue); } -void TestPSKc(nlTestSuite * inSuite, void * inContext) +TEST_F(TestThreadOperationalDataset, TestPSKc) { static constexpr uint8_t kPSKc[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; - Thread::OperationalDataset & dataset = *static_cast(inContext); - uint8_t pskc[Thread::kSizePSKc] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.SetPSKc(kPSKc) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, dataset.GetPSKc(pskc) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(pskc, kPSKc, sizeof(kPSKc)) == 0); + EXPECT_EQ(dataset.SetPSKc(kPSKc), CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetPSKc(pskc), CHIP_NO_ERROR); + EXPECT_FALSE(memcmp(pskc, kPSKc, sizeof(kPSKc))); } -void TestUnsetMasterKey(nlTestSuite * inSuite, void * inContext) +TEST_F(TestThreadOperationalDataset, TestUnsetMasterKey) { - Thread::OperationalDataset & dataset = *static_cast(inContext); uint8_t masterKey[Thread::kSizeMasterKey] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.GetMasterKey(masterKey) == CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetMasterKey(masterKey), CHIP_NO_ERROR); dataset.UnsetMasterKey(); - NL_TEST_ASSERT(inSuite, dataset.GetMasterKey(masterKey) == CHIP_ERROR_TLV_TAG_NOT_FOUND); - NL_TEST_ASSERT(inSuite, dataset.SetMasterKey(masterKey) == CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetMasterKey(masterKey), CHIP_ERROR_TLV_TAG_NOT_FOUND); + EXPECT_EQ(dataset.SetMasterKey(masterKey), CHIP_NO_ERROR); } -void TestUnsetPSKc(nlTestSuite * inSuite, void * inContext) +TEST_F(TestThreadOperationalDataset, TestUnsetPSKc) { - Thread::OperationalDataset & dataset = *static_cast(inContext); uint8_t pskc[Thread::kSizePSKc] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.GetPSKc(pskc) == CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetPSKc(pskc), CHIP_NO_ERROR); dataset.UnsetPSKc(); - NL_TEST_ASSERT(inSuite, dataset.GetPSKc(pskc) == CHIP_ERROR_TLV_TAG_NOT_FOUND); - NL_TEST_ASSERT(inSuite, dataset.SetPSKc(pskc) == CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetPSKc(pskc), CHIP_ERROR_TLV_TAG_NOT_FOUND); + EXPECT_EQ(dataset.SetPSKc(pskc), CHIP_NO_ERROR); } -void TestClear(nlTestSuite * inSuite, void * inContext) +TEST_F(TestThreadOperationalDataset, TestClear) { - Thread::OperationalDataset & dataset = *static_cast(inContext); { uint64_t activeTimestamp; - NL_TEST_ASSERT(inSuite, dataset.GetActiveTimestamp(activeTimestamp) == CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetActiveTimestamp(activeTimestamp), CHIP_NO_ERROR); } { uint16_t channel; - NL_TEST_ASSERT(inSuite, dataset.GetChannel(channel) == CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetChannel(channel), CHIP_NO_ERROR); } { uint8_t extendedPanId[Thread::kSizeExtendedPanId] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.GetExtendedPanId(extendedPanId) == CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetExtendedPanId(extendedPanId), CHIP_NO_ERROR); } { uint8_t masterKey[Thread::kSizeMasterKey] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.GetMasterKey(masterKey) == CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetMasterKey(masterKey), CHIP_NO_ERROR); } { uint8_t meshLocalPrefix[Thread::kSizeMeshLocalPrefix] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.GetMeshLocalPrefix(meshLocalPrefix) == CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetMeshLocalPrefix(meshLocalPrefix), CHIP_NO_ERROR); } { char networkName[Thread::kSizeNetworkName + 1] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.GetNetworkName(networkName) == CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetNetworkName(networkName), CHIP_NO_ERROR); } { uint16_t panid; - NL_TEST_ASSERT(inSuite, dataset.GetPanId(panid) == CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetPanId(panid), CHIP_NO_ERROR); } { uint8_t pskc[Thread::kSizePSKc] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.GetPSKc(pskc) == CHIP_NO_ERROR); + EXPECT_EQ(dataset.GetPSKc(pskc), CHIP_NO_ERROR); } dataset.Clear(); { uint64_t activeTimestamp; - NL_TEST_ASSERT(inSuite, dataset.GetActiveTimestamp(activeTimestamp) == CHIP_ERROR_TLV_TAG_NOT_FOUND); + EXPECT_EQ(dataset.GetActiveTimestamp(activeTimestamp), CHIP_ERROR_TLV_TAG_NOT_FOUND); } { uint16_t channel; - NL_TEST_ASSERT(inSuite, dataset.GetChannel(channel) == CHIP_ERROR_TLV_TAG_NOT_FOUND); + EXPECT_EQ(dataset.GetChannel(channel), CHIP_ERROR_TLV_TAG_NOT_FOUND); } { uint8_t extendedPanId[Thread::kSizeExtendedPanId] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.GetExtendedPanId(extendedPanId) == CHIP_ERROR_TLV_TAG_NOT_FOUND); + EXPECT_EQ(dataset.GetExtendedPanId(extendedPanId), CHIP_ERROR_TLV_TAG_NOT_FOUND); } { uint8_t masterKey[Thread::kSizeMasterKey] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.GetMasterKey(masterKey) == CHIP_ERROR_TLV_TAG_NOT_FOUND); + EXPECT_EQ(dataset.GetMasterKey(masterKey), CHIP_ERROR_TLV_TAG_NOT_FOUND); } { uint8_t meshLocalPrefix[Thread::kSizeMeshLocalPrefix] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.GetMeshLocalPrefix(meshLocalPrefix) == CHIP_ERROR_TLV_TAG_NOT_FOUND); + EXPECT_EQ(dataset.GetMeshLocalPrefix(meshLocalPrefix), CHIP_ERROR_TLV_TAG_NOT_FOUND); } { char networkName[Thread::kSizeNetworkName + 1] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.GetNetworkName(networkName) == CHIP_ERROR_TLV_TAG_NOT_FOUND); + EXPECT_EQ(dataset.GetNetworkName(networkName), CHIP_ERROR_TLV_TAG_NOT_FOUND); } { uint16_t panid; - NL_TEST_ASSERT(inSuite, dataset.GetPanId(panid) == CHIP_ERROR_TLV_TAG_NOT_FOUND); + EXPECT_EQ(dataset.GetPanId(panid), CHIP_ERROR_TLV_TAG_NOT_FOUND); } { uint8_t pskc[Thread::kSizePSKc] = { 0 }; - NL_TEST_ASSERT(inSuite, dataset.GetPSKc(pskc) == CHIP_ERROR_TLV_TAG_NOT_FOUND); + EXPECT_EQ(dataset.GetPSKc(pskc), CHIP_ERROR_TLV_TAG_NOT_FOUND); } } -const nlTest sTests[] = { - NL_TEST_DEF("TestInit", TestInit), // - NL_TEST_DEF("TestActiveTimestamp", TestActiveTimestamp), // - NL_TEST_DEF("TestChannel", TestChannel), // - NL_TEST_DEF("TestExtendedPanId", TestExtendedPanId), // - NL_TEST_DEF("TestMasterKey", TestMasterKey), // - NL_TEST_DEF("TestMeshLocalPrefix", TestMeshLocalPrefix), // - NL_TEST_DEF("TestNetworkName", TestNetworkName), // - NL_TEST_DEF("TestPanId", TestPanId), // - NL_TEST_DEF("TestPSKc", TestPSKc), // - NL_TEST_DEF("TestUnsetMasterKey", TestUnsetMasterKey), // - NL_TEST_DEF("TestUnsetPSKc", TestUnsetPSKc), // - NL_TEST_DEF("TestClear", TestClear), // - NL_TEST_SENTINEL() // -}; - } // namespace - -int TestThreadOperationalDatasetBuilder() -{ - nlTestSuite theSuite = { "ThreadOperationalDataset", sTests, nullptr, nullptr }; - - return ExecuteTestsWithContext(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestThreadOperationalDatasetBuilder) 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 e3d66b49d3f644..37f0bf2c39adbf 100644 --- a/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt +++ b/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt @@ -4,5 +4,4 @@ ICDServerTestsNL InetLayerTests MessagingLayerTests SecureChannelTestsNL -SupportTestsNL TransportLayerTests From 26be58444bffe8f674a08ecdc893c671c9ff7a96 Mon Sep 17 00:00:00 2001 From: Stefan Agner Date: Wed, 1 May 2024 16:18:33 +0200 Subject: [PATCH 2/3] [Python] Implement async friendly GetConnectedDevice (#32760) * [Python] Implement async friendly GetConnectedDevice Currently GetConnectedDeviceSync() is blocking e.g. when a new session needs to be created. This is not asyncio friendly as it blocks the whole event loop. Implement a asyncio friendly variant GetConnectedDevice() which is a co-routine function which can be awaited. * Drop bracket * Skip timeout only when passing None Change semantics slightly to make 0 mean don't wait at all. * Add API docs --- src/controller/python/chip/ChipDeviceCtrl.py | 84 +++++++++++++++++--- 1 file changed, 75 insertions(+), 9 deletions(-) diff --git a/src/controller/python/chip/ChipDeviceCtrl.py b/src/controller/python/chip/ChipDeviceCtrl.py index b553b2f85b641e..4e57e3d6044e67 100644 --- a/src/controller/python/chip/ChipDeviceCtrl.py +++ b/src/controller/python/chip/ChipDeviceCtrl.py @@ -787,8 +787,16 @@ def GetClusterHandler(self): return self._Cluster - def GetConnectedDeviceSync(self, nodeid, allowPASE=True, timeoutMs: int = None): - ''' Returns DeviceProxyWrapper upon success.''' + def GetConnectedDeviceSync(self, nodeid, allowPASE: bool = True, timeoutMs: int = None): + ''' Gets an OperationalDeviceProxy or CommissioneeDeviceProxy for the specified Node. + + nodeId: Target's Node ID + allowPASE: Get a device proxy of a device being commissioned. + timeoutMs: Timeout for a timed invoke request. Omit or set to 'None' to indicate a non-timed request. + + Returns: + - DeviceProxyWrapper on success + ''' self.CheckIsActive() returnDevice = c_void_p(None) @@ -824,7 +832,7 @@ def deviceAvailable(self, device, err): if returnDevice.value is None: with deviceAvailableCV: timeout = None - if (timeoutMs): + if timeoutMs is not None: timeout = float(timeoutMs) / 1000 ret = deviceAvailableCV.wait(timeout) @@ -836,6 +844,64 @@ def deviceAvailable(self, device, err): return DeviceProxyWrapper(returnDevice, self._dmLib) + async def GetConnectedDevice(self, nodeid, allowPASE: bool = True, timeoutMs: int = None): + ''' Gets an OperationalDeviceProxy or CommissioneeDeviceProxy for the specified Node. + + nodeId: Target's Node ID + allowPASE: Get a device proxy of a device being commissioned. + timeoutMs: Timeout for a timed invoke request. Omit or set to 'None' to indicate a non-timed request. + + Returns: + - DeviceProxyWrapper on success + ''' + self.CheckIsActive() + + if allowPASE: + returnDevice = c_void_p(None) + res = self._ChipStack.Call(lambda: self._dmLib.pychip_GetDeviceBeingCommissioned( + self.devCtrl, nodeid, byref(returnDevice)), timeoutMs) + if res.is_success: + logging.info('Using PASE connection') + return DeviceProxyWrapper(returnDevice) + + eventLoop = asyncio.get_running_loop() + future = eventLoop.create_future() + + class DeviceAvailableClosure(): + def __init__(self, loop, future: asyncio.Future): + self._returnDevice = c_void_p(None) + self._returnErr = None + self._event_loop = loop + self._future = future + + def _deviceAvailable(self): + if self._returnDevice.value is not None: + self._future.set_result(self._returnDevice) + else: + self._future.set_exception(self._returnErr.to_exception()) + + def deviceAvailable(self, device, err): + self._returnDevice = c_void_p(device) + self._returnErr = err + self._event_loop.call_soon_threadsafe(self._deviceAvailable) + ctypes.pythonapi.Py_DecRef(ctypes.py_object(self)) + + closure = DeviceAvailableClosure(eventLoop, future) + ctypes.pythonapi.Py_IncRef(ctypes.py_object(closure)) + self._ChipStack.Call(lambda: self._dmLib.pychip_GetConnectedDeviceByNodeId( + self.devCtrl, nodeid, ctypes.py_object(closure), _DeviceAvailableCallback), + timeoutMs).raise_on_error() + + # The callback might have been received synchronously (during self._ChipStack.Call()). + # In that case the Future has already been set it will return immediately + if timeoutMs is not None: + timeout = float(timeoutMs) / 1000 + await asyncio.wait_for(future, timeout=timeout) + else: + await future + + return DeviceProxyWrapper(future.result(), self._dmLib) + def ComputeRoundTripTimeout(self, nodeid, upperLayerProcessingTimeoutMs: int = 0): ''' Returns a computed timeout value based on the round-trip time it takes for the peer at the other end of the session to receive a message, process it and send it back. This is computed based on the session type, the type of transport, @@ -900,7 +966,7 @@ async def TestOnlySendBatchCommands(self, nodeid: int, commands: typing.List[Clu eventLoop = asyncio.get_running_loop() future = eventLoop.create_future() - device = self.GetConnectedDeviceSync(nodeid, timeoutMs=interactionTimeoutMs) + device = await self.GetConnectedDevice(nodeid, timeoutMs=interactionTimeoutMs) ClusterCommand.TestOnlySendBatchCommands( future, eventLoop, device.deviceProxy, commands, @@ -921,7 +987,7 @@ async def TestOnlySendCommandTimedRequestFlagWithNoTimedInvoke(self, nodeid: int eventLoop = asyncio.get_running_loop() future = eventLoop.create_future() - device = self.GetConnectedDeviceSync(nodeid, timeoutMs=None) + device = await self.GetConnectedDevice(nodeid, timeoutMs=None) ClusterCommand.TestOnlySendCommandTimedRequestFlagWithNoTimedInvoke( future, eventLoop, responseType, device.deviceProxy, ClusterCommand.CommandPath( EndpointId=endpoint, @@ -953,7 +1019,7 @@ async def SendCommand(self, nodeid: int, endpoint: int, payload: ClusterObjects. eventLoop = asyncio.get_running_loop() future = eventLoop.create_future() - device = self.GetConnectedDeviceSync(nodeid, timeoutMs=interactionTimeoutMs) + device = await self.GetConnectedDevice(nodeid, timeoutMs=interactionTimeoutMs) ClusterCommand.SendCommand( future, eventLoop, responseType, device.deviceProxy, ClusterCommand.CommandPath( EndpointId=endpoint, @@ -994,7 +1060,7 @@ async def SendBatchCommands(self, nodeid: int, commands: typing.List[ClusterComm eventLoop = asyncio.get_running_loop() future = eventLoop.create_future() - device = self.GetConnectedDeviceSync(nodeid, timeoutMs=interactionTimeoutMs) + device = await self.GetConnectedDevice(nodeid, timeoutMs=interactionTimeoutMs) ClusterCommand.SendBatchCommands( future, eventLoop, device.deviceProxy, commands, @@ -1044,7 +1110,7 @@ async def WriteAttribute(self, nodeid: int, eventLoop = asyncio.get_running_loop() future = eventLoop.create_future() - device = self.GetConnectedDeviceSync(nodeid, timeoutMs=interactionTimeoutMs) + device = await self.GetConnectedDevice(nodeid, timeoutMs=interactionTimeoutMs) attrs = [] for v in attributes: @@ -1272,7 +1338,7 @@ async def Read(self, nodeid: int, attributes: typing.List[typing.Union[ eventLoop = asyncio.get_running_loop() future = eventLoop.create_future() - device = self.GetConnectedDeviceSync(nodeid) + device = await self.GetConnectedDevice(nodeid) attributePaths = [self._parseAttributePathTuple( v) for v in attributes] if attributes else None clusterDataVersionFilters = [self._parseDataVersionFilterTuple( From 5570be922195347a1dee9187c59d3acf87ae1e94 Mon Sep 17 00:00:00 2001 From: Justin Wood Date: Wed, 1 May 2024 08:18:15 -0700 Subject: [PATCH 3/3] Update .pullapprove.yml --- .pullapprove.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.pullapprove.yml b/.pullapprove.yml index f7da2711417441..c18d52a36eb3b9 100644 --- a/.pullapprove.yml +++ b/.pullapprove.yml @@ -173,6 +173,14 @@ groups: teams: [reviewers-samsung] reviews: request: 10 + shared-reviewers-eve: + type: optional + conditions: + - files.include('*') + reviewers: + teams: [reviewers-eve] + reviews: + request: 10 # shared-reviewers-signify disabled for now, because the reviewers-signify # team is empty and pullapprove seems to mis-handle that badly and treats # _all_ reviewers as being in this group.