From 6d4d2579ab46874cbd8cd4869f6d581267b775a9 Mon Sep 17 00:00:00 2001 From: apio Date: Sat, 22 Oct 2022 20:36:28 +0200 Subject: [PATCH] Tests: Add tests for strchrnul, strdup and strndup --- tests/libc/Test.c | 6 +++++ tests/libc/string.c | 62 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/tests/libc/Test.c b/tests/libc/Test.c index 797a788d..07d30a79 100644 --- a/tests/libc/Test.c +++ b/tests/libc/Test.c @@ -11,8 +11,11 @@ DEFINE_TEST(strnlen); DEFINE_TEST(strcspn); DEFINE_TEST(strspn); DEFINE_TEST(strchr); +DEFINE_TEST(strchrnul); DEFINE_TEST(strrchr); DEFINE_TEST(strpbrk); +DEFINE_TEST(strdup); +DEFINE_TEST(strndup); // stdlib.h DEFINE_TEST(atoi); @@ -35,8 +38,11 @@ int main() RUN_TEST(strcspn); RUN_TEST(strspn); RUN_TEST(strchr); + RUN_TEST(strchrnul); RUN_TEST(strrchr); RUN_TEST(strpbrk); + RUN_TEST(strdup); + RUN_TEST(strndup); START_TEST_CASE(stdlib.h); RUN_TEST(atoi); diff --git a/tests/libc/string.c b/tests/libc/string.c index 004644e8..bd50a930 100644 --- a/tests/libc/string.c +++ b/tests/libc/string.c @@ -1,4 +1,5 @@ #include "Test.h" +#include #include DEFINE_TEST(memset) @@ -229,6 +230,27 @@ DEFINE_TEST(strchr) TEST_SUCCESS(); } +DEFINE_TEST(strchrnul) +{ + START_TEST(strchrnul); + + const char* str = "Hello, world!"; + + char* ptr = strchrnul(str, 'l'); + + EXPECT_EQ(ptr, str + 2); + + ptr = strchrnul(str, 'u'); + + EXPECT_EQ(ptr, str + 13); + + ptr = strchrnul(str, '!'); + + EXPECT_EQ(ptr, str + 12); + + TEST_SUCCESS(); +} + DEFINE_TEST(strrchr) { START_TEST(strrchr); @@ -271,5 +293,45 @@ DEFINE_TEST(strpbrk) EXPECT_EQ(ptr, NULL); + TEST_SUCCESS(); +} + +DEFINE_TEST(strdup) +{ + START_TEST(strdup); + + const char* orig = "Well hello there!"; + + char* copy = strdup(orig); + if (!copy) { TEST_NOT_SURE(copy); } + + EXPECT(memcmp(orig, copy, 17) == 0); + + free(copy); + + TEST_SUCCESS(); +} + +DEFINE_TEST(strndup) +{ + START_TEST(strndup); + + const char* orig = "Well hello there!"; + + char* copy = strndup(orig, 17); + if (!copy) { TEST_NOT_SURE(copy); } + + EXPECT(memcmp(orig, copy, 17) == 0); + + free(copy); + + copy = strndup(orig, 12); + if (!copy) { TEST_NOT_SURE(copy); } + + EXPECT_NOT_EQ(memcmp(orig, copy, 14), + 0); // FIXME: This is undefined behaviour and the memory could also be by chance identical. + + free(copy); + TEST_SUCCESS(); } \ No newline at end of file