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 <alx@kernel.org>
This commit is contained in:
Alejandro Colomar 2023-10-20 14:58:29 +02:00 committed by Iker Pedrosa
parent dad103bdb9
commit 6879f46327
2 changed files with 83 additions and 0 deletions

View File

@ -4,6 +4,7 @@ if HAVE_CMOCKA
TESTS = $(check_PROGRAMS) TESTS = $(check_PROGRAMS)
check_PROGRAMS = \ check_PROGRAMS = \
test_strlcpy \
test_xasprintf test_xasprintf
if ENABLE_LOGIND if ENABLE_LOGIND
@ -31,6 +32,21 @@ test_logind_LDADD = \
$(LIBSYSTEMD) \ $(LIBSYSTEMD) \
$(NULL) $(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 = \ test_xasprintf_SOURCES = \
../../lib/sprintf.c \ ../../lib/sprintf.c \
test_xasprintf.c \ test_xasprintf.c \

67
tests/unit/test_strlcpy.c Normal file
View File

@ -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, "");
}