From 6879f463277df9ad6c4a7b879b40dadb374d79fc Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Fri, 20 Oct 2023 14:58:29 +0200 Subject: [PATCH] tests/unit/test_strlcpy.c: Test strlcpy_() and STRLCPY() This test fails now, due to a bug: the return type of strlcpy_() is size_t, but it should be ssize_t. The next commit will pass the test, by fixing the bug. Signed-off-by: Alejandro Colomar --- tests/unit/Makefile.am | 16 ++++++++++ tests/unit/test_strlcpy.c | 67 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 tests/unit/test_strlcpy.c diff --git a/tests/unit/Makefile.am b/tests/unit/Makefile.am index 2ee144976..e209f0413 100644 --- a/tests/unit/Makefile.am +++ b/tests/unit/Makefile.am @@ -4,6 +4,7 @@ if HAVE_CMOCKA TESTS = $(check_PROGRAMS) check_PROGRAMS = \ + test_strlcpy \ test_xasprintf if ENABLE_LOGIND @@ -31,6 +32,21 @@ test_logind_LDADD = \ $(LIBSYSTEMD) \ $(NULL) +test_strlcpy_SOURCES = \ + ../../lib/strlcpy.c \ + test_strlcpy.c \ + $(NULL) +test_strlcpy_CFLAGS = \ + $(AM_FLAGS) \ + $(LIBBSD_CFLAGS) \ + $(NULL) +test_strlcpy_LDFLAGS = \ + $(NULL) +test_strlcpy_LDADD = \ + $(CMOCKA_LIBS) \ + $(LIBBSD_LIBS) \ + $(NULL) + test_xasprintf_SOURCES = \ ../../lib/sprintf.c \ test_xasprintf.c \ diff --git a/tests/unit/test_strlcpy.c b/tests/unit/test_strlcpy.c new file mode 100644 index 000000000..1c8aa8f6b --- /dev/null +++ b/tests/unit/test_strlcpy.c @@ -0,0 +1,67 @@ +/* + * SPDX-FileCopyrightText: 2023, Alejandro Colomar + * SPDX-License-Identifier: BSD-3-Clause + */ + + +#include + +#include + +#include // Required by +#include // Required by +#include // Required by +#include // Required by +#include + +#include "sizeof.h" +#include "strlcpy.h" + + +static void test_STRLCPY_trunc(void **state); +static void test_STRLCPY_ok(void **state); + + +int +main(void) +{ + const struct CMUnitTest tests[] = { + cmocka_unit_test(test_STRLCPY_trunc), + cmocka_unit_test(test_STRLCPY_ok), + }; + + return cmocka_run_group_tests(tests, NULL, NULL); +} + + +static void +test_STRLCPY_trunc(void **state) +{ + char buf[NITEMS("foo")]; + + // Test that we're not returning SIZE_MAX + assert_true(STRLCPY(buf, "fooo") < 0); + assert_string_equal(buf, "foo"); + + assert_int_equal(STRLCPY(buf, "barbaz"), -1); + assert_string_equal(buf, "bar"); +} + + +static void +test_STRLCPY_ok(void **state) +{ + char buf[NITEMS("foo")]; + + assert_int_equal(STRLCPY(buf, "foo"), strlen("foo")); + assert_string_equal(buf, "foo"); + + assert_int_equal(STRLCPY(buf, "fo"), strlen("fo")); + assert_string_equal(buf, "fo"); + + assert_int_equal(STRLCPY(buf, "f"), strlen("f")); + assert_string_equal(buf, "f"); + + assert_int_equal(STRLCPY(buf, ""), strlen("")); + assert_string_equal(buf, ""); +} -- 2.47.2