]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
tests/unit/test_strlcpy.c: Test strlcpy_() and STRLCPY()
authorAlejandro Colomar <alx@kernel.org>
Fri, 20 Oct 2023 12:58:29 +0000 (14:58 +0200)
committerIker Pedrosa <ikerpedrosam@gmail.com>
Wed, 22 Nov 2023 11:55:26 +0000 (12:55 +0100)
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 <alx@kernel.org>
tests/unit/Makefile.am
tests/unit/test_strlcpy.c [new file with mode: 0644]

index 2ee1449763d3fafdc88ad13e4de15148672959f3..e209f041396b058ba124b6f5f6d8f710af964f0a 100644 (file)
@@ -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 (file)
index 0000000..1c8aa8f
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * SPDX-FileCopyrightText: 2023, Alejandro Colomar <alx@kernel.org>
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+
+#include <config.h>
+
+#include <string.h>
+
+#include <stdarg.h>  // Required by <cmocka.h>
+#include <stddef.h>  // Required by <cmocka.h>
+#include <setjmp.h>  // Required by <cmocka.h>
+#include <stdint.h>  // Required by <cmocka.h>
+#include <cmocka.h>
+
+#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, "");
+}