From: Alejandro Colomar Date: Wed, 22 Nov 2023 18:39:02 +0000 (+0100) Subject: tests/unit/test_sprintf.c: Test SNPRINTF() X-Git-Tag: 4.15.0-rc1~70 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=ddbd3a36c1fab9ff09cafd11a427bd187e3e18cb;p=thirdparty%2Fshadow.git tests/unit/test_sprintf.c: Test SNPRINTF() Signed-off-by: Alejandro Colomar --- diff --git a/tests/unit/Makefile.am b/tests/unit/Makefile.am index 7416a1ded..03240010b 100644 --- a/tests/unit/Makefile.am +++ b/tests/unit/Makefile.am @@ -5,6 +5,7 @@ TESTS = $(check_PROGRAMS) check_PROGRAMS = \ test_chkname \ + test_sprintf \ test_strncpy \ test_strtcpy \ test_xasprintf @@ -47,6 +48,19 @@ test_logind_LDADD = \ $(LIBSYSTEMD) \ $(NULL) +test_sprintf_SOURCES = \ + ../../lib/string/sprintf.c \ + test_sprintf.c \ + $(NULL) +test_sprintf_CFLAGS = \ + $(AM_FLAGS) \ + $(NULL) +test_sprintf_LDFLAGS = \ + $(NULL) +test_sprintf_LDADD = \ + $(CMOCKA_LIBS) \ + $(NULL) + test_strncpy_SOURCES = \ test_strncpy.c \ $(NULL) diff --git a/tests/unit/test_sprintf.c b/tests/unit/test_sprintf.c new file mode 100644 index 000000000..bedcff6f4 --- /dev/null +++ b/tests/unit/test_sprintf.c @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: 2023, Alejandro Colomar +// SPDX-License-Identifier: BSD-3-Clause + + +#include + +#include +#include + +#include // Required by +#include // Required by +#include // Required by +#include // Required by +#include + +#include "sizeof.h" +#include "string/sprintf.h" + + +static void test_SNPRINTF_trunc(void **state); +static void test_SNPRINTF_ok(void **state); + + +int +main(void) +{ + const struct CMUnitTest tests[] = { + cmocka_unit_test(test_SNPRINTF_trunc), + cmocka_unit_test(test_SNPRINTF_ok), + }; + + return cmocka_run_group_tests(tests, NULL, NULL); +} + + +static void +test_SNPRINTF_trunc(void **state) +{ + char buf[NITEMS("foo")]; + + // Test that we're not returning SIZE_MAX + assert_true(SNPRINTF(buf, "f%su", "oo") < 0); + assert_true(strcmp(buf, "foo") == 0); + + assert_true(SNPRINTF(buf, "barbaz") == -1); + assert_true(strcmp(buf, "bar") == 0); +} + + +static void +test_SNPRINTF_ok(void **state) +{ + char buf[NITEMS("foo")]; + + assert_true(SNPRINTF(buf, "%s", "foo") == strlen("foo")); + assert_true(strcmp(buf, "foo") == 0); + + assert_true(SNPRINTF(buf, "%do", 1) == strlen("1o")); + assert_true(strcmp(buf, "1o") == 0); + + assert_true(SNPRINTF(buf, "f") == strlen("f")); + assert_true(strcmp(buf, "f") == 0); + + assert_true(SNPRINTF(buf, "") == strlen("")); + assert_true(strcmp(buf, "") == 0); +}