diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-06-12 03:50:45 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-06-12 03:50:45 +0000 |
commit | efeb864cb547a2cbf96dc0053a8bdb4d9190b364 (patch) | |
tree | c0b83368f18be983fcc763200c4c24d633244588 /src/test | |
parent | Releasing progress-linux version 255.5-1~progress7.99u1. (diff) | |
download | systemd-efeb864cb547a2cbf96dc0053a8bdb4d9190b364.tar.xz systemd-efeb864cb547a2cbf96dc0053a8bdb4d9190b364.zip |
Merging upstream version 256.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
157 files changed, 6011 insertions, 2780 deletions
diff --git a/src/test/meson.build b/src/test/meson.build index cce90d7..3abbb94 100644 --- a/src/test/meson.build +++ b/src/test/meson.build @@ -14,7 +14,7 @@ test_env = environment() test_env.set('SYSTEMD_LANGUAGE_FALLBACK_MAP', language_fallback_map) test_env.set('PATH', project_build_root + ':' + path) test_env.set('PROJECT_BUILD_ROOT', project_build_root) -test_env.set('SYSTEMD_SLOW_TESTS', slow_tests ? '1' : '0') +test_env.set('SYSTEMD_SLOW_TESTS', want_slow_tests ? '1' : '0') if efi_addon != '' test_env.set('EFI_ADDON', efi_addon) @@ -51,6 +51,7 @@ simple_tests += files( 'test-bitmap.c', 'test-blockdev-util.c', 'test-bootspec.c', + 'test-build-path.c', 'test-bus-util.c', 'test-calendarspec.c', 'test-cgroup-setup.c', @@ -58,6 +59,7 @@ simple_tests += files( 'test-cgroup.c', 'test-chase.c', 'test-clock.c', + 'test-color-util.c', 'test-compare-operator.c', 'test-condition.c', 'test-conf-files.c', @@ -72,6 +74,7 @@ simple_tests += files( 'test-dev-setup.c', 'test-device-nodes.c', 'test-devnum-util.c', + 'test-dirent-util.c', 'test-dns-domain.c', 'test-ellipsize.c', 'test-env-file.c', @@ -107,8 +110,10 @@ simple_tests += files( 'test-install-file.c', 'test-install-root.c', 'test-io-util.c', + 'test-iovec-util.c', 'test-journal-importer.c', 'test-kbd-util.c', + 'test-label.c', 'test-limits-util.c', 'test-list.c', 'test-local-addresses.c', @@ -116,6 +121,7 @@ simple_tests += files( 'test-lock-util.c', 'test-log.c', 'test-logarithm.c', + 'test-login-util.c', 'test-macro.c', 'test-memfd-util.c', 'test-memory-util.c', @@ -134,6 +140,7 @@ simple_tests += files( 'test-path-lookup.c', 'test-path-util.c', 'test-percent-util.c', + 'test-pidref.c', 'test-pretty-print.c', 'test-prioq.c', 'test-proc-cmdline.c', @@ -141,6 +148,7 @@ simple_tests += files( 'test-psi-util.c', 'test-ratelimit.c', 'test-raw-clone.c', + 'test-recovery-key.c', 'test-recurse-dir.c', 'test-replace-var.c', 'test-rlimit-util.c', @@ -170,7 +178,7 @@ simple_tests += files( 'test-terminal-util.c', 'test-tmpfile-util.c', 'test-udev-util.c', - 'test-uid-alloc-range.c', + 'test-uid-classification.c', 'test-uid-range.c', 'test-umask-util.c', 'test-unaligned.c', @@ -178,6 +186,7 @@ simple_tests += files( 'test-user-util.c', 'test-utf8.c', 'test-verbs.c', + 'test-vpick.c', 'test-web-util.c', 'test-xattr-util.c', 'test-xml.c', @@ -242,18 +251,12 @@ executables += [ }, test_template + { 'sources' : files('test-compress-benchmark.c'), - 'link_with' : [ - libbasic_compress, - libshared, - ], + 'link_with' : [libshared], 'timeout' : 90, }, test_template + { 'sources' : files('test-compress.c'), - 'link_with' : [ - libbasic_compress, - libshared, - ], + 'link_with' : [libshared], }, test_template + { 'sources' : files('test-cryptolib.c'), @@ -262,7 +265,10 @@ executables += [ }, test_template + { 'sources' : files('test-dlopen-so.c'), - 'dependencies' : libp11kit_cflags + 'dependencies' : [ + libp11kit_cflags, + libkmod_cflags, + ], }, test_template + { # only static linking apart from libdl, to make sure that the @@ -332,7 +338,7 @@ executables += [ }, test_template + { 'sources' : files('test-netlink-manual.c'), - 'dependencies' : libkmod, + 'dependencies' : libkmod_cflags, 'conditions' : ['HAVE_KMOD'], 'type' : 'manual', }, @@ -376,6 +382,10 @@ executables += [ 'dependencies' : threads, }, test_template + { + 'sources' : files('test-progress-bar.c'), + 'type' : 'manual', + }, + test_template + { 'sources' : files('test-qrcode-util.c'), 'dependencies' : libdl, }, @@ -475,7 +485,7 @@ executables += [ 'sources' : files('test-bpf-foreign-programs.c'), }, core_test_template + { - 'sources' : files('test-bpf-lsm.c'), + 'sources' : files('test-bpf-restrict-fs.c'), 'dependencies' : common_test_dependencies, }, core_test_template + { @@ -525,7 +535,7 @@ executables += [ 'parallel' : false, }, core_test_template + { - 'sources' : files('test-manager.c'), + 'sources' : files('test-taint.c'), }, core_test_template + { 'sources' : files('test-namespace.c'), @@ -579,12 +589,18 @@ executables += [ }, test_template + { 'sources' : files('../libsystemd/sd-device/test-sd-device-thread.c'), - 'link_with' : libsystemd, + 'link_with' : [ + libbasic, + libsystemd, + ], 'dependencies' : threads, }, test_template + { 'sources' : files('../libudev/test-udev-device-thread.c'), - 'link_with' : libudev, + 'link_with' : [ + libbasic, + libudev, + ], 'dependencies' : threads, }, test_template + { @@ -594,4 +610,8 @@ executables += [ libudev_basic, ], }, + test_template + { + 'sources' : files('test-aux-scope.c'), + 'type' : 'manual', + }, ] diff --git a/src/test/test-acl-util.c b/src/test/test-acl-util.c index eb9678a..0cc9afc 100644 --- a/src/test/test-acl-util.c +++ b/src/test/test-acl-util.c @@ -10,6 +10,7 @@ #include "fd-util.h" #include "format-util.h" #include "fs-util.h" +#include "path-util.h" #include "string-util.h" #include "tests.h" #include "tmpfile-util.h" @@ -22,6 +23,12 @@ TEST_RET(add_acls_for_user) { uid_t uid; int r; + FOREACH_STRING(s, "capsh", "getfacl", "ls") { + r = find_executable(s, NULL); + if (r < 0) + return log_tests_skipped_errno(r, "Could not find %s binary: %m", s); + } + fd = mkostemp_safe(fn); assert_se(fd >= 0); @@ -69,11 +76,18 @@ TEST_RET(add_acls_for_user) { return 0; } -TEST(fd_acl_make_read_only) { +TEST_RET(fd_acl_make_read_only) { _cleanup_(unlink_tempfilep) char fn[] = "/tmp/test-empty.XXXXXX"; _cleanup_close_ int fd = -EBADF; const char *cmd; struct stat st; + int r; + + FOREACH_STRING(s, "capsh", "getfacl", "ls", "stat") { + r = find_executable(s, NULL); + if (r < 0) + return log_tests_skipped_errno(r, "Could not find %s binary: %m", s); + } fd = mkostemp_safe(fn); assert_se(fd >= 0); @@ -81,8 +95,8 @@ TEST(fd_acl_make_read_only) { /* make it more exciting */ (void) fd_add_uid_acl_permission(fd, 1, ACL_READ|ACL_WRITE|ACL_EXECUTE); - assert_se(fstat(fd, &st) >= 0); - assert_se((st.st_mode & 0200) == 0200); + ASSERT_OK_ERRNO(fstat(fd, &st)); + assert_se(FLAGS_SET(st.st_mode, 0200)); cmd = strjoina("getfacl -p ", fn); assert_se(system(cmd) == 0); @@ -93,7 +107,7 @@ TEST(fd_acl_make_read_only) { log_info("read-only"); assert_se(fd_acl_make_read_only(fd)); - assert_se(fstat(fd, &st) >= 0); + ASSERT_OK_ERRNO(fstat(fd, &st)); assert_se((st.st_mode & 0222) == 0000); cmd = strjoina("getfacl -p ", fn); @@ -105,7 +119,7 @@ TEST(fd_acl_make_read_only) { log_info("writable"); assert_se(fd_acl_make_writable(fd)); - assert_se(fstat(fd, &st) >= 0); + ASSERT_OK_ERRNO(fstat(fd, &st)); assert_se((st.st_mode & 0222) == 0200); cmd = strjoina("getfacl -p ", fn); @@ -117,7 +131,7 @@ TEST(fd_acl_make_read_only) { log_info("read-only"); assert_se(fd_acl_make_read_only(fd)); - assert_se(fstat(fd, &st) >= 0); + ASSERT_OK_ERRNO(fstat(fd, &st)); assert_se((st.st_mode & 0222) == 0000); cmd = strjoina("getfacl -p ", fn); @@ -125,6 +139,8 @@ TEST(fd_acl_make_read_only) { cmd = strjoina("stat ", fn); assert_se(system(cmd) == 0); + + return 0; } DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-af-list.c b/src/test/test-af-list.c index 45655d7..1623c48 100644 --- a/src/test/test-af-list.c +++ b/src/test/test-af-list.c @@ -16,13 +16,14 @@ static const struct af_name* lookup_af(register const char *str, register GPERF_ TEST(af_list) { for (unsigned i = 0; i < ELEMENTSOF(af_names); i++) { if (af_names[i]) { - assert_se(streq(af_to_name(i), af_names[i])); + ASSERT_STREQ(af_to_name(i), af_names[i]); assert_se(af_from_name(af_names[i]) == (int) i); } } - assert_se(af_to_name(af_max()) == NULL); - assert_se(af_to_name(-1) == NULL); + ASSERT_NULL(af_to_name(af_max())); + ASSERT_NULL(af_to_name(0)); + ASSERT_NULL(af_to_name(-1)); assert_se(af_from_name("huddlduddl") == -EINVAL); assert_se(af_from_name("") == -EINVAL); } diff --git a/src/test/test-architecture.c b/src/test/test-architecture.c index 8731e1c..6b7777d 100644 --- a/src/test/test-architecture.c +++ b/src/test/test-architecture.c @@ -3,6 +3,7 @@ #include "architecture.h" #include "errno-util.h" #include "log.h" +#include "path-util.h" #include "tests.h" #include "virt.h" @@ -13,18 +14,18 @@ int main(int argc, char *argv[]) { test_setup_logging(LOG_INFO); - assert_se(architecture_from_string("") < 0); - assert_se(architecture_from_string(NULL) < 0); - assert_se(architecture_from_string("hoge") < 0); - assert_se(architecture_to_string(-1) == NULL); - assert_se(architecture_from_string(architecture_to_string(0)) == 0); - assert_se(architecture_from_string(architecture_to_string(1)) == 1); + ASSERT_LT(architecture_from_string(""), 0); + ASSERT_LT(architecture_from_string(NULL), 0); + ASSERT_LT(architecture_from_string("hoge"), 0); + ASSERT_NULL(architecture_to_string(-1)); + ASSERT_EQ(architecture_from_string(architecture_to_string(0)), 0); + ASSERT_EQ(architecture_from_string(architecture_to_string(1)), 1); v = detect_virtualization(); if (ERRNO_IS_NEG_PRIVILEGE(v)) return log_tests_skipped("Cannot detect virtualization"); - assert_se(v >= 0); + ASSERT_OK(v); log_info("virtualization=%s id=%s", VIRTUALIZATION_IS_CONTAINER(v) ? "container" : @@ -32,22 +33,34 @@ int main(int argc, char *argv[]) { virtualization_to_string(v)); a = uname_architecture(); - assert_se(a >= 0); + ASSERT_OK(a); p = architecture_to_string(a); assert_se(p); log_info("uname architecture=%s", p); - assert_se(architecture_from_string(p) == a); + ASSERT_EQ(architecture_from_string(p), a); a = native_architecture(); - assert_se(a >= 0); + ASSERT_OK(a); p = architecture_to_string(a); assert_se(p); log_info("native architecture=%s", p); - assert_se(architecture_from_string(p) == a); + ASSERT_EQ(architecture_from_string(p), a); log_info("primary library architecture=" LIB_ARCH_TUPLE); + for (Architecture i = 0; i < _ARCHITECTURE_MAX; i++) { + const char *n = ASSERT_PTR(architecture_to_string(i)); + + /* Let's validate that all architecture names we define are good for inclusion in .v/ + * filename patterns which use "." and "_" as field separators in the filenames. */ + assert(filename_part_is_valid(n)); + assert(!strchr(n, '_')); + assert(!strchr(n, '.')); + + log_info("Good for inclusion in .v/ filenames: %s", n); + } + return 0; } diff --git a/src/test/test-argv-util.c b/src/test/test-argv-util.c index 5bf2903..f7b8f94 100644 --- a/src/test/test-argv-util.c +++ b/src/test/test-argv-util.c @@ -122,6 +122,11 @@ TEST(argv_help) { assert_se(argv_looks_like_help(4, STRV_MAKE("program", "arg1", "arg2", "-h"))); assert_se(!argv_looks_like_help(2, STRV_MAKE("program", "arg1"))); assert_se(!argv_looks_like_help(4, STRV_MAKE("program", "arg1", "arg2", "--h"))); + assert_se(!argv_looks_like_help(3, STRV_MAKE("program", "Help", "arg2"))); + assert_se(argv_looks_like_help(5, STRV_MAKE("program", "--help", "arg1", "-h", "--help"))); + assert_se(!argv_looks_like_help(4, STRV_MAKE("program","arg1", "arg2", "-H"))); + assert_se(!argv_looks_like_help(3, STRV_MAKE("program", "--Help", "arg2"))); + } static int intro(void) { diff --git a/src/test/test-arphrd-util.c b/src/test/test-arphrd-util.c index d8dd464..15b7997 100644 --- a/src/test/test-arphrd-util.c +++ b/src/test/test-arphrd-util.c @@ -1,5 +1,7 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* Make sure the net/if.h header is included before any linux/ one */ +#include <net/if.h> #include <linux/if_arp.h> #include "arphrd-util.h" @@ -14,11 +16,11 @@ TEST(arphrd) { if (name) { log_info("%i: %s", i, name); - assert_se(arphrd_from_name(name) == i); + ASSERT_EQ(arphrd_from_name(name), i); } } - assert_se(arphrd_to_name(ARPHRD_VOID + 1) == NULL); + ASSERT_NULL(arphrd_to_name(ARPHRD_VOID + 1)); assert_se(arphrd_from_name("huddlduddl") == -EINVAL); assert_se(arphrd_from_name("") == -EINVAL); } diff --git a/src/test/test-ask-password-api.c b/src/test/test-ask-password-api.c index b24159e..e58e868 100644 --- a/src/test/test-ask-password-api.c +++ b/src/test/test-ask-password-api.c @@ -5,14 +5,19 @@ #include "tests.h" TEST(ask_password) { - int r; _cleanup_strv_free_ char **ret = NULL; + int r; + + static const AskPasswordRequest req = { + .message = "hello?", + .keyring = "da key", + }; - r = ask_password_tty(-1, "hello?", "da key", 0, ASK_PASSWORD_CONSOLE_COLOR, NULL, &ret); + r = ask_password_tty(-EBADF, &req, /* until= */ 0, /* flags= */ ASK_PASSWORD_CONSOLE_COLOR, /* flag_file= */ NULL, &ret); if (r == -ECANCELED) - assert_se(ret == NULL); + ASSERT_NULL(ret); else { - assert_se(r >= 0); + ASSERT_OK(r); assert_se(strv_length(ret) == 1); log_info("Got \"%s\"", *ret); } diff --git a/src/test/test-async.c b/src/test/test-async.c index 75bc4d8..ee6bae2 100644 --- a/src/test/test-async.c +++ b/src/test/test-async.c @@ -10,11 +10,24 @@ #include "path-util.h" #include "process-util.h" #include "signal-util.h" +#include "time-util.h" #include "tests.h" #include "tmpfile-util.h" TEST(asynchronous_sync) { - assert_se(asynchronous_sync(NULL) >= 0); + ASSERT_OK(asynchronous_sync(NULL)); +} + +static void wait_fd_closed(int fd) { + for (unsigned trial = 0; trial < 100; trial++) { + usleep_safe(100 * USEC_PER_MSEC); + if (fcntl(fd, F_GETFD) < 0) { + assert_se(errno == EBADF); + return; + } + } + + assert_not_reached(); } TEST(asynchronous_close) { @@ -22,67 +35,72 @@ TEST(asynchronous_close) { int fd, r; fd = mkostemp_safe(name); - assert_se(fd >= 0); + ASSERT_OK(fd); asynchronous_close(fd); - - sleep(1); - - assert_se(fcntl(fd, F_GETFD) == -1); - assert_se(errno == EBADF); + wait_fd_closed(fd); r = safe_fork("(subreaper)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL|FORK_LOG|FORK_WAIT, NULL); - assert(r >= 0); + ASSERT_OK(r); if (r == 0) { /* child */ - assert(make_reaper_process(true) >= 0); + ASSERT_OK(make_reaper_process(true)); fd = open("/dev/null", O_RDONLY|O_CLOEXEC); - assert_se(fd >= 0); + ASSERT_OK(fd); asynchronous_close(fd); - - sleep(1); - - assert_se(fcntl(fd, F_GETFD) == -1); - assert_se(errno == EBADF); + wait_fd_closed(fd); _exit(EXIT_SUCCESS); } } +static void wait_rm_rf(const char *path) { + for (unsigned trial = 0; trial < 100; trial++) { + usleep_safe(100 * USEC_PER_MSEC); + if (access(path, F_OK) < 0) { + assert_se(errno == ENOENT); + return; + } + } + + assert_not_reached(); +} + TEST(asynchronous_rm_rf) { _cleanup_free_ char *t = NULL, *k = NULL; int r; - assert_se(mkdtemp_malloc(NULL, &t) >= 0); + ASSERT_OK(mkdtemp_malloc(NULL, &t)); assert_se(k = path_join(t, "somefile")); - assert_se(touch(k) >= 0); - assert_se(asynchronous_rm_rf(t, REMOVE_ROOT|REMOVE_PHYSICAL) >= 0); + ASSERT_OK(touch(k)); + ASSERT_OK(asynchronous_rm_rf(t, REMOVE_ROOT|REMOVE_PHYSICAL)); + wait_rm_rf(t); - /* Do this once more, form a subreaper. Which is nice, because we can watch the async child even + /* Do this once more, from a subreaper. Which is nice, because we can watch the async child even * though detached */ r = safe_fork("(subreaper)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGTERM|FORK_LOG|FORK_WAIT, NULL); - assert_se(r >= 0); + ASSERT_OK(r); if (r == 0) { _cleanup_free_ char *tt = NULL, *kk = NULL; /* child */ - assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD, -1) >= 0); - assert_se(make_reaper_process(true) >= 0); + ASSERT_OK(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD)); + ASSERT_OK(make_reaper_process(true)); - assert_se(mkdtemp_malloc(NULL, &tt) >= 0); + ASSERT_OK(mkdtemp_malloc(NULL, &tt)); assert_se(kk = path_join(tt, "somefile")); - assert_se(touch(kk) >= 0); - assert_se(asynchronous_rm_rf(tt, REMOVE_ROOT|REMOVE_PHYSICAL) >= 0); + ASSERT_OK(touch(kk)); + ASSERT_OK(asynchronous_rm_rf(tt, REMOVE_ROOT|REMOVE_PHYSICAL)); for (;;) { siginfo_t si = {}; - assert_se(waitid(P_ALL, 0, &si, WEXITED) >= 0); + ASSERT_OK(waitid(P_ALL, 0, &si, WEXITED)); if (access(tt, F_OK) < 0) { assert_se(errno == ENOENT); diff --git a/src/test/test-aux-scope.c b/src/test/test-aux-scope.c new file mode 100644 index 0000000..0170314 --- /dev/null +++ b/src/test/test-aux-scope.c @@ -0,0 +1,168 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include <errno.h> +#include <stdio.h> +#include <stdlib.h> +#if HAVE_PIDFD_OPEN +#include <sys/pidfd.h> +#endif +#include <sys/wait.h> + +#include "sd-event.h" + +#include "bus-error.h" +#include "bus-message.h" +#include "bus-wait-for-jobs.h" +#include "daemon-util.h" +#include "fd-util.h" +#include "log.h" +#include "missing_syscall.h" +#include "process-util.h" +#include "tests.h" + +static int on_sigusr1(sd_event_source *s, const struct signalfd_siginfo *ssi, void *userdata) { + _cleanup_(sd_bus_message_unrefp) sd_bus_message *message = NULL, *reply = NULL; + _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; + _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL; + _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL; + PidRef *pids = (PidRef *) userdata; + const char *job; + int r; + + assert(pids); + + r = sd_bus_open_system(&bus); + if (r < 0) + return log_error_errno(r, "Failed to acquire bus: %m"); + + r = sd_bus_message_new_method_call(bus, &message, + "org.freedesktop.systemd1", + "/org/freedesktop/systemd1", + "org.freedesktop.systemd1.Manager", + "StartAuxiliaryScope"); + if (r < 0) + return log_error_errno(r, "Failed to create bus message: %m"); + + r = sd_bus_message_append_basic(message, 's', "test-aux-scope.scope"); + if (r < 0) + return log_error_errno(r, "Failed to attach scope name: %m"); + + r = sd_bus_message_open_container(message, 'a', "h"); + if (r < 0) + return log_error_errno(r, "Failed to create array of FDs: %m"); + + for (size_t i = 0; i < 10; i++) { + r = sd_bus_message_append_basic(message, 'h', &pids[i].fd); + if (r < 0) + return log_error_errno(r, "Failed to append PIDFD to message: %m"); + } + + r = sd_bus_message_close_container(message); + if (r < 0) + return log_error_errno(r, "Failed to close container: %m"); + + r = sd_bus_message_append(message, "ta(sv)", UINT64_C(0), 1, "Description", "s", "Test auxiliary scope"); + if (r < 0) + return log_error_errno(r, "Failed to append unit properties: %m"); + + r = sd_bus_call(bus, message, 0, &error, &reply); + if (r < 0) + return log_error_errno(r, "Failed to start auxiliary scope: %s", bus_error_message(&error, r)); + + r = sd_bus_message_read(reply, "o", &job); + if (r < 0) + return log_error_errno(r, "Failed to read reply: %m"); + + r = bus_wait_for_jobs_new(bus, &w); + if (r < 0) + return log_error_errno(r, "Could not watch jobs: %m"); + + r = bus_wait_for_jobs_one(w, job, false, NULL); + if (r < 0) + return r; + + return 0; +} + +static void destroy_pidrefs(PidRef *pids, size_t npids) { + assert(pids || npids == 0); + + for (size_t i = 0; i < npids; i++) + pidref_done(&pids[i]); + + free(pids); +} + +int main(int argc, char *argv[]) { + _cleanup_(sd_event_unrefp) sd_event *event = NULL; + PidRef *pids = NULL; + size_t npids = 0; + int r, fd; + + CLEANUP_ARRAY(pids, npids, destroy_pidrefs); + + test_setup_logging(LOG_INFO); + + fd = pidfd_open(getpid_cached(), 0); + if (fd < 0 && (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno))) + return log_tests_skipped("pidfds are not available"); + else if (fd < 0) { + log_error_errno(errno, "pidfd_open() failed: %m"); + return EXIT_FAILURE; + } + safe_close(fd); + + r = sd_event_new(&event); + if (r < 0) { + log_error_errno(r, "Failed to allocate event loop: %m"); + return EXIT_FAILURE; + } + + npids = 10; + pids = new0(PidRef, npids); + assert(pids); + + r = sd_event_add_signal(event, NULL, SIGUSR1|SD_EVENT_SIGNAL_PROCMASK, on_sigusr1, pids); + if (r < 0) { + log_error_errno(r, "Failed to setup SIGUSR1 signal handling: %m"); + return EXIT_FAILURE; + } + + for (size_t i = 0; i < npids; i++) { + PidRef pidref = PIDREF_NULL; + pid_t pid; + + r = safe_fork("(worker)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM|FORK_CLOSE_ALL_FDS, &pid); + if (r < 0) { + log_error_errno(r, "Failed to fork(): %m"); + return EXIT_FAILURE; + } + + if (r == 0) { + /* Worker */ + sleep(3600); + _exit(EXIT_SUCCESS); + } + + r = pidref_set_pid(&pidref, pid); + if (r < 0) { + log_error_errno(r, "Failed to initialize PID ref: %m"); + return EXIT_FAILURE; + } + + assert_se(pidref.pid == pid); + assert_se(pidref.fd != -EBADF); + + pids[i] = TAKE_PIDREF(pidref); + } + + r = sd_notify(false, NOTIFY_READY); + if (r < 0) + return log_error_errno(r, "Failed to send readiness notification: %m"); + + r = sd_event_loop(event); + if (r < 0) + return log_error_errno(r, "Failed to run event loop: %m"); + + return 0; +} diff --git a/src/test/test-barrier.c b/src/test/test-barrier.c index 7e8bfc0..1e0da59 100644 --- a/src/test/test-barrier.c +++ b/src/test/test-barrier.c @@ -30,7 +30,7 @@ static void set_alarm(usec_t usecs) { struct itimerval v = { }; timeval_store(&v.it_value, usecs); - assert_se(setitimer(ITIMER_REAL, &v, NULL) >= 0); + ASSERT_OK(setitimer(ITIMER_REAL, &v, NULL)); } #define TEST_BARRIER(_FUNCTION, _CHILD_CODE, _WAIT_CHILD, _PARENT_CODE, _WAIT_PARENT) \ @@ -38,14 +38,14 @@ static void set_alarm(usec_t usecs) { Barrier b = BARRIER_NULL; \ pid_t pid1, pid2; \ \ - assert_se(barrier_create(&b) >= 0); \ - assert_se(b.me > 0); \ - assert_se(b.them > 0); \ - assert_se(b.pipe[0] > 0); \ - assert_se(b.pipe[1] > 0); \ + ASSERT_OK(barrier_create(&b)); \ + ASSERT_GT(b.me, 0); \ + ASSERT_GT(b.them, 0); \ + ASSERT_GT(b.pipe[0], 0); \ + ASSERT_GT(b.pipe[1], 0); \ \ pid1 = fork(); \ - assert_se(pid1 >= 0); \ + ASSERT_OK(pid1); \ if (pid1 == 0) { \ barrier_set_role(&b, BARRIER_CHILD); \ { _CHILD_CODE; } \ @@ -53,7 +53,7 @@ static void set_alarm(usec_t usecs) { } \ \ pid2 = fork(); \ - assert_se(pid2 >= 0); \ + ASSERT_OK(pid2); \ if (pid2 == 0) { \ barrier_set_role(&b, BARRIER_PARENT); \ { _PARENT_CODE; } \ @@ -71,16 +71,16 @@ static void set_alarm(usec_t usecs) { ({ \ int pidr, status; \ pidr = waitpid(_pid, &status, 0); \ - assert_se(pidr == _pid); \ + ASSERT_EQ(pidr, _pid); \ assert_se(WIFEXITED(status)); \ - assert_se(WEXITSTATUS(status) == 42); \ + ASSERT_EQ(WEXITSTATUS(status), 42); \ }) #define TEST_BARRIER_WAIT_ALARM(_pid) \ ({ \ int pidr, status; \ pidr = waitpid(_pid, &status, 0); \ - assert_se(pidr == _pid); \ + ASSERT_EQ(pidr, _pid); \ assert_se(WIFSIGNALED(status)); \ assert_se(WTERMSIG(status) == SIGALRM); \ }) diff --git a/src/test/test-bitmap.c b/src/test/test-bitmap.c index 8acf833..b91b293 100644 --- a/src/test/test-bitmap.c +++ b/src/test/test-bitmap.c @@ -12,50 +12,50 @@ int main(int argc, const char *argv[]) { b = bitmap_new(); assert_se(b); - assert_se(bitmap_ensure_allocated(&b) == 0); + ASSERT_EQ(bitmap_ensure_allocated(&b), 0); b = bitmap_free(b); - assert_se(bitmap_ensure_allocated(&b) == 0); + ASSERT_EQ(bitmap_ensure_allocated(&b), 0); - assert_se(bitmap_isset(b, 0) == false); - assert_se(bitmap_isset(b, 1) == false); - assert_se(bitmap_isset(b, 256) == false); - assert_se(bitmap_isclear(b) == true); + ASSERT_FALSE(bitmap_isset(b, 0)); + ASSERT_FALSE(bitmap_isset(b, 1)); + ASSERT_FALSE(bitmap_isset(b, 256)); + ASSERT_TRUE(bitmap_isclear(b)); - assert_se(bitmap_set(b, 0) == 0); - assert_se(bitmap_isset(b, 0) == true); - assert_se(bitmap_isclear(b) == false); + ASSERT_EQ(bitmap_set(b, 0), 0); + ASSERT_TRUE(bitmap_isset(b, 0)); + ASSERT_FALSE(bitmap_isclear(b)); bitmap_unset(b, 0); - assert_se(bitmap_isset(b, 0) == false); - assert_se(bitmap_isclear(b) == true); + ASSERT_FALSE(bitmap_isset(b, 0)); + ASSERT_TRUE(bitmap_isclear(b)); - assert_se(bitmap_set(b, 1) == 0); - assert_se(bitmap_isset(b, 1) == true); - assert_se(bitmap_isclear(b) == false); + ASSERT_EQ(bitmap_set(b, 1), 0); + ASSERT_TRUE(bitmap_isset(b, 1)); + ASSERT_FALSE(bitmap_isclear(b)); bitmap_unset(b, 1); - assert_se(bitmap_isset(b, 1) == false); - assert_se(bitmap_isclear(b) == true); + ASSERT_FALSE(bitmap_isset(b, 1)); + ASSERT_TRUE(bitmap_isclear(b)); - assert_se(bitmap_set(b, 256) == 0); - assert_se(bitmap_isset(b, 256) == true); - assert_se(bitmap_isclear(b) == false); + ASSERT_EQ(bitmap_set(b, 256), 0); + ASSERT_TRUE(bitmap_isset(b, 256)); + ASSERT_FALSE(bitmap_isclear(b)); bitmap_unset(b, 256); - assert_se(bitmap_isset(b, 256) == false); - assert_se(bitmap_isclear(b) == true); + ASSERT_FALSE(bitmap_isset(b, 256)); + ASSERT_TRUE(bitmap_isclear(b)); - assert_se(bitmap_set(b, 32) == 0); + ASSERT_EQ(bitmap_set(b, 32), 0); bitmap_unset(b, 0); - assert_se(bitmap_isset(b, 32) == true); + ASSERT_TRUE(bitmap_isset(b, 32)); bitmap_unset(b, 32); BITMAP_FOREACH(n, NULL) assert_not_reached(); - assert_se(bitmap_set(b, 0) == 0); - assert_se(bitmap_set(b, 1) == 0); - assert_se(bitmap_set(b, 256) == 0); + ASSERT_EQ(bitmap_set(b, 0), 0); + ASSERT_EQ(bitmap_set(b, 1), 0); + ASSERT_EQ(bitmap_set(b, 256), 0); BITMAP_FOREACH(n, b) { - assert_se(n == i); + ASSERT_EQ(n, i); if (i == 0) i = 1; else if (i == 1) @@ -64,12 +64,12 @@ int main(int argc, const char *argv[]) { i = UINT_MAX; } - assert_se(i == UINT_MAX); + ASSERT_EQ(i, UINT_MAX); i = 0; BITMAP_FOREACH(n, b) { - assert_se(n == i); + ASSERT_EQ(n, i); if (i == 0) i = 1; else if (i == 1) @@ -78,38 +78,38 @@ int main(int argc, const char *argv[]) { i = UINT_MAX; } - assert_se(i == UINT_MAX); + ASSERT_EQ(i, UINT_MAX); b2 = bitmap_copy(b); assert_se(b2); - assert_se(bitmap_equal(b, b2) == true); - assert_se(bitmap_equal(b, b) == true); - assert_se(bitmap_equal(b, NULL) == false); - assert_se(bitmap_equal(NULL, b) == false); - assert_se(bitmap_equal(NULL, NULL) == true); + ASSERT_TRUE(bitmap_equal(b, b2)); + ASSERT_TRUE(bitmap_equal(b, b)); + ASSERT_FALSE(bitmap_equal(b, NULL)); + ASSERT_FALSE(bitmap_equal(NULL, b)); + ASSERT_TRUE(bitmap_equal(NULL, NULL)); bitmap_clear(b); - assert_se(bitmap_isclear(b) == true); - assert_se(bitmap_equal(b, b2) == false); + ASSERT_TRUE(bitmap_isclear(b)); + ASSERT_FALSE(bitmap_equal(b, b2)); b2 = bitmap_free(b2); assert_se(bitmap_set(b, UINT_MAX) == -ERANGE); b = bitmap_free(b); - assert_se(bitmap_ensure_allocated(&b) == 0); - assert_se(bitmap_ensure_allocated(&b2) == 0); + ASSERT_EQ(bitmap_ensure_allocated(&b), 0); + ASSERT_EQ(bitmap_ensure_allocated(&b2), 0); assert_se(bitmap_equal(b, b2)); - assert_se(bitmap_set(b, 0) == 0); + ASSERT_EQ(bitmap_set(b, 0), 0); bitmap_unset(b, 0); assert_se(bitmap_equal(b, b2)); - assert_se(bitmap_set(b, 1) == 0); + ASSERT_EQ(bitmap_set(b, 1), 0); bitmap_clear(b); assert_se(bitmap_equal(b, b2)); - assert_se(bitmap_set(b, 0) == 0); - assert_se(bitmap_set(b2, 0) == 0); + ASSERT_EQ(bitmap_set(b, 0), 0); + ASSERT_EQ(bitmap_set(b2, 0), 0); assert_se(bitmap_equal(b, b2)); return 0; diff --git a/src/test/test-blockdev-util.c b/src/test/test-blockdev-util.c index 134386c..19626e0 100644 --- a/src/test/test-blockdev-util.c +++ b/src/test/test-blockdev-util.c @@ -1,7 +1,9 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "blockdev-util.h" +#include "device-util.h" #include "errno-util.h" +#include "fd-util.h" #include "tests.h" static void test_path_is_encrypted_one(const char *p, int expect) { @@ -38,4 +40,39 @@ TEST(path_is_encrypted) { test_path_is_encrypted_one("/dev", booted > 0 ? false : -1); } +TEST(partscan_enabled) { + + _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL; + int r; + + assert_se(sd_device_enumerator_new(&e) >= 0); + assert_se(sd_device_enumerator_allow_uninitialized(e) >= 0); + assert_se(sd_device_enumerator_add_match_subsystem(e, "block", /* match = */ true) >= 0); + + FOREACH_DEVICE(e, dev) { + _cleanup_close_ int fd = -EBADF; + const char *name; + + r = sd_device_get_devname(dev, &name); + if (r < 0) { + log_warning_errno(r, "Found block device without a name, skipping."); + continue; + } + + fd = sd_device_open(dev, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY); + if (fd < 0) { + log_warning_errno(fd, "Found block device '%s' which we cannot open, skipping: %m", name); + continue; + } + + r = blockdev_partscan_enabled(fd); + if (r < 0) { + log_warning_errno(r, "Failed to determine if block device '%s' has partition scanning enabled, skipping: %m", name); + continue; + } + + log_info("%s has partition scanning enabled: %s", name, yes_no(r)); + } +} + DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-boot-timestamps.c b/src/test/test-boot-timestamps.c index c3e4876..6771729 100644 --- a/src/test/test-boot-timestamps.c +++ b/src/test/test-boot-timestamps.c @@ -76,11 +76,11 @@ int main(int argc, char* argv[]) { test_setup_logging(LOG_DEBUG); p = test_acpi_fpdt(); - assert_se(p >= 0); + ASSERT_OK(p); q = test_efi_loader(); - assert_se(q >= 0); + ASSERT_OK(q); r = test_boot_timestamps(); - assert_se(r >= 0); + ASSERT_OK(r); if (p == 0 && q == 0 && r == 0) return log_tests_skipped("access to firmware variables not possible"); diff --git a/src/test/test-bootspec.c b/src/test/test-bootspec.c index 18611fc..88faa1e 100644 --- a/src/test/test-bootspec.c +++ b/src/test/test-bootspec.c @@ -63,7 +63,7 @@ TEST_RET(bootspec_sort) { _cleanup_(rm_rf_physical_and_freep) char *d = NULL; _cleanup_(boot_config_free) BootConfig config = BOOT_CONFIG_NULL; - assert_se(mkdtemp_malloc("/tmp/bootspec-testXXXXXX", &d) >= 0); + ASSERT_OK(mkdtemp_malloc("/tmp/bootspec-testXXXXXX", &d)); for (size_t i = 0; i < ELEMENTSOF(entries); i++) { _cleanup_free_ char *j = NULL; @@ -71,24 +71,24 @@ TEST_RET(bootspec_sort) { j = path_join(d, "/loader/entries/", entries[i].fname); assert_se(j); - assert_se(write_string_file(j, entries[i].contents, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_MKDIR_0755) >= 0); + ASSERT_OK(write_string_file(j, entries[i].contents, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_MKDIR_0755)); } - assert_se(boot_config_load(&config, d, NULL) >= 0); + ASSERT_OK(boot_config_load(&config, d, NULL)); assert_se(config.n_entries == 6); /* First, because has sort key, and its the lowest one */ - assert_se(streq(config.entries[0].id, "d.conf")); + ASSERT_STREQ(config.entries[0].id, "d.conf"); /* These two have a sort key, and newest must be first */ - assert_se(streq(config.entries[1].id, "cx.conf")); - assert_se(streq(config.entries[2].id, "c.conf")); + ASSERT_STREQ(config.entries[1].id, "cx.conf"); + ASSERT_STREQ(config.entries[2].id, "c.conf"); /* The following ones have no sort key, hence order by version compared ids, lowest first */ - assert_se(streq(config.entries[3].id, "b.conf")); - assert_se(streq(config.entries[4].id, "a-10.conf")); - assert_se(streq(config.entries[5].id, "a-5.conf")); + ASSERT_STREQ(config.entries[3].id, "b.conf"); + ASSERT_STREQ(config.entries[4].id, "a-10.conf"); + ASSERT_STREQ(config.entries[5].id, "a-5.conf"); return 0; } @@ -101,7 +101,7 @@ static void test_extract_tries_one(const char *fname, int ret, const char *strip if (ret < 0) return; - assert_se(streq_ptr(p, stripped)); + ASSERT_STREQ(p, stripped); assert_se(l == tries_left); assert_se(d == tries_done); } @@ -188,23 +188,22 @@ TEST_RET(bootspec_boot_config_find_entry) { assert_se(boot_config_load(&config, d, NULL) >= 0); assert_se(config.n_entries == 2); - // Test finding the first entry + /* Test finding the first entry */ BootEntry *entry = boot_config_find_entry(&config, "a-10.conf"); assert_se(entry && streq(entry->id, "a-10.conf")); - // Test finding the second entry + /* Test finding the second entry */ entry = boot_config_find_entry(&config, "a-05.conf"); assert_se(entry && streq(entry->id, "a-05.conf")); - // Test finding a non-existent entry + /* Test finding a non-existent entry */ entry = boot_config_find_entry(&config, "nonexistent.conf"); - assert_se(entry == NULL); + ASSERT_NULL(entry); - // Test case-insensitivity + /* Test case-insensitivity */ entry = boot_config_find_entry(&config, "A-10.CONF"); assert_se(entry && streq(entry->id, "a-10.conf")); - return 0; } diff --git a/src/test/test-bpf-devices.c b/src/test/test-bpf-devices.c index 4bd606e..f1db021 100644 --- a/src/test/test-bpf-devices.c +++ b/src/test/test-bpf-devices.c @@ -22,13 +22,13 @@ static void test_policy_closed(const char *cgroup_path, BPFProgram **installed_p log_info("/* %s */", __func__); r = bpf_devices_cgroup_init(&prog, CGROUP_DEVICE_POLICY_CLOSED, true); - assert_se(r >= 0); + ASSERT_OK(r); r = bpf_devices_allow_list_static(prog, cgroup_path); - assert_se(r >= 0); + ASSERT_OK(r); r = bpf_devices_apply_policy(&prog, CGROUP_DEVICE_POLICY_CLOSED, true, cgroup_path, installed_prog); - assert_se(r >= 0); + ASSERT_OK(r); FOREACH_STRING(s, "/dev/null", "/dev/zero", @@ -59,19 +59,19 @@ static void test_policy_strict(const char *cgroup_path, BPFProgram **installed_p log_info("/* %s */", __func__); r = bpf_devices_cgroup_init(&prog, CGROUP_DEVICE_POLICY_STRICT, true); - assert_se(r >= 0); + ASSERT_OK(r); r = bpf_devices_allow_list_device(prog, cgroup_path, "/dev/null", CGROUP_DEVICE_READ|CGROUP_DEVICE_WRITE); - assert_se(r >= 0); + ASSERT_OK(r); r = bpf_devices_allow_list_device(prog, cgroup_path, "/dev/random", CGROUP_DEVICE_READ); - assert_se(r >= 0); + ASSERT_OK(r); r = bpf_devices_allow_list_device(prog, cgroup_path, "/dev/zero", CGROUP_DEVICE_WRITE); - assert_se(r >= 0); + ASSERT_OK(r); r = bpf_devices_apply_policy(&prog, CGROUP_DEVICE_POLICY_STRICT, true, cgroup_path, installed_prog); - assert_se(r >= 0); + ASSERT_OK(r); { _cleanup_close_ int fd = -EBADF, fd2 = -EBADF; @@ -136,13 +136,13 @@ static void test_policy_allow_list_major(const char *pattern, const char *cgroup log_info("/* %s(%s) */", __func__, pattern); r = bpf_devices_cgroup_init(&prog, CGROUP_DEVICE_POLICY_STRICT, true); - assert_se(r >= 0); + ASSERT_OK(r); r = bpf_devices_allow_list_major(prog, cgroup_path, pattern, 'c', CGROUP_DEVICE_READ|CGROUP_DEVICE_WRITE); - assert_se(r >= 0); + ASSERT_OK(r); r = bpf_devices_apply_policy(&prog, CGROUP_DEVICE_POLICY_STRICT, true, cgroup_path, installed_prog); - assert_se(r >= 0); + ASSERT_OK(r); /* /dev/null, /dev/full have major==1, /dev/tty has major==5 */ { @@ -195,13 +195,13 @@ static void test_policy_allow_list_major_star(char type, const char *cgroup_path log_info("/* %s(type=%c) */", __func__, type); r = bpf_devices_cgroup_init(&prog, CGROUP_DEVICE_POLICY_STRICT, true); - assert_se(r >= 0); + ASSERT_OK(r); r = bpf_devices_allow_list_major(prog, cgroup_path, "*", type, CGROUP_DEVICE_READ|CGROUP_DEVICE_WRITE); - assert_se(r >= 0); + ASSERT_OK(r); r = bpf_devices_apply_policy(&prog, CGROUP_DEVICE_POLICY_STRICT, true, cgroup_path, installed_prog); - assert_se(r >= 0); + ASSERT_OK(r); { _cleanup_close_ int fd = -EBADF; @@ -226,7 +226,7 @@ static void test_policy_empty(bool add_mismatched, const char *cgroup_path, BPFP log_info("/* %s(add_mismatched=%s) */", __func__, yes_no(add_mismatched)); r = bpf_devices_cgroup_init(&prog, CGROUP_DEVICE_POLICY_STRICT, add_mismatched); - assert_se(r >= 0); + ASSERT_OK(r); if (add_mismatched) { r = bpf_devices_allow_list_major(prog, cgroup_path, "foobarxxx", 'c', CGROUP_DEVICE_READ|CGROUP_DEVICE_WRITE); @@ -234,7 +234,7 @@ static void test_policy_empty(bool add_mismatched, const char *cgroup_path, BPFP } r = bpf_devices_apply_policy(&prog, CGROUP_DEVICE_POLICY_STRICT, false, cgroup_path, installed_prog); - assert_se(r >= 0); + ASSERT_OK(r); { _cleanup_close_ int fd = -EBADF; @@ -258,7 +258,7 @@ int main(int argc, char *argv[]) { test_setup_logging(LOG_DEBUG); - assert_se(getrlimit(RLIMIT_MEMLOCK, &rl) >= 0); + ASSERT_OK(getrlimit(RLIMIT_MEMLOCK, &rl)); rl.rlim_cur = rl.rlim_max = MAX(rl.rlim_max, CAN_MEMLOCK_SIZE); (void) setrlimit(RLIMIT_MEMLOCK, &rl); @@ -278,10 +278,10 @@ int main(int argc, char *argv[]) { r = bpf_devices_supported(); if (r == 0) return log_tests_skipped("BPF device filter not supported"); - assert_se(r == 1); + ASSERT_EQ(r, 1); r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, cgroup, NULL, &controller_path); - assert_se(r >= 0); + ASSERT_OK(r); _cleanup_(bpf_program_freep) BPFProgram *prog = NULL; @@ -297,11 +297,11 @@ int main(int argc, char *argv[]) { test_policy_empty(false, cgroup, &prog); test_policy_empty(true, cgroup, &prog); - assert_se(path_extract_directory(cgroup, &parent) >= 0); + ASSERT_OK(path_extract_directory(cgroup, &parent)); - assert_se(cg_mask_supported(&supported) >= 0); + ASSERT_OK(cg_mask_supported(&supported)); r = cg_attach_everywhere(supported, parent, 0, NULL, NULL); - assert_se(r >= 0); + ASSERT_OK(r); return 0; } diff --git a/src/test/test-bpf-firewall.c b/src/test/test-bpf-firewall.c index c4175bc..cc67774 100644 --- a/src/test/test-bpf-firewall.c +++ b/src/test/test-bpf-firewall.c @@ -39,7 +39,7 @@ int main(int argc, char *argv[]) { if (detect_container() > 0) return log_tests_skipped("test-bpf-firewall fails inside LXC and Docker containers: https://github.com/systemd/systemd/issues/9666"); - assert_se(getrlimit(RLIMIT_MEMLOCK, &rl) >= 0); + ASSERT_OK(getrlimit(RLIMIT_MEMLOCK, &rl)); rl.rlim_cur = rl.rlim_max = MAX(rl.rlim_max, CAN_MEMLOCK_SIZE); (void) setrlimit(RLIMIT_MEMLOCK, &rl); @@ -50,21 +50,25 @@ int main(int argc, char *argv[]) { if (r == -ENOMEDIUM) return log_tests_skipped("cgroupfs not available"); + r = find_executable("ping", NULL); + if (r < 0) + return log_tests_skipped_errno(r, "Can't find ping binary: %m"); + _cleanup_free_ char *unit_dir = NULL; - assert_se(get_testdata_dir("units", &unit_dir) >= 0); - assert_se(set_unit_path(unit_dir) >= 0); + ASSERT_OK(get_testdata_dir("units", &unit_dir)); + ASSERT_OK(set_unit_path(unit_dir)); assert_se(runtime_dir = setup_fake_runtime_dir()); r = bpf_program_new(BPF_PROG_TYPE_CGROUP_SKB, "sd_trivial", &p); - assert_se(r == 0); + ASSERT_EQ(r, 0); r = bpf_program_add_instructions(p, exit_insn, ELEMENTSOF(exit_insn)); - assert_se(r == 0); + ASSERT_EQ(r, 0); r = bpf_firewall_supported(); if (r == BPF_FIREWALL_UNSUPPORTED) return log_tests_skipped("BPF firewalling not supported"); - assert_se(r > 0); + ASSERT_GT(r, 0); if (r == BPF_FIREWALL_SUPPORTED_WITH_MULTI) { log_notice("BPF firewalling with BPF_F_ALLOW_MULTI supported. Yay!"); @@ -73,7 +77,7 @@ int main(int argc, char *argv[]) { log_notice("BPF firewalling (though without BPF_F_ALLOW_MULTI) supported. Good."); r = bpf_program_load_kernel(p, log_buf, ELEMENTSOF(log_buf)); - assert_se(r >= 0); + ASSERT_OK(r); if (test_custom_filter) { zero(attr); @@ -94,29 +98,29 @@ int main(int argc, char *argv[]) { /* The simple tests succeeded. Now let's try full unit-based use-case. */ - assert_se(manager_new(RUNTIME_SCOPE_USER, MANAGER_TEST_RUN_BASIC, &m) >= 0); - assert_se(manager_startup(m, NULL, NULL, NULL) >= 0); + ASSERT_OK(manager_new(RUNTIME_SCOPE_USER, MANAGER_TEST_RUN_BASIC, &m)); + ASSERT_OK(manager_startup(m, NULL, NULL, NULL)); assert_se(u = unit_new(m, sizeof(Service))); - assert_se(unit_add_name(u, "foo.service") == 0); + ASSERT_EQ(unit_add_name(u, "foo.service"), 0); assert_se(cc = unit_get_cgroup_context(u)); u->perpetual = true; cc->ip_accounting = true; - assert_se(config_parse_in_addr_prefixes(u->id, "filename", 1, "Service", 1, "IPAddressAllow", 0, "10.0.1.0/24", &cc->ip_address_allow, NULL) == 0); - assert_se(config_parse_in_addr_prefixes(u->id, "filename", 1, "Service", 1, "IPAddressAllow", 0, "127.0.0.2", &cc->ip_address_allow, NULL) == 0); - assert_se(config_parse_in_addr_prefixes(u->id, "filename", 1, "Service", 1, "IPAddressDeny", 0, "127.0.0.3", &cc->ip_address_deny, NULL) == 0); - assert_se(config_parse_in_addr_prefixes(u->id, "filename", 1, "Service", 1, "IPAddressDeny", 0, "10.0.3.2/24", &cc->ip_address_deny, NULL) == 0); - assert_se(config_parse_in_addr_prefixes(u->id, "filename", 1, "Service", 1, "IPAddressDeny", 0, "127.0.0.1/25", &cc->ip_address_deny, NULL) == 0); - assert_se(config_parse_in_addr_prefixes(u->id, "filename", 1, "Service", 1, "IPAddressDeny", 0, "127.0.0.4", &cc->ip_address_deny, NULL) == 0); + ASSERT_EQ(config_parse_in_addr_prefixes(u->id, "filename", 1, "Service", 1, "IPAddressAllow", 0, "10.0.1.0/24", &cc->ip_address_allow, NULL), 0); + ASSERT_EQ(config_parse_in_addr_prefixes(u->id, "filename", 1, "Service", 1, "IPAddressAllow", 0, "127.0.0.2", &cc->ip_address_allow, NULL), 0); + ASSERT_EQ(config_parse_in_addr_prefixes(u->id, "filename", 1, "Service", 1, "IPAddressDeny", 0, "127.0.0.3", &cc->ip_address_deny, NULL), 0); + ASSERT_EQ(config_parse_in_addr_prefixes(u->id, "filename", 1, "Service", 1, "IPAddressDeny", 0, "10.0.3.2/24", &cc->ip_address_deny, NULL), 0); + ASSERT_EQ(config_parse_in_addr_prefixes(u->id, "filename", 1, "Service", 1, "IPAddressDeny", 0, "127.0.0.1/25", &cc->ip_address_deny, NULL), 0); + ASSERT_EQ(config_parse_in_addr_prefixes(u->id, "filename", 1, "Service", 1, "IPAddressDeny", 0, "127.0.0.4", &cc->ip_address_deny, NULL), 0); assert_se(set_size(cc->ip_address_allow) == 2); assert_se(set_size(cc->ip_address_deny) == 4); /* The deny list is defined redundantly, let's ensure it will be properly reduced */ - assert_se(in_addr_prefixes_reduce(cc->ip_address_allow) >= 0); - assert_se(in_addr_prefixes_reduce(cc->ip_address_deny) >= 0); + ASSERT_OK(in_addr_prefixes_reduce(cc->ip_address_allow)); + ASSERT_OK(in_addr_prefixes_reduce(cc->ip_address_deny)); assert_se(set_size(cc->ip_address_allow) == 2); assert_se(set_size(cc->ip_address_deny) == 2); @@ -155,28 +159,29 @@ int main(int argc, char *argv[]) { return log_tests_skipped("Kernel doesn't support the necessary bpf bits (masked out via seccomp?)"); assert_se(r >= 0); - assert_se(u->ip_bpf_ingress); - assert_se(u->ip_bpf_egress); + CGroupRuntime *crt = ASSERT_PTR(unit_get_cgroup_runtime(u)); + assert_se(crt->ip_bpf_ingress); + assert_se(crt->ip_bpf_egress); - r = bpf_program_load_kernel(u->ip_bpf_ingress, log_buf, ELEMENTSOF(log_buf)); + r = bpf_program_load_kernel(crt->ip_bpf_ingress, log_buf, ELEMENTSOF(log_buf)); log_notice("log:"); log_notice("-------"); log_notice("%s", log_buf); log_notice("-------"); - assert_se(r >= 0); + ASSERT_OK(r); - r = bpf_program_load_kernel(u->ip_bpf_egress, log_buf, ELEMENTSOF(log_buf)); + r = bpf_program_load_kernel(crt->ip_bpf_egress, log_buf, ELEMENTSOF(log_buf)); log_notice("log:"); log_notice("-------"); log_notice("%s", log_buf); log_notice("-------"); - assert_se(r >= 0); + ASSERT_OK(r); - assert_se(unit_start(u, NULL) >= 0); + ASSERT_OK(unit_start(u, NULL)); while (!IN_SET(SERVICE(u)->state, SERVICE_DEAD, SERVICE_FAILED)) assert_se(sd_event_run(m->event, UINT64_MAX) >= 0); @@ -201,7 +206,7 @@ int main(int argc, char *argv[]) { SERVICE(u)->type = SERVICE_ONESHOT; u->load_state = UNIT_LOADED; - assert_se(unit_start(u, NULL) >= 0); + ASSERT_OK(unit_start(u, NULL)); while (!IN_SET(SERVICE(u)->state, SERVICE_DEAD, SERVICE_FAILED)) assert_se(sd_event_run(m->event, UINT64_MAX) >= 0); diff --git a/src/test/test-bpf-foreign-programs.c b/src/test/test-bpf-foreign-programs.c index 35c7e0d..34ccb74 100644 --- a/src/test/test-bpf-foreign-programs.c +++ b/src/test/test-bpf-foreign-programs.c @@ -253,7 +253,7 @@ static int test_bpf_cgroup_programs(Manager *m, const char *unit_name, const Tes while (!IN_SET(SERVICE(u)->state, SERVICE_DEAD, SERVICE_FAILED)) { r = sd_event_run(m->event, UINT64_MAX); if (r < 0) - return log_error_errno(errno, "Event run failed %m"); + return log_error_errno(r, "Event run failed %m"); } cld_code = SERVICE(u)->exec_command[SERVICE_EXEC_START]->exec_status.code; @@ -282,7 +282,7 @@ int main(int argc, char *argv[]) { if (getuid() != 0) return log_tests_skipped("not running as root"); - assert_se(getrlimit(RLIMIT_MEMLOCK, &rl) >= 0); + ASSERT_OK(getrlimit(RLIMIT_MEMLOCK, &rl)); rl.rlim_cur = rl.rlim_max = MAX(rl.rlim_max, CAN_MEMLOCK_SIZE); (void) setrlimit_closest(RLIMIT_MEMLOCK, &rl); @@ -297,34 +297,34 @@ int main(int argc, char *argv[]) { if (r == -ENOMEDIUM) return log_tests_skipped("cgroupfs not available"); - assert_se(get_testdata_dir("units", &unit_dir) >= 0); - assert_se(set_unit_path(unit_dir) >= 0); + ASSERT_OK(get_testdata_dir("units", &unit_dir)); + ASSERT_OK(set_unit_path(unit_dir)); assert_se(runtime_dir = setup_fake_runtime_dir()); - assert_se(manager_new(RUNTIME_SCOPE_USER, MANAGER_TEST_RUN_BASIC, &m) >= 0); - assert_se(manager_startup(m, NULL, NULL, NULL) >= 0); + ASSERT_OK(manager_new(RUNTIME_SCOPE_USER, MANAGER_TEST_RUN_BASIC, &m)); + ASSERT_OK(manager_startup(m, NULL, NULL, NULL)); - assert_se(test_bpf_cgroup_programs(m, - "single_prog.service", single_prog, ELEMENTSOF(single_prog)) >= 0); - assert_se(test_bpf_cgroup_programs(m, + ASSERT_OK(test_bpf_cgroup_programs(m, + "single_prog.service", single_prog, ELEMENTSOF(single_prog))); + ASSERT_OK(test_bpf_cgroup_programs(m, "multi_prog_same_hook.service", - multi_prog_same_hook, ELEMENTSOF(multi_prog_same_hook)) >= 0); - assert_se(test_bpf_cgroup_programs(m, + multi_prog_same_hook, ELEMENTSOF(multi_prog_same_hook))); + ASSERT_OK(test_bpf_cgroup_programs(m, "same_prog_multi_hook.service", - same_prog_multi_hook, ELEMENTSOF(same_prog_multi_hook)) >= 0); - assert_se(test_bpf_cgroup_programs(m, + same_prog_multi_hook, ELEMENTSOF(same_prog_multi_hook))); + ASSERT_OK(test_bpf_cgroup_programs(m, "same_prog_multi_option_0.service", - same_prog_multi_option_0, ELEMENTSOF(same_prog_multi_option_0)) >= 0); - assert_se(test_bpf_cgroup_programs(m, + same_prog_multi_option_0, ELEMENTSOF(same_prog_multi_option_0))); + ASSERT_OK(test_bpf_cgroup_programs(m, "same_prog_multi_option_1.service", - same_prog_multi_option_1, ELEMENTSOF(same_prog_multi_option_1)) >= 0); - assert_se(test_bpf_cgroup_programs(m, + same_prog_multi_option_1, ELEMENTSOF(same_prog_multi_option_1))); + ASSERT_OK(test_bpf_cgroup_programs(m, "same_prog_same_hook.service", same_prog_same_hook, - ELEMENTSOF(same_prog_same_hook)) >= 0); - assert_se(test_bpf_cgroup_programs(m, + ELEMENTSOF(same_prog_same_hook))); + ASSERT_OK(test_bpf_cgroup_programs(m, "path_split_test.service", path_split_test, - ELEMENTSOF(path_split_test)) >= 0); + ELEMENTSOF(path_split_test))); return 0; } diff --git a/src/test/test-bpf-lsm.c b/src/test/test-bpf-restrict-fs.c index 42ea64c..7ece337 100644 --- a/src/test/test-bpf-lsm.c +++ b/src/test/test-bpf-restrict-fs.c @@ -1,6 +1,6 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ -#include "bpf-lsm.h" +#include "bpf-restrict-fs.h" #include "load-fragment.h" #include "manager.h" #include "process-util.h" @@ -46,7 +46,7 @@ static int test_restrict_filesystems(Manager *m, const char *unit_name, const ch while (!IN_SET(SERVICE(u)->state, SERVICE_DEAD, SERVICE_FAILED)) { r = sd_event_run(m->event, UINT64_MAX); if (r < 0) - return log_error_errno(errno, "Event run failed %m"); + return log_error_errno(r, "Event run failed %m"); } cld_code = SERVICE(u)->exec_command[SERVICE_EXEC_START]->exec_status.code; @@ -68,35 +68,35 @@ int main(int argc, char *argv[]) { test_setup_logging(LOG_DEBUG); - assert_se(getrlimit(RLIMIT_MEMLOCK, &rl) >= 0); + ASSERT_OK(getrlimit(RLIMIT_MEMLOCK, &rl)); rl.rlim_cur = rl.rlim_max = MAX(rl.rlim_max, CAN_MEMLOCK_SIZE); (void) setrlimit_closest(RLIMIT_MEMLOCK, &rl); if (!can_memlock()) return log_tests_skipped("Can't use mlock()"); - if (!lsm_bpf_supported(/* initialize = */ true)) + if (!bpf_restrict_fs_supported(/* initialize = */ true)) return log_tests_skipped("LSM BPF hooks are not supported"); r = enter_cgroup_subroot(NULL); if (r == -ENOMEDIUM) return log_tests_skipped("cgroupfs not available"); - assert_se(get_testdata_dir("units", &unit_dir) >= 0); - assert_se(set_unit_path(unit_dir) >= 0); + ASSERT_OK(get_testdata_dir("units", &unit_dir)); + ASSERT_OK(set_unit_path(unit_dir)); assert_se(runtime_dir = setup_fake_runtime_dir()); - assert_se(manager_new(RUNTIME_SCOPE_SYSTEM, MANAGER_TEST_RUN_BASIC, &m) >= 0); - assert_se(manager_startup(m, NULL, NULL, NULL) >= 0); + ASSERT_OK(manager_new(RUNTIME_SCOPE_SYSTEM, MANAGER_TEST_RUN_BASIC, &m)); + ASSERT_OK(manager_startup(m, NULL, NULL, NULL)); /* We need to enable access to the filesystem where the binary is so we - * add @common-block */ - assert_se(test_restrict_filesystems(m, "restrict_filesystems_test.service", "/sys/kernel/tracing/printk_formats", STRV_MAKE("@common-block")) < 0); - assert_se(test_restrict_filesystems(m, "restrict_filesystems_test.service", "/sys/kernel/tracing/printk_formats", STRV_MAKE("tracefs", "@common-block")) >= 0); - assert_se(test_restrict_filesystems(m, "restrict_filesystems_test.service", "/sys/kernel/tracing/printk_formats", STRV_MAKE("tracefs", "@common-block", "~tracefs")) < 0); - assert_se(test_restrict_filesystems(m, "restrict_filesystems_test.service", "/sys/kernel/debug/sleep_time", STRV_MAKE("@common-block")) < 0); - assert_se(test_restrict_filesystems(m, "restrict_filesystems_test.service", "/sys/kernel/debug/sleep_time", STRV_MAKE("debugfs", "@common-block")) >= 0); - assert_se(test_restrict_filesystems(m, "restrict_filesystems_test.service", "/sys/kernel/debug/sleep_time", STRV_MAKE("~debugfs")) < 0); + * add @common-block and @application */ + ASSERT_LT(test_restrict_filesystems(m, "restrict_filesystems_test.service", "/sys/kernel/tracing/printk_formats", STRV_MAKE("@common-block", "@application")), 0); + ASSERT_OK(test_restrict_filesystems(m, "restrict_filesystems_test.service", "/sys/kernel/tracing/printk_formats", STRV_MAKE("tracefs", "@common-block", "@application"))); + ASSERT_LT(test_restrict_filesystems(m, "restrict_filesystems_test.service", "/sys/kernel/tracing/printk_formats", STRV_MAKE("tracefs", "@common-block", "@application", "~tracefs")), 0); + ASSERT_LT(test_restrict_filesystems(m, "restrict_filesystems_test.service", "/sys/kernel/debug/sleep_time", STRV_MAKE("@common-block", "@application")), 0); + ASSERT_OK(test_restrict_filesystems(m, "restrict_filesystems_test.service", "/sys/kernel/debug/sleep_time", STRV_MAKE("debugfs", "@common-block", "@application"))); + ASSERT_LT(test_restrict_filesystems(m, "restrict_filesystems_test.service", "/sys/kernel/debug/sleep_time", STRV_MAKE("~debugfs")), 0); return 0; } diff --git a/src/test/test-build-path.c b/src/test/test-build-path.c new file mode 100644 index 0000000..661b5fc --- /dev/null +++ b/src/test/test-build-path.c @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include "build-path.h" +#include "log.h" +#include "string-util.h" + +int main(int argc, char* argv[]) { + _cleanup_free_ char *p = NULL; + int r; + + r = get_build_exec_dir(&p); + if (r == -ENOEXEC) + log_info("Not run from build dir."); + else if (r < 0) + log_error_errno(r, "Failed to find build dir: %m"); + else + log_info("%s", strna(p)); + + return 0; +} diff --git a/src/test/test-bus-util.c b/src/test/test-bus-util.c index 2f52bca..2cf44d6 100644 --- a/src/test/test-bus-util.c +++ b/src/test/test-bus-util.c @@ -11,7 +11,7 @@ static int callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) static void destroy_callback(void *userdata) { int *n_called = userdata; - (*n_called) ++; + (*n_called)++; } TEST(destroy_callback) { diff --git a/src/test/test-calendarspec.c b/src/test/test-calendarspec.c index 18a0f8f..7cda114 100644 --- a/src/test/test-calendarspec.c +++ b/src/test/test-calendarspec.c @@ -16,24 +16,24 @@ static void _test_one(int line, const char *input, const char *output) { r = calendar_spec_from_string(input, &c); if (r < 0) log_error_errno(r, "Failed to parse \"%s\": %m", input); - assert_se(r >= 0); + ASSERT_OK(r); - assert_se(calendar_spec_to_string(c, &p) >= 0); + ASSERT_OK(calendar_spec_to_string(c, &p)); log_info("line %d: \"%s\" → \"%s\"%s%s", line, input, p, !streq(p, output) ? " expected:" : "", !streq(p, output) ? output : ""); - assert_se(streq(p, output)); + ASSERT_STREQ(p, output); u = now(CLOCK_REALTIME); r = calendar_spec_next_usec(c, u, &u); log_info("Next: %s", r < 0 ? STRERROR(r) : FORMAT_TIMESTAMP(u)); c = calendar_spec_free(c); - assert_se(calendar_spec_from_string(p, &c) >= 0); - assert_se(calendar_spec_to_string(c, &q) >= 0); + ASSERT_OK(calendar_spec_from_string(p, &c)); + ASSERT_OK(calendar_spec_to_string(c, &q)); - assert_se(streq(q, p)); + ASSERT_STREQ(q, p); } #define test_one(input, output) _test_one(__LINE__, input, output) @@ -53,7 +53,7 @@ static void _test_next(int line, const char *input, const char *new_tz, usec_t a assert_se(set_unset_env("TZ", new_tz, true) == 0); tzset(); - assert_se(calendar_spec_from_string(input, &c) >= 0); + ASSERT_OK(calendar_spec_from_string(input, &c)); log_info("line %d: \"%s\" new_tz=%s", line, input, strnull(new_tz)); @@ -82,11 +82,11 @@ TEST(timestamp) { assert_se(format_timestamp_style(buf, sizeof buf, x, TIMESTAMP_US)); log_info("%s", buf); - assert_se(calendar_spec_from_string(buf, &c) >= 0); - assert_se(calendar_spec_to_string(c, &t) >= 0); + ASSERT_OK(calendar_spec_from_string(buf, &c)); + ASSERT_OK(calendar_spec_to_string(c, &t)); log_info("%s", t); - assert_se(parse_timestamp(t, &y) >= 0); + ASSERT_OK(parse_timestamp(t, &y)); assert_se(y == x); } @@ -95,9 +95,9 @@ TEST(hourly_bug_4031) { usec_t n, u, w; int r; - assert_se(calendar_spec_from_string("hourly", &c) >= 0); + ASSERT_OK(calendar_spec_from_string("hourly", &c)); n = now(CLOCK_REALTIME); - assert_se((r = calendar_spec_next_usec(c, n, &u)) >= 0); + ASSERT_OK((r = calendar_spec_next_usec(c, n, &u))); log_info("Now: %s (%"PRIu64")", FORMAT_TIMESTAMP_STYLE(n, TIMESTAMP_US), n); log_info("Next hourly: %s (%"PRIu64")", r < 0 ? STRERROR(r) : FORMAT_TIMESTAMP_STYLE(u, TIMESTAMP_US), u); @@ -256,7 +256,7 @@ TEST(calendar_spec_from_string) { static int intro(void) { /* Tests have hard-coded results that do not expect a specific timezone to be set by the caller */ - assert_se(unsetenv("TZ") >= 0); + ASSERT_OK(unsetenv("TZ")); return EXIT_SUCCESS; } diff --git a/src/test/test-cap-list.c b/src/test/test-cap-list.c index a9cbf69..49be4a2 100644 --- a/src/test/test-cap-list.c +++ b/src/test/test-cap-list.c @@ -21,7 +21,7 @@ TEST(cap_list) { assert_se(!CAPABILITY_TO_STRING(-1)); if (capability_list_length() <= 62) - assert_se(streq(CAPABILITY_TO_STRING(62), "0x3e")); + ASSERT_STREQ(CAPABILITY_TO_STRING(62), "0x3e"); assert_se(!CAPABILITY_TO_STRING(64)); for (int i = 0; i < capability_list_length(); i++) { @@ -31,7 +31,7 @@ TEST(cap_list) { assert_se(capability_from_name(n) == i); printf("%s = %i\n", n, i); - assert_se(streq(CAPABILITY_TO_STRING(i), n)); + ASSERT_STREQ(CAPABILITY_TO_STRING(i), n); } assert_se(capability_from_name("asdfbsd") == -EINVAL); @@ -70,7 +70,7 @@ static void test_capability_set_one(uint64_t c, const char *t) { uint64_t c1, c_masked = c & all_capabilities(); assert_se(capability_set_to_string(c, &t1) == 0); - assert_se(streq(t1, t)); + ASSERT_STREQ(t1, t); assert_se(capability_set_from_string(t1, &c1) > 0); assert_se(c1 == c_masked); @@ -160,8 +160,8 @@ TEST(capability_set_to_string_negative) { uint64_t m = random_u64() % (UINT64_C(1) << (cap_last_cap() + 1)); - assert_se(capability_set_to_string(m, &a) >= 0); - assert_se(capability_set_to_string_negative(m, &b) >= 0); + ASSERT_OK(capability_set_to_string(m, &a)); + ASSERT_OK(capability_set_to_string_negative(m, &b)); printf("%s (%zu) → ", a, strlen(a)); @@ -170,7 +170,7 @@ TEST(capability_set_to_string_negative) { else printf("%s (%zu)\n", b, strlen(b)); - assert_se(strlen(b) <= strlen(a)); + ASSERT_LE(strlen(b), strlen(a)); } } diff --git a/src/test/test-capability.c b/src/test/test-capability.c index e8a0569..34f3a91 100644 --- a/src/test/test-capability.c +++ b/src/test/test-capability.c @@ -41,12 +41,12 @@ static void test_last_cap_file(void) { r = read_one_line_file("/proc/sys/kernel/cap_last_cap", &content); if (r == -ENOENT || ERRNO_IS_NEG_PRIVILEGE(r)) /* kernel pre 3.2 or no access */ return; - assert_se(r >= 0); + ASSERT_OK(r); r = safe_atolu(content, &val); - assert_se(r >= 0); + ASSERT_OK(r); assert_se(val != 0); - assert_se(val == cap_last_cap()); + ASSERT_EQ(val, cap_last_cap()); } /* verify cap_last_cap() against syscall probing */ @@ -54,7 +54,7 @@ static void test_last_cap_probe(void) { unsigned long p = (unsigned long)CAP_LAST_CAP; if (prctl(PR_CAPBSET_READ, p) < 0) { - for (p--; p > 0; p --) + for (p--; p > 0; p--) if (prctl(PR_CAPBSET_READ, p) >= 0) break; } else { @@ -64,7 +64,7 @@ static void test_last_cap_probe(void) { } assert_se(p != 0); - assert_se(p == cap_last_cap()); + ASSERT_EQ(p, cap_last_cap()); } static void fork_test(void (*test_func)(void)) { @@ -104,7 +104,7 @@ static int setup_tests(bool *run_ambient) { nobody = getpwnam(NOBODY_USER_NAME); if (!nobody) - return log_warning_errno(SYNTHETIC_ERRNO(ENOENT), "Couldn't find 'nobody' user: %m"); + return log_warning_errno(SYNTHETIC_ERRNO(ENOENT), "Couldn't find 'nobody' user."); test_uid = nobody->pw_uid; test_gid = nobody->pw_gid; @@ -130,7 +130,7 @@ static void test_drop_privileges_keep_net_raw(void) { show_capabilities(); sock = socket(AF_INET, SOCK_RAW, IPPROTO_UDP); - assert_se(sock >= 0); + ASSERT_OK(sock); safe_close(sock); } @@ -138,7 +138,7 @@ static void test_drop_privileges_dontkeep_net_raw(void) { int sock; sock = socket(AF_INET, SOCK_RAW, IPPROTO_UDP); - assert_se(sock >= 0); + ASSERT_OK(sock); safe_close(sock); assert_se(drop_privileges(test_uid, test_gid, test_flags) >= 0); @@ -147,7 +147,7 @@ static void test_drop_privileges_dontkeep_net_raw(void) { show_capabilities(); sock = socket(AF_INET, SOCK_RAW, IPPROTO_UDP); - assert_se(sock < 0); + ASSERT_LT(sock, 0); } static void test_drop_privileges_fail(void) { @@ -155,8 +155,8 @@ static void test_drop_privileges_fail(void) { assert_se(getuid() == test_uid); assert_se(getgid() == test_gid); - assert_se(drop_privileges(test_uid, test_gid, test_flags) < 0); - assert_se(drop_privileges(0, 0, test_flags) < 0); + ASSERT_LT(drop_privileges(test_uid, test_gid, test_flags), 0); + ASSERT_LT(drop_privileges(0, 0, test_flags), 0); } static void test_drop_privileges(void) { @@ -172,14 +172,14 @@ static void test_drop_privileges(void) { } static void test_have_effective_cap(void) { - assert_se(have_effective_cap(CAP_KILL) > 0); - assert_se(have_effective_cap(CAP_CHOWN) > 0); + ASSERT_GT(have_effective_cap(CAP_KILL), 0); + ASSERT_GT(have_effective_cap(CAP_CHOWN), 0); - assert_se(drop_privileges(test_uid, test_gid, test_flags | (1ULL << CAP_KILL)) >= 0); + ASSERT_OK(drop_privileges(test_uid, test_gid, test_flags | (1ULL << CAP_KILL))); assert_se(getuid() == test_uid); assert_se(getgid() == test_gid); - assert_se(have_effective_cap(CAP_KILL) > 0); + ASSERT_GT(have_effective_cap(CAP_KILL), 0); assert_se(have_effective_cap(CAP_CHOWN) == 0); } @@ -237,9 +237,9 @@ static void test_ensure_cap_64_bit(void) { r = read_one_line_file("/proc/sys/kernel/cap_last_cap", &content); if (r == -ENOENT || ERRNO_IS_NEG_PRIVILEGE(r)) /* kernel pre 3.2 or no access */ return; - assert_se(r >= 0); + ASSERT_OK(r); - assert_se(safe_atolu(content, &p) >= 0); + ASSERT_OK(safe_atolu(content, &p)); /* If caps don't fit into 64-bit anymore, we have a problem, fail the test. */ assert_se(p <= 63); @@ -252,10 +252,10 @@ static void test_capability_get_ambient(void) { uint64_t c; int r; - assert_se(capability_get_ambient(&c) >= 0); + ASSERT_OK(capability_get_ambient(&c)); r = safe_fork("(getambient)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM|FORK_WAIT|FORK_LOG, NULL); - assert_se(r >= 0); + ASSERT_OK(r); if (r == 0) { int x, y; diff --git a/src/test/test-cgroup-mask.c b/src/test/test-cgroup-mask.c index bfc8fac..857102f 100644 --- a/src/test/test-cgroup-mask.c +++ b/src/test/test-cgroup-mask.c @@ -20,9 +20,9 @@ static void log_cgroup_mask(CGroupMask got, CGroupMask expected) { _cleanup_free_ char *e_store = NULL, *g_store = NULL; - assert_se(cg_mask_to_string(expected, &e_store) >= 0); + ASSERT_OK(cg_mask_to_string(expected, &e_store)); log_info("Expected mask: %s", e_store); - assert_se(cg_mask_to_string(got, &g_store) >= 0); + ASSERT_OK(cg_mask_to_string(got, &g_store)); log_info("Got mask: %s", g_store); } @@ -39,8 +39,8 @@ TEST_RET(cgroup_mask, .sd_booted = true) { /* Prepare the manager. */ _cleanup_free_ char *unit_dir = NULL; - assert_se(get_testdata_dir("units", &unit_dir) >= 0); - assert_se(set_unit_path(unit_dir) >= 0); + ASSERT_OK(get_testdata_dir("units", &unit_dir)); + ASSERT_OK(set_unit_path(unit_dir)); assert_se(runtime_dir = setup_fake_runtime_dir()); r = manager_new(RUNTIME_SCOPE_USER, MANAGER_TEST_RUN_BASIC, &m); if (IN_SET(r, -EPERM, -EACCES)) { @@ -63,13 +63,13 @@ TEST_RET(cgroup_mask, .sd_booted = true) { assert_se(manager_startup(m, NULL, NULL, NULL) >= 0); /* Load units and verify hierarchy. */ - assert_se(manager_load_startable_unit_or_warn(m, "parent.slice", NULL, &parent) >= 0); - assert_se(manager_load_startable_unit_or_warn(m, "son.service", NULL, &son) >= 0); - assert_se(manager_load_startable_unit_or_warn(m, "daughter.service", NULL, &daughter) >= 0); - assert_se(manager_load_startable_unit_or_warn(m, "grandchild.service", NULL, &grandchild) >= 0); - assert_se(manager_load_startable_unit_or_warn(m, "parent-deep.slice", NULL, &parent_deep) >= 0); - assert_se(manager_load_startable_unit_or_warn(m, "nomem.slice", NULL, &nomem_parent) >= 0); - assert_se(manager_load_startable_unit_or_warn(m, "nomemleaf.service", NULL, &nomem_leaf) >= 0); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "parent.slice", NULL, &parent)); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "son.service", NULL, &son)); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "daughter.service", NULL, &daughter)); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "grandchild.service", NULL, &grandchild)); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "parent-deep.slice", NULL, &parent_deep)); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "nomem.slice", NULL, &nomem_parent)); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "nomemleaf.service", NULL, &nomem_leaf)); assert_se(UNIT_GET_SLICE(son) == parent); assert_se(UNIT_GET_SLICE(daughter) == parent); assert_se(UNIT_GET_SLICE(parent_deep) == parent); @@ -135,7 +135,7 @@ static void test_cg_mask_to_string_one(CGroupMask mask, const char *t) { _cleanup_free_ char *b = NULL; assert_se(cg_mask_to_string(mask, &b) >= 0); - assert_se(streq_ptr(b, t)); + ASSERT_STREQ(b, t); } TEST(cg_mask_to_string) { @@ -157,7 +157,7 @@ TEST(cg_mask_to_string) { } static void cgroup_device_permissions_test_normalize(const char *a, const char *b) { - assert_se(streq_ptr(cgroup_device_permissions_to_string(cgroup_device_permissions_from_string(a)), b)); + ASSERT_STREQ(cgroup_device_permissions_to_string(cgroup_device_permissions_from_string(a)), b); } TEST(cgroup_device_permissions) { diff --git a/src/test/test-cgroup-setup.c b/src/test/test-cgroup-setup.c index e669e9b..8b5d02d 100644 --- a/src/test/test-cgroup-setup.c +++ b/src/test/test-cgroup-setup.c @@ -14,12 +14,10 @@ static void test_is_wanted_print_one(bool header) { _cleanup_free_ char *cmdline = NULL; log_info("-- %s --", __func__); - assert_se(proc_cmdline(&cmdline) >= 0); + ASSERT_OK(proc_cmdline(&cmdline)); log_info("cmdline: %s", cmdline); - if (header) { - log_info("default-hierarchy=" DEFAULT_HIERARCHY_NAME); + if (header) (void) system("findmnt -n /sys/fs/cgroup"); - } log_info("is_unified_wanted() → %s", yes_no(cg_is_unified_wanted())); log_info("is_hybrid_wanted() → %s", yes_no(cg_is_hybrid_wanted())); @@ -33,33 +31,33 @@ TEST(is_wanted_print) { } TEST(is_wanted) { - assert_se(setenv("SYSTEMD_PROC_CMDLINE", - "systemd.unified_cgroup_hierarchy", 1) >= 0); + ASSERT_OK(setenv("SYSTEMD_PROC_CMDLINE", + "systemd.unified_cgroup_hierarchy", 1)); test_is_wanted_print_one(false); - assert_se(setenv("SYSTEMD_PROC_CMDLINE", - "systemd.unified_cgroup_hierarchy=0", 1) >= 0); + ASSERT_OK(setenv("SYSTEMD_PROC_CMDLINE", + "systemd.unified_cgroup_hierarchy=0", 1)); test_is_wanted_print_one(false); - assert_se(setenv("SYSTEMD_PROC_CMDLINE", + ASSERT_OK(setenv("SYSTEMD_PROC_CMDLINE", "systemd.unified_cgroup_hierarchy=0 " - "systemd.legacy_systemd_cgroup_controller", 1) >= 0); + "systemd.legacy_systemd_cgroup_controller", 1)); test_is_wanted_print_one(false); - assert_se(setenv("SYSTEMD_PROC_CMDLINE", + ASSERT_OK(setenv("SYSTEMD_PROC_CMDLINE", "systemd.unified_cgroup_hierarchy=0 " - "systemd.legacy_systemd_cgroup_controller=0", 1) >= 0); + "systemd.legacy_systemd_cgroup_controller=0", 1)); test_is_wanted_print_one(false); /* cgroup_no_v1=all implies unified cgroup hierarchy, unless otherwise * explicitly specified. */ - assert_se(setenv("SYSTEMD_PROC_CMDLINE", - "cgroup_no_v1=all", 1) >= 0); + ASSERT_OK(setenv("SYSTEMD_PROC_CMDLINE", + "cgroup_no_v1=all", 1)); test_is_wanted_print_one(false); - assert_se(setenv("SYSTEMD_PROC_CMDLINE", + ASSERT_OK(setenv("SYSTEMD_PROC_CMDLINE", "cgroup_no_v1=all " - "systemd.unified_cgroup_hierarchy=0", 1) >= 0); + "systemd.unified_cgroup_hierarchy=0", 1)); test_is_wanted_print_one(false); } diff --git a/src/test/test-cgroup-unit-default.c b/src/test/test-cgroup-unit-default.c index 62618ce..97101d4 100644 --- a/src/test/test-cgroup-unit-default.c +++ b/src/test/test-cgroup-unit-default.c @@ -23,8 +23,8 @@ TEST_RET(default_memory_low, .sd_booted = true) { return log_tests_skipped("cgroupfs not available"); _cleanup_free_ char *unit_dir = NULL; - assert_se(get_testdata_dir("units", &unit_dir) >= 0); - assert_se(set_unit_path(unit_dir) >= 0); + ASSERT_OK(get_testdata_dir("units", &unit_dir)); + ASSERT_OK(set_unit_path(unit_dir)); assert_se(runtime_dir = setup_fake_runtime_dir()); r = manager_new(RUNTIME_SCOPE_USER, MANAGER_TEST_RUN_BASIC, &m); if (IN_SET(r, -EPERM, -EACCES)) { @@ -32,8 +32,8 @@ TEST_RET(default_memory_low, .sd_booted = true) { return log_tests_skipped("cannot create manager"); } - assert_se(r >= 0); - assert_se(manager_startup(m, NULL, NULL, NULL) >= 0); + ASSERT_OK(r); + ASSERT_OK(manager_startup(m, NULL, NULL, NULL)); /* dml.slice has DefaultMemoryLow=50. Beyond that, individual subhierarchies look like this: * @@ -88,27 +88,27 @@ TEST_RET(default_memory_low, .sd_booted = true) { * │ dml-discard-empty.service │ │ dml-discard-set-ml.service │ * └───────────────────────────┘ └────────────────────────────┘ */ - assert_se(manager_load_startable_unit_or_warn(m, "dml.slice", NULL, &dml) >= 0); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "dml.slice", NULL, &dml)); - assert_se(manager_load_startable_unit_or_warn(m, "dml-passthrough.slice", NULL, &dml_passthrough) >= 0); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "dml-passthrough.slice", NULL, &dml_passthrough)); assert_se(UNIT_GET_SLICE(dml_passthrough) == dml); - assert_se(manager_load_startable_unit_or_warn(m, "dml-passthrough-empty.service", NULL, &dml_passthrough_empty) >= 0); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "dml-passthrough-empty.service", NULL, &dml_passthrough_empty)); assert_se(UNIT_GET_SLICE(dml_passthrough_empty) == dml_passthrough); - assert_se(manager_load_startable_unit_or_warn(m, "dml-passthrough-set-dml.service", NULL, &dml_passthrough_set_dml) >= 0); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "dml-passthrough-set-dml.service", NULL, &dml_passthrough_set_dml)); assert_se(UNIT_GET_SLICE(dml_passthrough_set_dml) == dml_passthrough); - assert_se(manager_load_startable_unit_or_warn(m, "dml-passthrough-set-ml.service", NULL, &dml_passthrough_set_ml) >= 0); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "dml-passthrough-set-ml.service", NULL, &dml_passthrough_set_ml)); assert_se(UNIT_GET_SLICE(dml_passthrough_set_ml) == dml_passthrough); - assert_se(manager_load_startable_unit_or_warn(m, "dml-override.slice", NULL, &dml_override) >= 0); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "dml-override.slice", NULL, &dml_override)); assert_se(UNIT_GET_SLICE(dml_override) == dml); - assert_se(manager_load_startable_unit_or_warn(m, "dml-override-empty.service", NULL, &dml_override_empty) >= 0); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "dml-override-empty.service", NULL, &dml_override_empty)); assert_se(UNIT_GET_SLICE(dml_override_empty) == dml_override); - assert_se(manager_load_startable_unit_or_warn(m, "dml-discard.slice", NULL, &dml_discard) >= 0); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "dml-discard.slice", NULL, &dml_discard)); assert_se(UNIT_GET_SLICE(dml_discard) == dml); - assert_se(manager_load_startable_unit_or_warn(m, "dml-discard-empty.service", NULL, &dml_discard_empty) >= 0); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "dml-discard-empty.service", NULL, &dml_discard_empty)); assert_se(UNIT_GET_SLICE(dml_discard_empty) == dml_discard); - assert_se(manager_load_startable_unit_or_warn(m, "dml-discard-set-ml.service", NULL, &dml_discard_set_ml) >= 0); + ASSERT_OK(manager_load_startable_unit_or_warn(m, "dml-discard-set-ml.service", NULL, &dml_discard_set_ml)); assert_se(UNIT_GET_SLICE(dml_discard_set_ml) == dml_discard); assert_se(root = UNIT_GET_SLICE(dml)); diff --git a/src/test/test-cgroup-util.c b/src/test/test-cgroup-util.c index 51f52d9..1d8f99c 100644 --- a/src/test/test-cgroup-util.c +++ b/src/test/test-cgroup-util.c @@ -23,7 +23,7 @@ static void check_p_d_u(const char *path, int code, const char *result) { r = cg_path_decode_unit(path, &unit); printf("%s: %s → %s %d expected %s %d\n", __func__, path, unit, r, strnull(result), code); assert_se(r == code); - assert_se(streq_ptr(unit, result)); + ASSERT_STREQ(unit, result); } TEST(path_decode_unit) { @@ -45,7 +45,7 @@ static void check_p_g_u(const char *path, int code, const char *result) { r = cg_path_get_unit(path, &unit); printf("%s: %s → %s %d expected %s %d\n", __func__, path, unit, r, strnull(result), code); assert_se(r == code); - assert_se(streq_ptr(unit, result)); + ASSERT_STREQ(unit, result); } TEST(path_get_unit) { @@ -69,7 +69,7 @@ static void check_p_g_u_p(const char *path, int code, const char *result) { r = cg_path_get_unit_path(path, &unit_path); printf("%s: %s → %s %d expected %s %d\n", __func__, path, unit_path, r, strnull(result), code); assert_se(r == code); - assert_se(streq_ptr(unit_path, result)); + ASSERT_STREQ(unit_path, result); } TEST(path_get_unit_path) { @@ -96,7 +96,7 @@ static void check_p_g_u_u(const char *path, int code, const char *result) { r = cg_path_get_user_unit(path, &unit); printf("%s: %s → %s %d expected %s %d\n", __func__, path, unit, r, strnull(result), code); assert_se(r == code); - assert_se(streq_ptr(unit, result)); + ASSERT_STREQ(unit, result); } TEST(path_get_user_unit) { @@ -119,7 +119,7 @@ static void check_p_g_s(const char *path, int code, const char *result) { _cleanup_free_ char *s = NULL; assert_se(cg_path_get_session(path, &s) == code); - assert_se(streq_ptr(s, result)); + ASSERT_STREQ(s, result); } TEST(path_get_session) { @@ -146,7 +146,7 @@ static void check_p_g_slice(const char *path, int code, const char *result) { _cleanup_free_ char *s = NULL; assert_se(cg_path_get_slice(path, &s) == code); - assert_se(streq_ptr(s, result)); + ASSERT_STREQ(s, result); } TEST(path_get_slice) { @@ -163,7 +163,7 @@ static void check_p_g_u_slice(const char *path, int code, const char *result) { _cleanup_free_ char *s = NULL; assert_se(cg_path_get_user_slice(path, &s) == code); - assert_se(streq_ptr(s, result)); + ASSERT_STREQ(s, result); } TEST(path_get_user_slice) { @@ -194,7 +194,7 @@ TEST(proc) { _cleanup_closedir_ DIR *d = NULL; int r; - assert_se(proc_dir_open(&d) >= 0); + ASSERT_OK(proc_dir_open(&d)); for (;;) { _cleanup_free_ char *path = NULL, *path_shifted = NULL, *session = NULL, *unit = NULL, *user_unit = NULL, *machine = NULL, *slice = NULL; @@ -238,10 +238,10 @@ static void test_escape_one(const char *s, const char *expected) { assert_se(s); assert_se(expected); - assert_se(cg_escape(s, &b) >= 0); - assert_se(streq(b, expected)); + ASSERT_OK(cg_escape(s, &b)); + ASSERT_STREQ(b, expected); - assert_se(streq(cg_unescape(b), s)); + ASSERT_STREQ(cg_unescape(b), s); assert_se(filename_is_valid(b)); assert_se(!cg_needs_escape(s) || b[0] == '_'); @@ -284,7 +284,7 @@ static void test_slice_to_path_one(const char *unit, const char *path, int error log_info("actual: %s / %d", strnull(ret), r); log_info("expect: %s / %d", strnull(path), error); assert_se(r == error); - assert_se(streq_ptr(ret, path)); + ASSERT_STREQ(ret, path); } TEST(slice_to_path) { @@ -315,8 +315,8 @@ TEST(slice_to_path) { static void test_shift_path_one(const char *raw, const char *root, const char *shifted) { const char *s = NULL; - assert_se(cg_shift_path(raw, root, &s) >= 0); - assert_se(streq(s, shifted)); + ASSERT_OK(cg_shift_path(raw, root, &s)); + ASSERT_STREQ(s, shifted); } TEST(shift_path) { @@ -328,12 +328,13 @@ TEST(shift_path) { TEST(mask_supported, .sd_booted = true) { CGroupMask m; - CGroupController c; - assert_se(cg_mask_supported(&m) >= 0); + ASSERT_OK(cg_mask_supported(&m)); - for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) - printf("'%s' is supported: %s\n", cgroup_controller_to_string(c), yes_no(m & CGROUP_CONTROLLER_TO_MASK(c))); + for (CGroupController c = 0; c < _CGROUP_CONTROLLER_MAX; c++) + printf("'%s' is supported: %s\n", + cgroup_controller_to_string(c), + yes_no(m & CGROUP_CONTROLLER_TO_MASK(c))); } TEST(is_cgroup_fs, .sd_booted = true) { @@ -362,7 +363,7 @@ TEST(cg_tests) { int all, hybrid, systemd, r; r = cg_unified(); - if (r == -ENOMEDIUM) { + if (IN_SET(r, -ENOENT, -ENOMEDIUM)) { log_tests_skipped("cgroup not mounted"); return; } @@ -392,16 +393,16 @@ TEST(cg_tests) { TEST(cg_get_keyed_attribute) { _cleanup_free_ char *val = NULL; char *vals3[3] = {}, *vals3a[3] = {}; - int i, r; + int r; r = cg_get_keyed_attribute("cpu", "/init.scope", "no_such_file", STRV_MAKE("no_such_attr"), &val); - if (r == -ENOMEDIUM || ERRNO_IS_PRIVILEGE(r)) { + if (IN_SET(r, -ENOMEDIUM, -ENOENT) || ERRNO_IS_PRIVILEGE(r)) { log_info_errno(r, "Skipping most of %s, /sys/fs/cgroup not accessible: %m", __func__); return; } assert_se(r == -ENOENT); - assert_se(val == NULL); + ASSERT_NULL(val); if (access("/sys/fs/cgroup/init.scope/cpu.stat", R_OK) < 0) { log_info_errno(errno, "Skipping most of %s, /init.scope/cpu.stat not accessible: %m", __func__); @@ -410,7 +411,7 @@ TEST(cg_get_keyed_attribute) { assert_se(cg_get_keyed_attribute("cpu", "/init.scope", "cpu.stat", STRV_MAKE("no_such_attr"), &val) == -ENXIO); assert_se(cg_get_keyed_attribute_graceful("cpu", "/init.scope", "cpu.stat", STRV_MAKE("no_such_attr"), &val) == 0); - assert_se(val == NULL); + ASSERT_NULL(val); assert_se(cg_get_keyed_attribute("cpu", "/init.scope", "cpu.stat", STRV_MAKE("usage_usec"), &val) == 0); val = mfree(val); @@ -430,7 +431,7 @@ TEST(cg_get_keyed_attribute) { assert_se(cg_get_keyed_attribute("cpu", "/init.scope", "cpu.stat", STRV_MAKE("usage_usec", "user_usec", "system_usec"), vals3) == 0); - for (i = 0; i < 3; i++) + for (size_t i = 0; i < 3; i++) free(vals3[i]); assert_se(cg_get_keyed_attribute_graceful("cpu", "/init.scope", "cpu.stat", @@ -440,7 +441,7 @@ TEST(cg_get_keyed_attribute) { assert_se(cg_get_keyed_attribute("cpu", "/init.scope", "cpu.stat", STRV_MAKE("system_usec", "user_usec", "usage_usec"), vals3a) == 0); - for (i = 0; i < 3; i++) + for (size_t i = 0; i < 3; i++) free(vals3a[i]); assert_se(cg_get_keyed_attribute_graceful("cpu", "/init.scope", "cpu.stat", @@ -448,7 +449,7 @@ TEST(cg_get_keyed_attribute) { log_info("cpu /init.scope cpu.stat [system_usec user_usec usage_usec] → \"%s\", \"%s\", \"%s\"", vals3a[0], vals3a[1], vals3a[2]); - for (i = 0; i < 3; i++) { + for (size_t i = 0; i < 3; i++) { free(vals3[i]); free(vals3a[i]); } diff --git a/src/test/test-cgroup.c b/src/test/test-cgroup.c index 0fbd635..8bd4af9 100644 --- a/src/test/test-cgroup.c +++ b/src/test/test-cgroup.c @@ -5,6 +5,7 @@ #include "cgroup-setup.h" #include "cgroup-util.h" #include "errno-util.h" +#include "fd-util.h" #include "path-util.h" #include "process-util.h" #include "string-util.h" @@ -14,8 +15,8 @@ TEST(cg_split_spec) { char *c, *p; assert_se(cg_split_spec("foobar:/", &c, &p) == 0); - assert_se(streq(c, "foobar")); - assert_se(streq(p, "/")); + ASSERT_STREQ(c, "foobar"); + ASSERT_STREQ(p, "/"); c = mfree(c); p = mfree(p); @@ -30,13 +31,13 @@ TEST(cg_split_spec) { assert_se(cg_split_spec("fo/obar:/", &c, &p) < 0); assert_se(cg_split_spec("/", &c, &p) >= 0); - assert_se(c == NULL); - assert_se(streq(p, "/")); + ASSERT_NULL(c); + ASSERT_STREQ(p, "/"); p = mfree(p); assert_se(cg_split_spec("foo", &c, &p) >= 0); - assert_se(streq(c, "foo")); - assert_se(p == NULL); + ASSERT_STREQ(c, "foo"); + ASSERT_NULL(p); c = mfree(c); } @@ -44,8 +45,8 @@ TEST(cg_create) { int r; r = cg_unified_cached(false); - if (r == -ENOMEDIUM) { - log_tests_skipped("cgroup not mounted"); + if (IN_SET(r, -ENOMEDIUM, -ENOENT)) { + log_tests_skipped("cgroupfs is not mounted"); return; } assert_se(r >= 0); @@ -78,7 +79,7 @@ TEST(cg_create) { assert_se(cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, test_b, 0) == 0); assert_se(cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, getpid_cached(), &path) == 0); - assert_se(streq(path, test_b)); + ASSERT_STREQ(path, test_b); free(path); assert_se(cg_attach(SYSTEMD_CGROUP_CONTROLLER, test_a, 0) == 0); @@ -129,4 +130,47 @@ TEST(cg_create) { assert_se(cg_rmdir(SYSTEMD_CGROUP_CONTROLLER, test_a) == 0); } +TEST(id) { + _cleanup_free_ char *p = NULL, *p2 = NULL; + _cleanup_close_ int fd = -EBADF, fd2 = -EBADF; + uint64_t id, id2; + int r; + + r = cg_all_unified(); + if (r == 0) { + log_tests_skipped("skipping cgroupid test, not running in unified mode"); + return; + } + if (IN_SET(r, -ENOMEDIUM, -ENOENT)) { + log_tests_skipped("cgroupfs is not mounted"); + return; + } + assert_se(r > 0); + + fd = cg_path_open(SYSTEMD_CGROUP_CONTROLLER, "/"); + assert_se(fd >= 0); + + assert_se(fd_get_path(fd, &p) >= 0); + assert_se(path_equal(p, "/sys/fs/cgroup")); + + assert_se(cg_fd_get_cgroupid(fd, &id) >= 0); + + fd2 = cg_cgroupid_open(fd, id); + + if (ERRNO_IS_NEG_PRIVILEGE(fd2)) + log_notice("Skipping open-by-cgroup-id test because lacking privs."); + else { + assert_se(fd2 >= 0); + + assert_se(fd_get_path(fd2, &p2) >= 0); + assert_se(path_equal(p2, "/sys/fs/cgroup")); + + assert_se(cg_fd_get_cgroupid(fd2, &id2) >= 0); + + assert_se(id == id2); + + assert_se(inode_same_at(fd, NULL, fd2, NULL, AT_EMPTY_PATH) > 0); + } +} + DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-chase.c b/src/test/test-chase.c index dbbc99b..13ee702 100644 --- a/src/test/test-chase.c +++ b/src/test/test-chase.c @@ -23,11 +23,11 @@ static void test_chase_extract_filename_one(const char *path, const char *root, log_debug("/* %s(path=%s, root=%s) */", __func__, path, strnull(root)); assert_se(chase(path, root, CHASE_EXTRACT_FILENAME, &ret1, NULL) > 0); - assert_se(streq(ret1, expected)); + ASSERT_STREQ(ret1, expected); assert_se(chase(path, root, 0, &ret2, NULL) > 0); - assert_se(chase_extract_filename(ret2, root, &fname) >= 0); - assert_se(streq(fname, expected)); + ASSERT_OK(chase_extract_filename(ret2, root, &fname)); + ASSERT_STREQ(fname, expected); } TEST(chase) { @@ -42,7 +42,7 @@ TEST(chase) { assert_se(mkdtemp(temp)); top = strjoina(temp, "/top"); - assert_se(mkdir(top, 0700) >= 0); + ASSERT_OK(mkdir(top, 0700)); p = strjoina(top, "/dot"); if (symlink(".", p) < 0) { @@ -52,19 +52,19 @@ TEST(chase) { }; p = strjoina(top, "/dotdot"); - assert_se(symlink("..", p) >= 0); + ASSERT_OK(symlink("..", p)); p = strjoina(top, "/dotdota"); - assert_se(symlink("../a", p) >= 0); + ASSERT_OK(symlink("../a", p)); p = strjoina(temp, "/a"); - assert_se(symlink("b", p) >= 0); + ASSERT_OK(symlink("b", p)); p = strjoina(temp, "/b"); - assert_se(symlink("/usr", p) >= 0); + ASSERT_OK(symlink("/usr", p)); p = strjoina(temp, "/start"); - assert_se(symlink("top/dot/dotdota", p) >= 0); + ASSERT_OK(symlink("top/dot/dotdota", p)); /* Paths that use symlinks underneath the "root" */ @@ -104,7 +104,7 @@ TEST(chase) { assert_se(path_equal(result, qslash)); result = mfree(result); - assert_se(mkdir(q, 0700) >= 0); + ASSERT_OK(mkdir(q, 0700)); r = chase(p, temp, 0, &result, NULL); assert_se(r > 0); @@ -145,21 +145,21 @@ TEST(chase) { /* Paths that would "escape" outside of the "root" */ p = strjoina(temp, "/6dots"); - assert_se(symlink("../../..", p) >= 0); + ASSERT_OK(symlink("../../..", p)); r = chase(p, temp, 0, &result, NULL); assert_se(r > 0 && path_equal(result, temp)); result = mfree(result); p = strjoina(temp, "/6dotsusr"); - assert_se(symlink("../../../usr", p) >= 0); + ASSERT_OK(symlink("../../../usr", p)); r = chase(p, temp, 0, &result, NULL); assert_se(r > 0 && path_equal(result, q)); result = mfree(result); p = strjoina(temp, "/top/8dotsusr"); - assert_se(symlink("../../../../usr", p) >= 0); + ASSERT_OK(symlink("../../../../usr", p)); r = chase(p, temp, 0, &result, NULL); assert_se(r > 0 && path_equal(result, q)); @@ -168,12 +168,12 @@ TEST(chase) { /* Paths that contain repeated slashes */ p = strjoina(temp, "/slashslash"); - assert_se(symlink("///usr///", p) >= 0); + ASSERT_OK(symlink("///usr///", p)); r = chase(p, NULL, 0, &result, NULL); assert_se(r > 0); assert_se(path_equal(result, "/usr")); - assert_se(streq(result, "/usr")); /* we guarantee that we drop redundant slashes */ + ASSERT_STREQ(result, "/usr"); /* we guarantee that we drop redundant slashes */ result = mfree(result); r = chase(p, temp, 0, &result, NULL); @@ -185,14 +185,14 @@ TEST(chase) { if (geteuid() == 0) { p = strjoina(temp, "/user"); - assert_se(mkdir(p, 0755) >= 0); - assert_se(chown(p, UID_NOBODY, GID_NOBODY) >= 0); + ASSERT_OK(mkdir(p, 0755)); + ASSERT_OK(chown(p, UID_NOBODY, GID_NOBODY)); q = strjoina(temp, "/user/root"); - assert_se(mkdir(q, 0755) >= 0); + ASSERT_OK(mkdir(q, 0755)); p = strjoina(q, "/link"); - assert_se(symlink("/", p) >= 0); + ASSERT_OK(symlink("/", p)); /* Fail when user-owned directories contain root-owned subdirectories. */ r = chase(p, temp, CHASE_SAFE, &result, NULL); @@ -218,22 +218,28 @@ TEST(chase) { r = chase("/../.././//../../etc", NULL, 0, &result, NULL); assert_se(r > 0); - assert_se(streq(result, "/etc")); + ASSERT_STREQ(result, "/etc"); result = mfree(result); r = chase("/../.././//../../test-chase.fsldajfl", NULL, CHASE_NONEXISTENT, &result, NULL); assert_se(r == 0); - assert_se(streq(result, "/test-chase.fsldajfl")); + ASSERT_STREQ(result, "/test-chase.fsldajfl"); result = mfree(result); r = chase("/../.././//../../etc", "/", CHASE_PREFIX_ROOT, &result, NULL); assert_se(r > 0); - assert_se(streq(result, "/etc")); + ASSERT_STREQ(result, "/etc"); result = mfree(result); r = chase("/../.././//../../test-chase.fsldajfl", "/", CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &result, NULL); assert_se(r == 0); - assert_se(streq(result, "/test-chase.fsldajfl")); + ASSERT_STREQ(result, "/test-chase.fsldajfl"); + result = mfree(result); + + r = chase("/.path/with/dot", temp, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &result, NULL); + ASSERT_OK(r); + q = strjoina(temp, "/.path/with/dot"); + ASSERT_STREQ(result, q); result = mfree(result); r = chase("/etc/machine-id/foo", NULL, 0, &result, NULL); @@ -243,7 +249,7 @@ TEST(chase) { /* Path that loops back to self */ p = strjoina(temp, "/recursive-symlink"); - assert_se(symlink("recursive-symlink", p) >= 0); + ASSERT_OK(symlink("recursive-symlink", p)); r = chase(p, NULL, 0, &result, NULL); assert_se(r == -ELOOP); @@ -269,9 +275,9 @@ TEST(chase) { /* Relative paths */ - assert_se(safe_getcwd(&pwd) >= 0); + ASSERT_OK(safe_getcwd(&pwd)); - assert_se(chdir(temp) >= 0); + ASSERT_OK(chdir(temp)); p = "this/is/a/relative/path"; r = chase(p, NULL, CHASE_NONEXISTENT, &result, NULL); @@ -309,46 +315,46 @@ TEST(chase) { if (geteuid() == 0) { p = strjoina(temp, "/priv1"); - assert_se(mkdir(p, 0755) >= 0); + ASSERT_OK(mkdir(p, 0755)); q = strjoina(p, "/priv2"); - assert_se(mkdir(q, 0755) >= 0); + ASSERT_OK(mkdir(q, 0755)); - assert_se(chase(q, NULL, CHASE_SAFE, NULL, NULL) >= 0); + ASSERT_OK(chase(q, NULL, CHASE_SAFE, NULL, NULL)); - assert_se(chown(q, UID_NOBODY, GID_NOBODY) >= 0); - assert_se(chase(q, NULL, CHASE_SAFE, NULL, NULL) >= 0); + ASSERT_OK(chown(q, UID_NOBODY, GID_NOBODY)); + ASSERT_OK(chase(q, NULL, CHASE_SAFE, NULL, NULL)); - assert_se(chown(p, UID_NOBODY, GID_NOBODY) >= 0); - assert_se(chase(q, NULL, CHASE_SAFE, NULL, NULL) >= 0); + ASSERT_OK(chown(p, UID_NOBODY, GID_NOBODY)); + ASSERT_OK(chase(q, NULL, CHASE_SAFE, NULL, NULL)); assert_se(chown(q, 0, 0) >= 0); assert_se(chase(q, NULL, CHASE_SAFE, NULL, NULL) == -ENOLINK); - assert_se(rmdir(q) >= 0); - assert_se(symlink("/etc/passwd", q) >= 0); + ASSERT_OK(rmdir(q)); + ASSERT_OK(symlink("/etc/passwd", q)); assert_se(chase(q, NULL, CHASE_SAFE, NULL, NULL) == -ENOLINK); assert_se(chown(p, 0, 0) >= 0); - assert_se(chase(q, NULL, CHASE_SAFE, NULL, NULL) >= 0); + ASSERT_OK(chase(q, NULL, CHASE_SAFE, NULL, NULL)); } p = strjoina(temp, "/machine-id-test"); - assert_se(symlink("/usr/../etc/./machine-id", p) >= 0); + ASSERT_OK(symlink("/usr/../etc/./machine-id", p)); r = chase(p, NULL, 0, NULL, &pfd); if (r != -ENOENT && sd_id128_get_machine(NULL) >= 0) { _cleanup_close_ int fd = -EBADF; sd_id128_t a, b; - assert_se(pfd >= 0); + ASSERT_OK(pfd); fd = fd_reopen(pfd, O_RDONLY|O_CLOEXEC); - assert_se(fd >= 0); + ASSERT_OK(fd); safe_close(pfd); - assert_se(id128_read_fd(fd, ID128_FORMAT_PLAIN, &a) >= 0); - assert_se(sd_id128_get_machine(&b) >= 0); + ASSERT_OK(id128_read_fd(fd, ID128_FORMAT_PLAIN, &a)); + ASSERT_OK(sd_id128_get_machine(&b)); assert_se(sd_id128_equal(a, b)); } @@ -365,24 +371,24 @@ TEST(chase) { q = strjoina(temp, "/symlink"); assert_se(symlink(p, q) >= 0); r = chase(q, NULL, CHASE_NOFOLLOW, &result, &pfd); - assert_se(r >= 0); - assert_se(pfd >= 0); + ASSERT_OK(r); + ASSERT_OK(pfd); assert_se(path_equal(result, q)); - assert_se(fstat(pfd, &st) >= 0); + ASSERT_OK(fstat(pfd, &st)); assert_se(S_ISLNK(st.st_mode)); result = mfree(result); pfd = safe_close(pfd); /* s1 -> s2 -> nonexistent */ q = strjoina(temp, "/s1"); - assert_se(symlink("s2", q) >= 0); + ASSERT_OK(symlink("s2", q)); p = strjoina(temp, "/s2"); - assert_se(symlink("nonexistent", p) >= 0); + ASSERT_OK(symlink("nonexistent", p)); r = chase(q, NULL, CHASE_NOFOLLOW, &result, &pfd); - assert_se(r >= 0); - assert_se(pfd >= 0); + ASSERT_OK(r); + ASSERT_OK(pfd); assert_se(path_equal(result, q)); - assert_se(fstat(pfd, &st) >= 0); + ASSERT_OK(fstat(pfd, &st)); assert_se(S_ISLNK(st.st_mode)); result = mfree(result); pfd = safe_close(pfd); @@ -393,41 +399,41 @@ TEST(chase) { r = chase(p, NULL, CHASE_STEP, &result, NULL); assert_se(r == 0); p = strjoina(temp, "/top/dot/dotdota"); - assert_se(streq(p, result)); + ASSERT_STREQ(p, result); result = mfree(result); r = chase(p, NULL, CHASE_STEP, &result, NULL); assert_se(r == 0); p = strjoina(temp, "/top/dotdota"); - assert_se(streq(p, result)); + ASSERT_STREQ(p, result); result = mfree(result); r = chase(p, NULL, CHASE_STEP, &result, NULL); assert_se(r == 0); p = strjoina(temp, "/top/../a"); - assert_se(streq(p, result)); + ASSERT_STREQ(p, result); result = mfree(result); r = chase(p, NULL, CHASE_STEP, &result, NULL); assert_se(r == 0); p = strjoina(temp, "/a"); - assert_se(streq(p, result)); + ASSERT_STREQ(p, result); result = mfree(result); r = chase(p, NULL, CHASE_STEP, &result, NULL); assert_se(r == 0); p = strjoina(temp, "/b"); - assert_se(streq(p, result)); + ASSERT_STREQ(p, result); result = mfree(result); r = chase(p, NULL, CHASE_STEP, &result, NULL); assert_se(r == 0); - assert_se(streq("/usr", result)); + ASSERT_STREQ("/usr", result); result = mfree(result); r = chase("/usr", NULL, CHASE_STEP, &result, NULL); assert_se(r > 0); - assert_se(streq("/usr", result)); + ASSERT_STREQ("/usr", result); result = mfree(result); /* Make sure that symlinks in the "root" path are not resolved, but those below are */ @@ -449,7 +455,7 @@ TEST(chase) { assert_se(chase("top/dot/dot", temp, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_WARN, NULL, NULL) == -EREMCHG); cleanup: - assert_se(rm_rf(temp, REMOVE_ROOT|REMOVE_PHYSICAL) >= 0); + ASSERT_OK(rm_rf(temp, REMOVE_ROOT|REMOVE_PHYSICAL)); } TEST(chaseat) { @@ -461,29 +467,29 @@ TEST(chaseat) { struct stat st; const char *p; - assert_se((tfd = mkdtemp_open(NULL, 0, &t)) >= 0); + ASSERT_OK((tfd = mkdtemp_open(NULL, 0, &t))); /* Test that AT_FDCWD with CHASE_AT_RESOLVE_IN_ROOT resolves against / and not the current working * directory. */ - assert_se(symlinkat("/usr", tfd, "abc") >= 0); + ASSERT_OK(symlinkat("/usr", tfd, "abc")); p = strjoina(t, "/abc"); - assert_se(chaseat(AT_FDCWD, p, CHASE_AT_RESOLVE_IN_ROOT, &result, NULL) >= 0); - assert_se(streq(result, "/usr")); + ASSERT_OK(chaseat(AT_FDCWD, p, CHASE_AT_RESOLVE_IN_ROOT, &result, NULL)); + ASSERT_STREQ(result, "/usr"); result = mfree(result); /* If the file descriptor points to the root directory, the result will be absolute. */ fd = open("/", O_CLOEXEC | O_DIRECTORY | O_PATH); - assert_se(fd >= 0); + ASSERT_OK(fd); - assert_se(chaseat(fd, p, 0, &result, NULL) >= 0); - assert_se(streq(result, "/usr")); + ASSERT_OK(chaseat(fd, p, 0, &result, NULL)); + ASSERT_STREQ(result, "/usr"); result = mfree(result); - assert_se(chaseat(fd, p, CHASE_AT_RESOLVE_IN_ROOT, &result, NULL) >= 0); - assert_se(streq(result, "/usr")); + ASSERT_OK(chaseat(fd, p, CHASE_AT_RESOLVE_IN_ROOT, &result, NULL)); + ASSERT_STREQ(result, "/usr"); result = mfree(result); fd = safe_close(fd); @@ -491,36 +497,36 @@ TEST(chaseat) { /* If the file descriptor does not point to the root directory, the result will be relative * unless the result is outside of the specified file descriptor. */ - assert_se(chaseat(tfd, "abc", 0, &result, NULL) >= 0); - assert_se(streq(result, "/usr")); + ASSERT_OK(chaseat(tfd, "abc", 0, &result, NULL)); + ASSERT_STREQ(result, "/usr"); result = mfree(result); - assert_se(chaseat(tfd, "/abc", 0, &result, NULL) >= 0); - assert_se(streq(result, "/usr")); + ASSERT_OK(chaseat(tfd, "/abc", 0, &result, NULL)); + ASSERT_STREQ(result, "/usr"); result = mfree(result); assert_se(chaseat(tfd, "abc", CHASE_AT_RESOLVE_IN_ROOT, NULL, NULL) == -ENOENT); assert_se(chaseat(tfd, "/abc", CHASE_AT_RESOLVE_IN_ROOT, NULL, NULL) == -ENOENT); - assert_se(chaseat(tfd, "abc", CHASE_AT_RESOLVE_IN_ROOT | CHASE_NONEXISTENT, &result, NULL) >= 0); - assert_se(streq(result, "usr")); + ASSERT_OK(chaseat(tfd, "abc", CHASE_AT_RESOLVE_IN_ROOT | CHASE_NONEXISTENT, &result, NULL)); + ASSERT_STREQ(result, "usr"); result = mfree(result); - assert_se(chaseat(tfd, "/abc", CHASE_AT_RESOLVE_IN_ROOT | CHASE_NONEXISTENT, &result, NULL) >= 0); - assert_se(streq(result, "usr")); + ASSERT_OK(chaseat(tfd, "/abc", CHASE_AT_RESOLVE_IN_ROOT | CHASE_NONEXISTENT, &result, NULL)); + ASSERT_STREQ(result, "usr"); result = mfree(result); /* Test that absolute path or not are the same when resolving relative to a directory file * descriptor and that we always get a relative path back. */ - assert_se(fd = openat(tfd, "def", O_CREAT|O_CLOEXEC, 0700) >= 0); + ASSERT_OK(fd = openat(tfd, "def", O_CREAT|O_CLOEXEC, 0700)); fd = safe_close(fd); - assert_se(symlinkat("/def", tfd, "qed") >= 0); - assert_se(chaseat(tfd, "qed", CHASE_AT_RESOLVE_IN_ROOT, &result, NULL) >= 0); - assert_se(streq(result, "def")); + ASSERT_OK(symlinkat("/def", tfd, "qed")); + ASSERT_OK(chaseat(tfd, "qed", CHASE_AT_RESOLVE_IN_ROOT, &result, NULL)); + ASSERT_STREQ(result, "def"); result = mfree(result); - assert_se(chaseat(tfd, "/qed", CHASE_AT_RESOLVE_IN_ROOT, &result, NULL) >= 0); - assert_se(streq(result, "def")); + ASSERT_OK(chaseat(tfd, "/qed", CHASE_AT_RESOLVE_IN_ROOT, &result, NULL)); + ASSERT_STREQ(result, "def"); result = mfree(result); /* Valid directory file descriptor without CHASE_AT_RESOLVE_IN_ROOT should resolve symlinks against @@ -529,157 +535,157 @@ TEST(chaseat) { /* Test CHASE_PARENT */ - assert_se((fd = open_mkdir_at(tfd, "chase", O_CLOEXEC, 0755)) >= 0); - assert_se(symlinkat("/def", fd, "parent") >= 0); + ASSERT_OK((fd = open_mkdir_at(tfd, "chase", O_CLOEXEC, 0755))); + ASSERT_OK(symlinkat("/def", fd, "parent")); fd = safe_close(fd); /* Make sure that when we chase a symlink parent directory, that we chase the parent directory of the * symlink target and not the symlink itself. But if we add CHASE_NOFOLLOW, we get the parent * directory of the symlink itself. */ - assert_se(chaseat(tfd, "chase/parent", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT, &result, &fd) >= 0); - assert_se(faccessat(fd, "def", F_OK, 0) >= 0); - assert_se(streq(result, "def")); + ASSERT_OK(chaseat(tfd, "chase/parent", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT, &result, &fd)); + ASSERT_OK(faccessat(fd, "def", F_OK, 0)); + ASSERT_STREQ(result, "def"); fd = safe_close(fd); result = mfree(result); - assert_se(chaseat(tfd, "chase/parent", CHASE_AT_RESOLVE_IN_ROOT|CHASE_PARENT|CHASE_NOFOLLOW, &result, &fd) >= 0); - assert_se(faccessat(fd, "parent", F_OK, AT_SYMLINK_NOFOLLOW) >= 0); - assert_se(streq(result, "chase/parent")); + ASSERT_OK(chaseat(tfd, "chase/parent", CHASE_AT_RESOLVE_IN_ROOT|CHASE_PARENT|CHASE_NOFOLLOW, &result, &fd)); + ASSERT_OK(faccessat(fd, "parent", F_OK, AT_SYMLINK_NOFOLLOW)); + ASSERT_STREQ(result, "chase/parent"); fd = safe_close(fd); result = mfree(result); - assert_se(chaseat(tfd, "chase", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT, &result, &fd) >= 0); - assert_se(faccessat(fd, "chase", F_OK, 0) >= 0); - assert_se(streq(result, "chase")); + ASSERT_OK(chaseat(tfd, "chase", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT, &result, &fd)); + ASSERT_OK(faccessat(fd, "chase", F_OK, 0)); + ASSERT_STREQ(result, "chase"); fd = safe_close(fd); result = mfree(result); - assert_se(chaseat(tfd, "/", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT, &result, NULL) >= 0); - assert_se(streq(result, ".")); + ASSERT_OK(chaseat(tfd, "/", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT, &result, NULL)); + ASSERT_STREQ(result, "."); result = mfree(result); - assert_se(chaseat(tfd, ".", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT, &result, NULL) >= 0); - assert_se(streq(result, ".")); + assert_se(chaseat(tfd, ".", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT, &result, NULL)); + ASSERT_STREQ(result, "."); result = mfree(result); /* Test CHASE_MKDIR_0755 */ - assert_se(chaseat(tfd, "m/k/d/i/r", CHASE_MKDIR_0755|CHASE_NONEXISTENT, &result, NULL) >= 0); - assert_se(faccessat(tfd, "m/k/d/i", F_OK, 0) >= 0); + ASSERT_OK(chaseat(tfd, "m/k/d/i/r", CHASE_MKDIR_0755|CHASE_NONEXISTENT, &result, NULL)); + ASSERT_OK(faccessat(tfd, "m/k/d/i", F_OK, 0)); assert_se(RET_NERRNO(faccessat(tfd, "m/k/d/i/r", F_OK, 0)) == -ENOENT); - assert_se(streq(result, "m/k/d/i/r")); + ASSERT_STREQ(result, "m/k/d/i/r"); result = mfree(result); - assert_se(chaseat(tfd, "m/../q", CHASE_MKDIR_0755|CHASE_NONEXISTENT, &result, NULL) >= 0); - assert_se(faccessat(tfd, "m", F_OK, 0) >= 0); + ASSERT_OK(chaseat(tfd, "m/../q", CHASE_MKDIR_0755|CHASE_NONEXISTENT, &result, NULL)); + ASSERT_OK(faccessat(tfd, "m", F_OK, 0)); assert_se(RET_NERRNO(faccessat(tfd, "q", F_OK, 0)) == -ENOENT); - assert_se(streq(result, "q")); + ASSERT_STREQ(result, "q"); result = mfree(result); assert_se(chaseat(tfd, "i/../p", CHASE_MKDIR_0755|CHASE_NONEXISTENT, NULL, NULL) == -ENOENT); /* Test CHASE_EXTRACT_FILENAME */ - assert_se(chaseat(tfd, "chase/parent", CHASE_AT_RESOLVE_IN_ROOT|CHASE_PARENT|CHASE_NOFOLLOW|CHASE_EXTRACT_FILENAME, &result, &fd) >= 0); - assert_se(faccessat(fd, result, F_OK, AT_SYMLINK_NOFOLLOW) >= 0); - assert_se(streq(result, "parent")); + ASSERT_OK(chaseat(tfd, "chase/parent", CHASE_AT_RESOLVE_IN_ROOT|CHASE_PARENT|CHASE_NOFOLLOW|CHASE_EXTRACT_FILENAME, &result, &fd)); + ASSERT_OK(faccessat(fd, result, F_OK, AT_SYMLINK_NOFOLLOW)); + ASSERT_STREQ(result, "parent"); fd = safe_close(fd); result = mfree(result); - assert_se(chaseat(tfd, "chase", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT|CHASE_EXTRACT_FILENAME, &result, &fd) >= 0); - assert_se(faccessat(fd, result, F_OK, 0) >= 0); - assert_se(streq(result, "chase")); + ASSERT_OK(chaseat(tfd, "chase", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT|CHASE_EXTRACT_FILENAME, &result, &fd)); + ASSERT_OK(faccessat(fd, result, F_OK, 0)); + ASSERT_STREQ(result, "chase"); fd = safe_close(fd); result = mfree(result); - assert_se(chaseat(tfd, "/", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT|CHASE_EXTRACT_FILENAME, &result, NULL) >= 0); - assert_se(streq(result, ".")); + ASSERT_OK(chaseat(tfd, "/", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT|CHASE_EXTRACT_FILENAME, &result, NULL)); + ASSERT_STREQ(result, "."); result = mfree(result); - assert_se(chaseat(tfd, ".", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT|CHASE_EXTRACT_FILENAME, &result, NULL) >= 0); - assert_se(streq(result, ".")); + ASSERT_OK(chaseat(tfd, ".", CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT|CHASE_EXTRACT_FILENAME, &result, NULL)); + ASSERT_STREQ(result, "."); result = mfree(result); - assert_se(chaseat(tfd, NULL, CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT|CHASE_EXTRACT_FILENAME, &result, NULL) >= 0); - assert_se(streq(result, ".")); + ASSERT_OK(chaseat(tfd, NULL, CHASE_PARENT|CHASE_AT_RESOLVE_IN_ROOT|CHASE_EXTRACT_FILENAME, &result, NULL)); + ASSERT_STREQ(result, "."); result = mfree(result); /* Test chase_and_openat() */ fd = chase_and_openat(tfd, "o/p/e/n/f/i/l/e", CHASE_MKDIR_0755, O_CREAT|O_EXCL|O_CLOEXEC, NULL); - assert_se(fd >= 0); - assert_se(fd_verify_regular(fd) >= 0); + ASSERT_OK(fd); + ASSERT_OK(fd_verify_regular(fd)); fd = safe_close(fd); fd = chase_and_openat(tfd, "o/p/e/n/d/i/r", CHASE_MKDIR_0755, O_DIRECTORY|O_CREAT|O_EXCL|O_CLOEXEC, NULL); - assert_se(fd >= 0); - assert_se(fd_verify_directory(fd) >= 0); + ASSERT_OK(fd); + ASSERT_OK(fd_verify_directory(fd)); fd = safe_close(fd); fd = chase_and_openat(tfd, NULL, CHASE_PARENT|CHASE_EXTRACT_FILENAME, O_PATH|O_DIRECTORY|O_CLOEXEC, &result); - assert_se(fd >= 0); - assert_se(streq(result, ".")); + ASSERT_OK(fd); + ASSERT_STREQ(result, "."); fd = safe_close(fd); result = mfree(result); /* Test chase_and_openatdir() */ - assert_se(chase_and_opendirat(tfd, "o/p/e/n/d/i", 0, &result, &dir) >= 0); + ASSERT_OK(chase_and_opendirat(tfd, "o/p/e/n/d/i", 0, &result, &dir)); FOREACH_DIRENT(de, dir, assert_not_reached()) - assert_se(streq(de->d_name, "r")); - assert_se(streq(result, "o/p/e/n/d/i")); + ASSERT_STREQ(de->d_name, "r"); + ASSERT_STREQ(result, "o/p/e/n/d/i"); result = mfree(result); /* Test chase_and_statat() */ - assert_se(chase_and_statat(tfd, "o/p", 0, &result, &st) >= 0); - assert_se(stat_verify_directory(&st) >= 0); - assert_se(streq(result, "o/p")); + ASSERT_OK(chase_and_statat(tfd, "o/p", 0, &result, &st)); + ASSERT_OK(stat_verify_directory(&st)); + ASSERT_STREQ(result, "o/p"); result = mfree(result); /* Test chase_and_accessat() */ - assert_se(chase_and_accessat(tfd, "o/p/e", 0, F_OK, &result) >= 0); - assert_se(streq(result, "o/p/e")); + ASSERT_OK(chase_and_accessat(tfd, "o/p/e", 0, F_OK, &result)); + ASSERT_STREQ(result, "o/p/e"); result = mfree(result); /* Test chase_and_fopenat_unlocked() */ - assert_se(chase_and_fopenat_unlocked(tfd, "o/p/e/n/f/i/l/e", 0, "re", &result, &f) >= 0); + ASSERT_OK(chase_and_fopenat_unlocked(tfd, "o/p/e/n/f/i/l/e", 0, "re", &result, &f)); assert_se(fread(&(char[1]) {}, 1, 1, f) == 0); assert_se(feof(f)); f = safe_fclose(f); - assert_se(streq(result, "o/p/e/n/f/i/l/e")); + ASSERT_STREQ(result, "o/p/e/n/f/i/l/e"); result = mfree(result); /* Test chase_and_unlinkat() */ - assert_se(chase_and_unlinkat(tfd, "o/p/e/n/f/i/l/e", 0, 0, &result) >= 0); - assert_se(streq(result, "o/p/e/n/f/i/l/e")); + ASSERT_OK(chase_and_unlinkat(tfd, "o/p/e/n/f/i/l/e", 0, 0, &result)); + ASSERT_STREQ(result, "o/p/e/n/f/i/l/e"); result = mfree(result); /* Test chase_and_open_parent_at() */ - assert_se((fd = chase_and_open_parent_at(tfd, "chase/parent", CHASE_AT_RESOLVE_IN_ROOT|CHASE_NOFOLLOW, &result)) >= 0); - assert_se(faccessat(fd, result, F_OK, AT_SYMLINK_NOFOLLOW) >= 0); - assert_se(streq(result, "parent")); + ASSERT_OK((fd = chase_and_open_parent_at(tfd, "chase/parent", CHASE_AT_RESOLVE_IN_ROOT|CHASE_NOFOLLOW, &result))); + ASSERT_OK(faccessat(fd, result, F_OK, AT_SYMLINK_NOFOLLOW)); + ASSERT_STREQ(result, "parent"); fd = safe_close(fd); result = mfree(result); - assert_se((fd = chase_and_open_parent_at(tfd, "chase", CHASE_AT_RESOLVE_IN_ROOT, &result)) >= 0); - assert_se(faccessat(fd, result, F_OK, 0) >= 0); - assert_se(streq(result, "chase")); + ASSERT_OK((fd = chase_and_open_parent_at(tfd, "chase", CHASE_AT_RESOLVE_IN_ROOT, &result))); + ASSERT_OK(faccessat(fd, result, F_OK, 0)); + ASSERT_STREQ(result, "chase"); fd = safe_close(fd); result = mfree(result); - assert_se((fd = chase_and_open_parent_at(tfd, "/", CHASE_AT_RESOLVE_IN_ROOT, &result)) >= 0); - assert_se(streq(result, ".")); + ASSERT_OK((fd = chase_and_open_parent_at(tfd, "/", CHASE_AT_RESOLVE_IN_ROOT, &result))); + ASSERT_STREQ(result, "."); fd = safe_close(fd); result = mfree(result); - assert_se((fd = chase_and_open_parent_at(tfd, ".", CHASE_AT_RESOLVE_IN_ROOT, &result)) >= 0); - assert_se(streq(result, ".")); + ASSERT_OK((fd = chase_and_open_parent_at(tfd, ".", CHASE_AT_RESOLVE_IN_ROOT, &result))); + ASSERT_STREQ(result, "."); fd = safe_close(fd); result = mfree(result); } @@ -687,47 +693,47 @@ TEST(chaseat) { TEST(chaseat_prefix_root) { _cleanup_free_ char *cwd = NULL, *ret = NULL, *expected = NULL; - assert_se(safe_getcwd(&cwd) >= 0); + ASSERT_OK(safe_getcwd(&cwd)); - assert_se(chaseat_prefix_root("/hoge", NULL, &ret) >= 0); - assert_se(streq(ret, "/hoge")); + ASSERT_OK(chaseat_prefix_root("/hoge", NULL, &ret)); + ASSERT_STREQ(ret, "/hoge"); ret = mfree(ret); - assert_se(chaseat_prefix_root("/hoge", "a/b/c", &ret) >= 0); - assert_se(streq(ret, "/hoge")); + ASSERT_OK(chaseat_prefix_root("/hoge", "a/b/c", &ret)); + ASSERT_STREQ(ret, "/hoge"); ret = mfree(ret); - assert_se(chaseat_prefix_root("hoge", "/a/b//./c///", &ret) >= 0); - assert_se(streq(ret, "/a/b/c/hoge")); + ASSERT_OK(chaseat_prefix_root("hoge", "/a/b//./c///", &ret)); + ASSERT_STREQ(ret, "/a/b/c/hoge"); ret = mfree(ret); - assert_se(chaseat_prefix_root("hoge", "a/b//./c///", &ret) >= 0); + ASSERT_OK(chaseat_prefix_root("hoge", "a/b//./c///", &ret)); assert_se(expected = path_join(cwd, "a/b/c/hoge")); - assert_se(streq(ret, expected)); + ASSERT_STREQ(ret, expected); ret = mfree(ret); expected = mfree(expected); - assert_se(chaseat_prefix_root("./hoge/aaa/../././b", "/a/b//./c///", &ret) >= 0); - assert_se(streq(ret, "/a/b/c/hoge/aaa/../././b")); + ASSERT_OK(chaseat_prefix_root("./hoge/aaa/../././b", "/a/b//./c///", &ret)); + ASSERT_STREQ(ret, "/a/b/c/hoge/aaa/../././b"); ret = mfree(ret); assert_se(chaseat_prefix_root("./hoge/aaa/../././b", "a/b//./c///", &ret) >= 0); assert_se(expected = path_join(cwd, "a/b/c/hoge/aaa/../././b")); - assert_se(streq(ret, expected)); + ASSERT_STREQ(ret, expected); } TEST(trailing_dot_dot) { _cleanup_free_ char *path = NULL, *fdpath = NULL; _cleanup_close_ int fd = -EBADF; - assert_se(chase("/usr/..", NULL, CHASE_PARENT, &path, &fd) >= 0); + ASSERT_OK(chase("/usr/..", NULL, CHASE_PARENT, &path, &fd)); assert_se(path_equal(path, "/")); - assert_se(fd_get_path(fd, &fdpath) >= 0); + ASSERT_OK(fd_get_path(fd, &fdpath)); assert_se(path_equal(fdpath, "/")); path = mfree(path); @@ -735,16 +741,16 @@ TEST(trailing_dot_dot) { fd = safe_close(fd); _cleanup_(rm_rf_physical_and_freep) char *t = NULL; - assert_se(mkdtemp_malloc(NULL, &t) >= 0); + ASSERT_OK(mkdtemp_malloc(NULL, &t)); _cleanup_free_ char *sub = ASSERT_PTR(path_join(t, "a/b/c/d")); - assert_se(mkdir_p(sub, 0700) >= 0); + ASSERT_OK(mkdir_p(sub, 0700)); _cleanup_free_ char *suffixed = ASSERT_PTR(path_join(sub, "..")); - assert_se(chase(suffixed, NULL, CHASE_PARENT, &path, &fd) >= 0); + ASSERT_OK(chase(suffixed, NULL, CHASE_PARENT, &path, &fd)); _cleanup_free_ char *expected1 = ASSERT_PTR(path_join(t, "a/b/c")); _cleanup_free_ char *expected2 = ASSERT_PTR(path_join(t, "a/b")); assert_se(path_equal(path, expected1)); - assert_se(fd_get_path(fd, &fdpath) >= 0); + ASSERT_OK(fd_get_path(fd, &fdpath)); assert_se(path_equal(fdpath, expected2)); } diff --git a/src/test/test-color-util.c b/src/test/test-color-util.c new file mode 100644 index 0000000..3d00d87 --- /dev/null +++ b/src/test/test-color-util.c @@ -0,0 +1,63 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include "color-util.h" +#include "tests.h" + +TEST(hsv_to_rgb) { + uint8_t r, g, b; + + hsv_to_rgb(0, 0, 0, &r, &g, &b); + assert(r == 0 && g == 0 && b == 0); + + hsv_to_rgb(60, 0, 0, &r, &g, &b); + assert(r == 0 && g == 0 && b == 0); + + hsv_to_rgb(0, 0, 100, &r, &g, &b); + assert(r == 255 && g == 255 && b == 255); + + hsv_to_rgb(0, 100, 100, &r, &g, &b); + assert(r == 255 && g == 0 && b == 0); + + hsv_to_rgb(120, 100, 100, &r, &g, &b); + assert(r == 0 && g == 255 && b == 0); + + hsv_to_rgb(240, 100, 100, &r, &g, &b); + assert(r == 0 && g == 0 && b == 255); + + hsv_to_rgb(311, 52, 62, &r, &g, &b); + assert(r == 158 && g == 75 && b == 143); +} + +TEST(rgb_to_hsv) { + + double h, s, v; + rgb_to_hsv(0, 0, 0, &h, &s, &v); + assert(s <= 0); + assert(v <= 0); + + rgb_to_hsv(1, 1, 1, &h, &s, &v); + assert(s <= 0); + assert(v >= 100); + + rgb_to_hsv(1, 0, 0, &h, &s, &v); + assert(h >= 359 || h <= 1); + assert(s >= 100); + assert(v >= 100); + + rgb_to_hsv(0, 1, 0, &h, &s, &v); + assert(h >= 119 && h <= 121); + assert(s >= 100); + assert(v >= 100); + + rgb_to_hsv(0, 0, 1, &h, &s, &v); + assert(h >= 239 && h <= 241); + assert(s >= 100); + assert(v >= 100); + + rgb_to_hsv(0.5, 0.6, 0.7, &h, &s, &v); + assert(h >= 209 && h <= 211); + assert(s >= 28 && s <= 31); + assert(v >= 69 && v <= 71); +} + +DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-compress.c b/src/test/test-compress.c index 2f20d00..868b862 100644 --- a/src/test/test-compress.c +++ b/src/test/test-compress.c @@ -6,6 +6,7 @@ #include <lz4.h> #endif +#include "dlfcn-util.h" #include "alloc-util.h" #include "compress.h" #include "fd-util.h" @@ -187,13 +188,13 @@ _unused_ static void test_compress_stream(const char *compression, log_debug("/* create source from %s */", srcfile); - assert_se((src = open(srcfile, O_RDONLY|O_CLOEXEC)) >= 0); + ASSERT_OK((src = open(srcfile, O_RDONLY|O_CLOEXEC))); log_debug("/* test compression */"); assert_se((dst = mkostemp_safe(pattern)) >= 0); - assert_se(compress(src, dst, -1, &uncompressed_size) >= 0); + ASSERT_OK(compress(src, dst, -1, &uncompressed_size)); if (cat) { assert_se(asprintf(&cmd, "%s %s | diff %s -", cat, pattern, srcfile) > 0); @@ -241,16 +242,16 @@ static void test_lz4_decompress_partial(void) { memset(&huge[STRLEN("HUGE=")], 'x', HUGE_SIZE - STRLEN("HUGE=") - 1); huge[HUGE_SIZE - 1] = '\0'; - r = LZ4_compress_default(huge, buf, HUGE_SIZE, buf_size); + r = sym_LZ4_compress_default(huge, buf, HUGE_SIZE, buf_size); assert_se(r >= 0); compressed = r; log_info("Compressed %i → %zu", HUGE_SIZE, compressed); - r = LZ4_decompress_safe(buf, huge, r, HUGE_SIZE); + r = sym_LZ4_decompress_safe(buf, huge, r, HUGE_SIZE); assert_se(r >= 0); log_info("Decompressed → %i", r); - r = LZ4_decompress_safe_partial(buf, huge, + r = sym_LZ4_decompress_safe_partial(buf, huge, compressed, 12, HUGE_SIZE); assert_se(r >= 0); @@ -258,10 +259,10 @@ static void test_lz4_decompress_partial(void) { for (size_t size = 1; size < sizeof(buf2); size++) { /* This failed in older lz4s but works in newer ones. */ - r = LZ4_decompress_safe_partial(buf, buf2, compressed, size, size); + r = sym_LZ4_decompress_safe_partial(buf, buf2, compressed, size, size); log_info("Decompressed partial %zu/%zu → %i (%s)", size, size, r, r < 0 ? "bad" : "good"); - if (r >= 0 && LZ4_versionNumber() >= 10803) + if (r >= 0 && sym_LZ4_versionNumber() >= 10803) /* lz4 <= 1.8.2 should fail that test, let's only check for newer ones */ assert_se(memcmp(buf2, huge, r) == 0); } @@ -316,28 +317,30 @@ int main(int argc, char *argv[]) { #endif #if HAVE_LZ4 - test_compress_decompress("LZ4", compress_blob_lz4, decompress_blob_lz4, - text, sizeof(text), false); - test_compress_decompress("LZ4", compress_blob_lz4, decompress_blob_lz4, - data, sizeof(data), true); - - test_decompress_startswith("LZ4", - compress_blob_lz4, decompress_startswith_lz4, - text, sizeof(text), false); - test_decompress_startswith("LZ4", - compress_blob_lz4, decompress_startswith_lz4, - data, sizeof(data), true); - test_decompress_startswith("LZ4", - compress_blob_lz4, decompress_startswith_lz4, - huge, HUGE_SIZE, true); - - test_compress_stream("LZ4", "lz4cat", - compress_stream_lz4, decompress_stream_lz4, srcfile); - - test_lz4_decompress_partial(); - - test_decompress_startswith_short("LZ4", compress_blob_lz4, decompress_startswith_lz4); - + if (dlopen_lz4() >= 0) { + test_compress_decompress("LZ4", compress_blob_lz4, decompress_blob_lz4, + text, sizeof(text), false); + test_compress_decompress("LZ4", compress_blob_lz4, decompress_blob_lz4, + data, sizeof(data), true); + + test_decompress_startswith("LZ4", + compress_blob_lz4, decompress_startswith_lz4, + text, sizeof(text), false); + test_decompress_startswith("LZ4", + compress_blob_lz4, decompress_startswith_lz4, + data, sizeof(data), true); + test_decompress_startswith("LZ4", + compress_blob_lz4, decompress_startswith_lz4, + huge, HUGE_SIZE, true); + + test_compress_stream("LZ4", "lz4cat", + compress_stream_lz4, decompress_stream_lz4, srcfile); + + test_lz4_decompress_partial(); + + test_decompress_startswith_short("LZ4", compress_blob_lz4, decompress_startswith_lz4); + } else + log_error("/* Can't load liblz4 */"); #else log_info("/* LZ4 test skipped */"); #endif diff --git a/src/test/test-condition.c b/src/test/test-condition.c index bb98761..be83690 100644 --- a/src/test/test-condition.c +++ b/src/test/test-condition.c @@ -41,7 +41,7 @@ #include "tests.h" #include "tmpfile-util.h" #include "tomoyo-util.h" -#include "uid-alloc-range.h" +#include "uid-classification.h" #include "user-util.h" #include "virt.h" @@ -139,8 +139,8 @@ TEST(condition_test_control_group_hierarchy) { int r; r = cg_unified(); - if (r == -ENOMEDIUM) { - log_tests_skipped("cgroup not mounted"); + if (IN_SET(r, -ENOMEDIUM, -ENOENT)) { + log_tests_skipped("cgroupfs is not mounted"); return; } assert_se(r >= 0); @@ -163,8 +163,8 @@ TEST(condition_test_control_group_controller) { int r; r = cg_unified(); - if (r == -ENOMEDIUM) { - log_tests_skipped("cgroup not mounted"); + if (IN_SET(r, -ENOMEDIUM, -ENOENT)) { + log_tests_skipped("cgroupfs is not mounted"); return; } assert_se(r >= 0); diff --git a/src/test/test-conf-parser.c b/src/test/test-conf-parser.c index 0acb413..4e236bd 100644 --- a/src/test/test-conf-parser.c +++ b/src/test/test-conf-parser.c @@ -3,8 +3,10 @@ #include "conf-parser.h" #include "fd-util.h" #include "fs-util.h" +#include "fileio.h" #include "log.h" #include "macro.h" +#include "mkdir.h" #include "string-util.h" #include "strv.h" #include "tests.h" @@ -14,7 +16,7 @@ static void test_config_parse_path_one(const char *rvalue, const char *expected) _cleanup_free_ char *path = NULL; assert_se(config_parse_path("unit", "filename", 1, "section", 1, "lvalue", 0, rvalue, &path, NULL) >= 0); - assert_se(streq_ptr(expected, path)); + ASSERT_STREQ(expected, path); } static void test_config_parse_log_level_one(const char *rvalue, int expected) { @@ -350,37 +352,37 @@ static void test_config_parse_one(unsigned i, const char *s) { switch (i) { case 0 ... 4: assert_se(r == 1); - assert_se(streq(setting1, "1")); + ASSERT_STREQ(setting1, "1"); break; case 5 ... 10: assert_se(r == 1); - assert_se(streq(setting1, "1 2 3")); + ASSERT_STREQ(setting1, "1 2 3"); break; case 11: assert_se(r == 1); - assert_se(streq(setting1, "1\\\\ \\\\2")); + ASSERT_STREQ(setting1, "1\\\\ \\\\2"); break; case 12: assert_se(r == 1); - assert_se(streq(setting1, x1000("ABCD"))); + ASSERT_STREQ(setting1, x1000("ABCD")); break; case 13 ... 14: assert_se(r == 1); - assert_se(streq(setting1, x1000("ABCD") " foobar")); + ASSERT_STREQ(setting1, x1000("ABCD") " foobar"); break; case 15 ... 16: assert_se(r == -ENOBUFS); - assert_se(setting1 == NULL); + ASSERT_NULL(setting1); break; case 17: assert_se(r == 1); - assert_se(streq(setting1, "2")); + ASSERT_STREQ(setting1, "2"); break; } } @@ -390,4 +392,102 @@ TEST(config_parse) { test_config_parse_one(i, config_file[i]); } +TEST(config_parse_standard_file_with_dropins_full) { + _cleanup_(rmdir_and_freep) char *root = NULL; + _cleanup_close_ int rfd = -EBADF; + int r; + + assert_se(mkdtemp_malloc(NULL, &root) >= 0); + assert_se(mkdir_p_root(root, "/etc/kernel/install.conf.d", UID_INVALID, GID_INVALID, 0755)); + assert_se(mkdir_p_root(root, "/run/kernel/install.conf.d", UID_INVALID, GID_INVALID, 0755)); + assert_se(mkdir_p_root(root, "/usr/lib/kernel/install.conf.d", UID_INVALID, GID_INVALID, 0755)); + assert_se(mkdir_p_root(root, "/usr/local/lib/kernel/install.conf.d", UID_INVALID, GID_INVALID, 0755)); + + rfd = open(root, O_CLOEXEC|O_DIRECTORY); + assert_se(rfd >= 0); + + assert_se(write_string_file_at(rfd, "usr/lib/kernel/install.conf", /* this one is ignored */ + "A=!!!", WRITE_STRING_FILE_CREATE) == 0); + assert_se(write_string_file_at(rfd, "usr/local/lib/kernel/install.conf", + "A=aaa", WRITE_STRING_FILE_CREATE) == 0); + assert_se(write_string_file_at(rfd, "usr/local/lib/kernel/install.conf.d/drop1.conf", + "B=bbb", WRITE_STRING_FILE_CREATE) == 0); + assert_se(write_string_file_at(rfd, "usr/local/lib/kernel/install.conf.d/drop2.conf", + "C=c1", WRITE_STRING_FILE_CREATE) == 0); + assert_se(write_string_file_at(rfd, "usr/lib/kernel/install.conf.d/drop2.conf", /* this one is ignored */ + "C=c2", WRITE_STRING_FILE_CREATE) == 0); + assert_se(write_string_file_at(rfd, "run/kernel/install.conf.d/drop3.conf", + "D=ddd", WRITE_STRING_FILE_CREATE) == 0); + assert_se(write_string_file_at(rfd, "etc/kernel/install.conf.d/drop4.conf", + "E=eee", WRITE_STRING_FILE_CREATE) == 0); + + _cleanup_free_ char *A = NULL, *B = NULL, *C = NULL, *D = NULL, *E = NULL, *F = NULL; + _cleanup_strv_free_ char **dropins = NULL; + + const ConfigTableItem items[] = { + { NULL, "A", config_parse_string, 0, &A}, + { NULL, "B", config_parse_string, 0, &B}, + { NULL, "C", config_parse_string, 0, &C}, + { NULL, "D", config_parse_string, 0, &D}, + { NULL, "E", config_parse_string, 0, &E}, + { NULL, "F", config_parse_string, 0, &F}, + {} + }; + + r = config_parse_standard_file_with_dropins_full( + root, "kernel/install.conf", + /* sections= */ NULL, + config_item_table_lookup, items, + CONFIG_PARSE_WARN, + /* userdata= */ NULL, + /* ret_stats_by_path= */ NULL, + /* ret_dropin_files= */ &dropins); + assert_se(r >= 0); + ASSERT_STREQ(A, "aaa"); + ASSERT_STREQ(B, "bbb"); + ASSERT_STREQ(C, "c1"); + ASSERT_STREQ(D, "ddd"); + ASSERT_STREQ(E, "eee"); + ASSERT_STREQ(F, NULL); + + A = mfree(A); + B = mfree(B); + C = mfree(C); + D = mfree(D); + E = mfree(E); + + assert_se(strv_length(dropins) == 4); + + /* Make sure that we follow symlinks */ + assert_se(mkdir_p_root(root, "/etc/kernel/install2.conf.d", UID_INVALID, GID_INVALID, 0755)); + assert_se(mkdir_p_root(root, "/run/kernel/install2.conf.d", UID_INVALID, GID_INVALID, 0755)); + assert_se(mkdir_p_root(root, "/usr/lib/kernel/install2.conf.d", UID_INVALID, GID_INVALID, 0755)); + assert_se(mkdir_p_root(root, "/usr/local/lib/kernel/install2.conf.d", UID_INVALID, GID_INVALID, 0755)); + + /* (Those symlinks are only useful relative to <root>. */ + assert_se(symlinkat("/usr/lib/kernel/install.conf", rfd, "usr/lib/kernel/install2.conf") == 0); + assert_se(symlinkat("/usr/local/lib/kernel/install.conf", rfd, "usr/local/lib/kernel/install2.conf") == 0); + assert_se(symlinkat("/usr/local/lib/kernel/install.conf.d/drop1.conf", rfd, "usr/local/lib/kernel/install2.conf.d/drop1.conf") == 0); + assert_se(symlinkat("/usr/local/lib/kernel/install.conf.d/drop2.conf", rfd, "usr/local/lib/kernel/install2.conf.d/drop2.conf") == 0); + assert_se(symlinkat("/usr/lib/kernel/install.conf.d/drop2.conf", rfd, "usr/lib/kernel/install2.conf.d/drop2.conf") == 0); + assert_se(symlinkat("/run/kernel/install.conf.d/drop3.conf", rfd, "run/kernel/install2.conf.d/drop3.conf") == 0); + assert_se(symlinkat("/etc/kernel/install.conf.d/drop4.conf", rfd, "etc/kernel/install2.conf.d/drop4.conf") == 0); + + r = config_parse_standard_file_with_dropins_full( + root, "kernel/install2.conf", + /* sections= */ NULL, + config_item_table_lookup, items, + CONFIG_PARSE_WARN, + /* userdata= */ NULL, + /* ret_stats_by_path= */ NULL, + /* ret_dropin_files= */ NULL); + assert_se(r >= 0); + ASSERT_STREQ(A, "aaa"); + ASSERT_STREQ(B, "bbb"); + ASSERT_STREQ(C, "c1"); + ASSERT_STREQ(D, "ddd"); + ASSERT_STREQ(E, "eee"); + ASSERT_STREQ(F, NULL); +} + DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-copy.c b/src/test/test-copy.c index 9674e78..7b16cf2 100644 --- a/src/test/test-copy.c +++ b/src/test/test-copy.c @@ -45,7 +45,7 @@ TEST(copy_file) { assert_se(copy_file(fn, fn_copy, 0, 0644, COPY_REFLINK) == 0); assert_se(read_full_file(fn_copy, &buf, &sz) == 0); - assert_se(streq(buf, "foo bar bar bar foo\n")); + ASSERT_STREQ(buf, "foo bar bar bar foo\n"); assert_se(sz == 20); } @@ -125,7 +125,7 @@ TEST(copy_file_fd) { assert_se(lseek(out_fd, SEEK_SET, 0) == 0); assert_se(read(out_fd, buf, sizeof buf) == (ssize_t) strlen(text)); - assert_se(streq(buf, text)); + ASSERT_STREQ(buf, text); } TEST(copy_tree) { @@ -202,7 +202,7 @@ TEST(copy_tree) { assert_se(access(f, F_OK) == 0); assert_se(read_full_file(f, &buf, &sz) == 0); - assert_se(streq(buf, "file\n")); + ASSERT_STREQ(buf, "file\n"); k = lgetxattr_malloc(f, "user.testxattr", &c); assert_se(xattr_worked < 0 || ((k >= 0) == !!xattr_worked)); @@ -211,7 +211,7 @@ TEST(copy_tree) { _cleanup_free_ char *d = NULL; assert_se(base64mem(*p, strlen(*p), &d) >= 0); - assert_se(streq(d, c)); + ASSERT_STREQ(d, c); } } @@ -253,7 +253,44 @@ TEST(copy_tree) { (void) rm_rf(original_dir, REMOVE_ROOT|REMOVE_PHYSICAL); } -TEST(copy_bytes) { +TEST(copy_tree_at_symlink) { + _cleanup_(rm_rf_physical_and_freep) char *t = NULL; + _cleanup_close_ int tfd = -EBADF, fd = -EBADF; + _cleanup_free_ char *p = NULL, *q = NULL; + const char *expect = "hgoehogefoobar"; + + tfd = mkdtemp_open(NULL, O_PATH, &t); + assert_se(tfd >= 0); + + assert_se(symlinkat(expect, tfd, "from") >= 0); + + assert_se(copy_tree_at(tfd, "from", tfd, "to_1", UID_INVALID, GID_INVALID, 0, NULL, NULL) >= 0); + assert_se(readlinkat_malloc(tfd, "to_1", &p) >= 0); + ASSERT_STREQ(p, expect); + p = mfree(p); + + assert_se(q = path_join(t, "from")); + assert_se(copy_tree_at(AT_FDCWD, q, tfd, "to_2", UID_INVALID, GID_INVALID, 0, NULL, NULL) >= 0); + assert_se(readlinkat_malloc(tfd, "to_2", &p) >= 0); + ASSERT_STREQ(p, expect); + p = mfree(p); + q = mfree(q); + + fd = openat(tfd, "from", O_CLOEXEC | O_PATH | O_NOFOLLOW); + assert_se(fd >= 0); + assert_se(copy_tree_at(fd, NULL, tfd, "to_3", UID_INVALID, GID_INVALID, 0, NULL, NULL) >= 0); + assert_se(readlinkat_malloc(tfd, "to_3", &p) >= 0); + ASSERT_STREQ(p, expect); + p = mfree(p); + + assert_se(copy_tree_at(fd, "", tfd, "to_4", UID_INVALID, GID_INVALID, 0, NULL, NULL) >= 0); + assert_se(readlinkat_malloc(tfd, "to_4", &p) >= 0); + ASSERT_STREQ(p, expect); + p = mfree(p); + fd = safe_close(fd); +} + +TEST_RET(copy_bytes) { _cleanup_close_pair_ int pipefd[2] = EBADF_PAIR; _cleanup_close_ int infd = -EBADF; int r, r2; @@ -262,7 +299,8 @@ TEST(copy_bytes) { infd = open("/usr/lib/os-release", O_RDONLY|O_CLOEXEC); if (infd < 0) infd = open("/etc/os-release", O_RDONLY|O_CLOEXEC); - assert_se(infd >= 0); + if (infd < 0) + return log_tests_skipped_errno(errno, "Could not open /usr/lib/os-release or /etc/os-release: %m"); assert_se(pipe2(pipefd, O_CLOEXEC) == 0); @@ -287,6 +325,8 @@ TEST(copy_bytes) { r = copy_bytes(pipefd[1], infd, 1, 0); assert_se(r == -EBADF); + + return 0; } static void test_copy_bytes_regular_file_one(const char *src, bool try_reflink, uint64_t max_bytes) { @@ -381,7 +421,7 @@ TEST(copy_proc) { assert_se(read_one_line_file("/proc/version", &a) >= 0); assert_se(read_one_line_file(f, &b) >= 0); - assert_se(streq(a, b)); + ASSERT_STREQ(a, b); assert_se(!isempty(a)); } @@ -404,7 +444,7 @@ TEST_RET(copy_holes) { return log_tests_skipped("Filesystem doesn't support hole punching"); assert_se(r >= 0); - assert_se(fstat(fd, &stat) >= 0); + ASSERT_OK_ERRNO(fstat(fd, &stat)); blksz = stat.st_blksize; buf = alloca_safe(blksz); memset(buf, 1, blksz); @@ -429,7 +469,7 @@ TEST_RET(copy_holes) { assert_se(lseek(fd_copy, 2 * blksz, SEEK_DATA) < 0 && errno == ENXIO); /* Test that the copied file has the correct size. */ - assert_se(fstat(fd_copy, &stat) >= 0); + ASSERT_OK_ERRNO(fstat(fd_copy, &stat)); assert_se(stat.st_size == 3 * blksz); close(fd); @@ -450,7 +490,7 @@ TEST_RET(copy_holes_with_gaps) { assert_se((fd = openat(tfd, "src", O_CREAT | O_RDWR, 0600)) >= 0); assert_se((fd_copy = openat(tfd, "dst", O_CREAT | O_WRONLY, 0600)) >= 0); - assert_se(fstat(fd, &st) >= 0); + ASSERT_OK_ERRNO(fstat(fd, &st)); blksz = st.st_blksize; buf = alloca_safe(blksz); memset(buf, 1, blksz); @@ -479,7 +519,7 @@ TEST_RET(copy_holes_with_gaps) { /* Copy to the start of the second hole */ assert_se(copy_bytes(fd, fd_copy, 3 * blksz, COPY_HOLES) >= 0); - assert_se(fstat(fd_copy, &st) >= 0); + ASSERT_OK_ERRNO(fstat(fd_copy, &st)); assert_se(st.st_size == 3 * blksz); /* Copy to the middle of the second hole */ @@ -487,7 +527,7 @@ TEST_RET(copy_holes_with_gaps) { assert_se(lseek(fd_copy, 0, SEEK_SET) >= 0); assert_se(ftruncate(fd_copy, 0) >= 0); assert_se(copy_bytes(fd, fd_copy, 4 * blksz, COPY_HOLES) >= 0); - assert_se(fstat(fd_copy, &st) >= 0); + ASSERT_OK_ERRNO(fstat(fd_copy, &st)); assert_se(st.st_size == 4 * blksz); /* Copy to the end of the second hole */ @@ -495,7 +535,7 @@ TEST_RET(copy_holes_with_gaps) { assert_se(lseek(fd_copy, 0, SEEK_SET) >= 0); assert_se(ftruncate(fd_copy, 0) >= 0); assert_se(copy_bytes(fd, fd_copy, 5 * blksz, COPY_HOLES) >= 0); - assert_se(fstat(fd_copy, &st) >= 0); + ASSERT_OK_ERRNO(fstat(fd_copy, &st)); assert_se(st.st_size == 5 * blksz); /* Copy everything */ @@ -503,7 +543,7 @@ TEST_RET(copy_holes_with_gaps) { assert_se(lseek(fd_copy, 0, SEEK_SET) >= 0); assert_se(ftruncate(fd_copy, 0) >= 0); assert_se(copy_bytes(fd, fd_copy, UINT64_MAX, COPY_HOLES) >= 0); - assert_se(fstat(fd_copy, &st) >= 0); + ASSERT_OK_ERRNO(fstat(fd_copy, &st)); assert_se(st.st_size == 6 * blksz); return 0; diff --git a/src/test/test-core-unit.c b/src/test/test-core-unit.c index dc108cc..83c8674 100644 --- a/src/test/test-core-unit.c +++ b/src/test/test-core-unit.c @@ -26,26 +26,26 @@ static void test_unit_escape_setting_one( assert_se(t = unit_escape_setting(s, 0, &a)); assert_se(a_esc = cescape(t)); log_debug("%s: [%s] → [%s]", __func__, s_esc, a_esc); - assert_se(a == NULL); + ASSERT_NULL(a); assert_se(t == s); assert_se(t = unit_escape_setting(s, UNIT_ESCAPE_EXEC_SYNTAX_ENV, &b)); assert_se(b_esc = cescape(t)); log_debug("%s: [%s] → [%s]", __func__, s_esc, b_esc); assert_se(b == NULL || streq(b, t)); - assert_se(streq(t, expected_exec_env)); + ASSERT_STREQ(t, expected_exec_env); assert_se(t = unit_escape_setting(s, UNIT_ESCAPE_EXEC_SYNTAX, &c)); assert_se(c_esc = cescape(t)); log_debug("%s: [%s] → [%s]", __func__, s_esc, c_esc); assert_se(c == NULL || streq(c, t)); - assert_se(streq(t, expected_exec)); + ASSERT_STREQ(t, expected_exec); assert_se(t = unit_escape_setting(s, UNIT_ESCAPE_C, &d)); assert_se(d_esc = cescape(t)); log_debug("%s: [%s] → [%s]", __func__, s_esc, d_esc); assert_se(d == NULL || streq(d, t)); - assert_se(streq(t, expected_c)); + ASSERT_STREQ(t, expected_c); } TEST(unit_escape_setting) { @@ -81,22 +81,22 @@ static void test_unit_concat_strv_one( assert_se(a = unit_concat_strv(s, 0)); assert_se(a_esc = cescape(a)); log_debug("%s: [%s] → [%s]", __func__, s_esc, a_esc); - assert_se(streq(a, expected_none)); + ASSERT_STREQ(a, expected_none); assert_se(b = unit_concat_strv(s, UNIT_ESCAPE_EXEC_SYNTAX_ENV)); assert_se(b_esc = cescape(b)); log_debug("%s: [%s] → [%s]", __func__, s_esc, b_esc); - assert_se(streq(b, expected_exec_env)); + ASSERT_STREQ(b, expected_exec_env); assert_se(c = unit_concat_strv(s, UNIT_ESCAPE_EXEC_SYNTAX)); assert_se(c_esc = cescape(c)); log_debug("%s: [%s] → [%s]", __func__, s_esc, c_esc); - assert_se(streq(c, expected_exec)); + ASSERT_STREQ(c, expected_exec); assert_se(d = unit_concat_strv(s, UNIT_ESCAPE_C)); assert_se(d_esc = cescape(d)); log_debug("%s: [%s] → [%s]", __func__, s_esc, d_esc); - assert_se(streq(d, expected_c)); + ASSERT_STREQ(d, expected_c); } TEST(unit_concat_strv) { diff --git a/src/test/test-cpu-set-util.c b/src/test/test-cpu-set-util.c index a0660f5..ccb52c9 100644 --- a/src/test/test-cpu-set-util.c +++ b/src/test/test-cpu-set-util.c @@ -23,7 +23,11 @@ TEST(parse_cpu_set) { str = mfree(str); assert_se(str = cpu_set_to_range_string(&c)); log_info("cpu_set_to_range_string: %s", str); - assert_se(streq(str, "0")); + ASSERT_STREQ(str, "0"); + str = mfree(str); + assert_se(str = cpu_set_to_mask_string(&c)); + log_info("cpu_set_to_mask_string: %s", str); + ASSERT_STREQ(str, "1"); str = mfree(str); cpu_set_reset(&c); @@ -41,7 +45,11 @@ TEST(parse_cpu_set) { str = mfree(str); assert_se(str = cpu_set_to_range_string(&c)); log_info("cpu_set_to_range_string: %s", str); - assert_se(streq(str, "1-2 4")); + ASSERT_STREQ(str, "1-2 4"); + str = mfree(str); + assert_se(str = cpu_set_to_mask_string(&c)); + log_info("cpu_set_to_mask_string: %s", str); + ASSERT_STREQ(str, "16"); str = mfree(str); cpu_set_reset(&c); @@ -59,7 +67,11 @@ TEST(parse_cpu_set) { str = mfree(str); assert_se(str = cpu_set_to_range_string(&c)); log_info("cpu_set_to_range_string: %s", str); - assert_se(streq(str, "0-3 8-11")); + ASSERT_STREQ(str, "0-3 8-11"); + str = mfree(str); + assert_se(str = cpu_set_to_mask_string(&c)); + log_info("cpu_set_to_mask_string: %s", str); + ASSERT_STREQ(str, "f0f"); str = mfree(str); cpu_set_reset(&c); @@ -74,7 +86,11 @@ TEST(parse_cpu_set) { str = mfree(str); assert_se(str = cpu_set_to_range_string(&c)); log_info("cpu_set_to_range_string: %s", str); - assert_se(streq(str, "8-11")); + ASSERT_STREQ(str, "8-11"); + str = mfree(str); + assert_se(str = cpu_set_to_mask_string(&c)); + log_info("cpu_set_to_mask_string: %s", str); + ASSERT_STREQ(str, "f00"); str = mfree(str); cpu_set_reset(&c); @@ -104,7 +120,11 @@ TEST(parse_cpu_set) { str = mfree(str); assert_se(str = cpu_set_to_range_string(&c)); log_info("cpu_set_to_range_string: %s", str); - assert_se(streq(str, "0-7 63")); + ASSERT_STREQ(str, "0-7 63"); + str = mfree(str); + assert_se(str = cpu_set_to_mask_string(&c)); + log_info("cpu_set_to_mask_string: %s", str); + ASSERT_STREQ(str, "80000000,000000ff"); str = mfree(str); cpu_set_reset(&c); @@ -120,6 +140,28 @@ TEST(parse_cpu_set) { log_info("cpu_set_to_string: %s", str); str = mfree(str); cpu_set_reset(&c); + assert_se(parse_cpu_set_full("36-39,44-47", &c, true, NULL, "fake", 1, "CPUAffinity") >= 0); + assert_se(c.allocated >= DIV_ROUND_UP(sizeof(__cpu_mask), 8)); + assert_se(CPU_COUNT_S(c.allocated, c.set) == 8); + for (cpu = 36; cpu < 40; cpu++) + assert_se(CPU_ISSET_S(cpu, c.allocated, c.set)); + for (cpu = 44; cpu < 48; cpu++) + assert_se(CPU_ISSET_S(cpu, c.allocated, c.set)); + assert_se(str = cpu_set_to_mask_string(&c)); + log_info("cpu_set_to_mask_string: %s", str); + ASSERT_STREQ(str, "f0f0,00000000"); + str = mfree(str); + cpu_set_reset(&c); + assert_se(parse_cpu_set_full("64-71", &c, true, NULL, "fake", 1, "CPUAffinity") >= 0); + assert_se(c.allocated >= DIV_ROUND_UP(sizeof(__cpu_mask), 8)); + assert_se(CPU_COUNT_S(c.allocated, c.set) == 8); + for (cpu = 64; cpu < 72; cpu++) + assert_se(CPU_ISSET_S(cpu, c.allocated, c.set)); + assert_se(str = cpu_set_to_mask_string(&c)); + log_info("cpu_set_to_mask_string: %s", str); + ASSERT_STREQ(str, "ff,00000000,00000000"); + str = mfree(str); + cpu_set_reset(&c); /* Ranges with trailing comma, space */ assert_se(parse_cpu_set_full("0-3 8-11, ", &c, true, NULL, "fake", 1, "CPUAffinity") >= 0); @@ -134,7 +176,11 @@ TEST(parse_cpu_set) { str = mfree(str); assert_se(str = cpu_set_to_range_string(&c)); log_info("cpu_set_to_range_string: %s", str); - assert_se(streq(str, "0-3 8-11")); + ASSERT_STREQ(str, "0-3 8-11"); + str = mfree(str); + assert_se(str = cpu_set_to_mask_string(&c)); + log_info("cpu_set_to_mask_string: %s", str); + ASSERT_STREQ(str, "f0f"); str = mfree(str); cpu_set_reset(&c); @@ -142,6 +188,10 @@ TEST(parse_cpu_set) { assert_se(parse_cpu_set_full("3-0", &c, true, NULL, "fake", 1, "CPUAffinity") >= 0); assert_se(c.allocated >= DIV_ROUND_UP(sizeof(__cpu_mask), 8)); assert_se(CPU_COUNT_S(c.allocated, c.set) == 0); + assert_se(str = cpu_set_to_mask_string(&c)); + log_info("cpu_set_to_mask_string: %s", str); + ASSERT_STREQ(str, "0"); + str = mfree(str); cpu_set_reset(&c); /* Overlapping ranges */ @@ -155,7 +205,11 @@ TEST(parse_cpu_set) { str = mfree(str); assert_se(str = cpu_set_to_range_string(&c)); log_info("cpu_set_to_range_string: %s", str); - assert_se(streq(str, "0-11")); + ASSERT_STREQ(str, "0-11"); + str = mfree(str); + assert_se(str = cpu_set_to_mask_string(&c)); + log_info("cpu_set_to_mask_string: %s", str); + ASSERT_STREQ(str, "fff"); str = mfree(str); cpu_set_reset(&c); @@ -172,7 +226,11 @@ TEST(parse_cpu_set) { str = mfree(str); assert_se(str = cpu_set_to_range_string(&c)); log_info("cpu_set_to_range_string: %s", str); - assert_se(streq(str, "0 2 4-11")); + ASSERT_STREQ(str, "0 2 4-11"); + str = mfree(str); + assert_se(str = cpu_set_to_mask_string(&c)); + log_info("cpu_set_to_mask_string: %s", str); + ASSERT_STREQ(str, "ff5"); str = mfree(str); cpu_set_reset(&c); @@ -190,6 +248,10 @@ TEST(parse_cpu_set) { assert_se(parse_cpu_set_full("", &c, true, NULL, "fake", 1, "CPUAffinity") == 0); assert_se(!c.set); /* empty string returns NULL */ assert_se(c.allocated == 0); + assert_se(str = cpu_set_to_mask_string(&c)); + log_info("cpu_set_to_mask_string: %s", str); + ASSERT_STREQ(str, "0"); + str = mfree(str); /* Runaway quoted string */ assert_se(parse_cpu_set_full("0 1 2 3 \"4 5 6 7 ", &c, true, NULL, "fake", 1, "CPUAffinity") == -EINVAL); @@ -204,7 +266,24 @@ TEST(parse_cpu_set) { str = mfree(str); assert_se(str = cpu_set_to_range_string(&c)); log_info("cpu_set_to_range_string: %s", str); - assert_se(streq(str, "8000-8191")); + ASSERT_STREQ(str, "8000-8191"); + str = mfree(str); + assert_se(str = cpu_set_to_mask_string(&c)); + log_info("cpu_set_to_mask_string: %s", str); + for (size_t i = 0; i < strlen(str); i++) { + if (i < 54) { + if (i >= 8 && (i + 1) % 9 == 0) + assert_se(str[i] == ','); + else + assert_se(str[i] == 'f'); + } + else { + if (i >= 8 && (i + 1) % 9 == 0) + assert_se(str[i] == ','); + else + assert_se(str[i] == '0'); + } + } str = mfree(str); cpu_set_reset(&c); } diff --git a/src/test/test-creds.c b/src/test/test-creds.c index acb198c..cc9cc73 100644 --- a/src/test/test-creds.c +++ b/src/test/test-creds.c @@ -2,10 +2,16 @@ #include "creds-util.h" #include "fileio.h" +#include "format-util.h" +#include "hexdecoct.h" +#include "id128-util.h" +#include "iovec-util.h" #include "path-util.h" #include "rm-rf.h" #include "tests.h" #include "tmpfile-util.h" +#include "tpm2-util.h" +#include "user-util.h" TEST(read_credential_strings) { _cleanup_free_ char *x = NULL, *y = NULL, *saved = NULL, *p = NULL; @@ -17,43 +23,37 @@ TEST(read_credential_strings) { assert_se(saved = strdup(e)); assert_se(read_credential_strings_many("foo", &x, "bar", &y) == 0); - assert_se(x == NULL); - assert_se(y == NULL); + ASSERT_NULL(x); + ASSERT_NULL(y); assert_se(mkdtemp_malloc(NULL, &tmp) >= 0); assert_se(setenv("CREDENTIALS_DIRECTORY", tmp, /* override= */ true) >= 0); assert_se(read_credential_strings_many("foo", &x, "bar", &y) == 0); - assert_se(x == NULL); - assert_se(y == NULL); + ASSERT_NULL(x); + ASSERT_NULL(y); assert_se(p = path_join(tmp, "bar")); assert_se(write_string_file(p, "piff", WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_AVOID_NEWLINE) >= 0); assert_se(read_credential_strings_many("foo", &x, "bar", &y) == 0); - assert_se(x == NULL); - assert_se(streq(y, "piff")); + ASSERT_NULL(x); + ASSERT_STREQ(y, "piff"); assert_se(write_string_file(p, "paff", WRITE_STRING_FILE_TRUNCATE|WRITE_STRING_FILE_AVOID_NEWLINE) >= 0); assert_se(read_credential_strings_many("foo", &x, "bar", &y) == 0); - assert_se(x == NULL); - assert_se(streq(y, "piff")); + ASSERT_NULL(x); + ASSERT_STREQ(y, "paff"); p = mfree(p); assert_se(p = path_join(tmp, "foo")); assert_se(write_string_file(p, "knurz", WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_AVOID_NEWLINE) >= 0); assert_se(read_credential_strings_many("foo", &x, "bar", &y) >= 0); - assert_se(streq(x, "knurz")); - assert_se(streq(y, "piff")); - - y = mfree(y); - - assert_se(read_credential_strings_many("foo", &x, "bar", &y) >= 0); - assert_se(streq(x, "knurz")); - assert_se(streq(y, "paff")); + ASSERT_STREQ(x, "knurz"); + ASSERT_STREQ(y, "paff"); p = mfree(p); assert_se(p = path_join(tmp, "bazz")); @@ -61,9 +61,11 @@ TEST(read_credential_strings) { assert_se(fwrite("x\0y", 1, 3, f) == 3); /* embedded NUL byte should result in EBADMSG when reading back with read_credential_strings_many() */ f = safe_fclose(f); - assert_se(read_credential_strings_many("bazz", &x, "foo", &y) == -EBADMSG); - assert_se(streq(x, "knurz")); - assert_se(streq(y, "paff")); + y = mfree(y); + + assert_se(read_credential_strings_many("bazz", &x, "bar", &y) == -EBADMSG); + ASSERT_STREQ(x, "knurz"); + ASSERT_STREQ(y, "paff"); if (saved) assert_se(setenv("CREDENTIALS_DIRECTORY", saved, /* override= */ 1) >= 0); @@ -118,4 +120,142 @@ TEST(credential_glob_valid) { assert_se(credential_glob_valid(buf)); } +static void test_encrypt_decrypt_with(sd_id128_t mode, uid_t uid) { + static const struct iovec plaintext = CONST_IOVEC_MAKE_STRING("this is a super secret string"); + int r; + + if (uid_is_valid(uid)) + log_notice("Running encryption/decryption test with mode " SD_ID128_FORMAT_STR " for UID " UID_FMT ".", SD_ID128_FORMAT_VAL(mode), uid); + else + log_notice("Running encryption/decryption test with mode " SD_ID128_FORMAT_STR ".", SD_ID128_FORMAT_VAL(mode)); + + _cleanup_(iovec_done) struct iovec encrypted = {}; + r = encrypt_credential_and_warn( + mode, + "foo", + /* timestamp= */ USEC_INFINITY, + /* not_after=*/ USEC_INFINITY, + /* tpm2_device= */ NULL, + /* tpm2_hash_pcr_mask= */ 0, + /* tpm2_pubkey_path= */ NULL, + /* tpm2_pubkey_pcr_mask= */ 0, + uid, + &plaintext, + CREDENTIAL_ALLOW_NULL, + &encrypted); + if (ERRNO_IS_NEG_MACHINE_ID_UNSET(r)) { + log_notice_errno(r, "Skipping test encryption mode " SD_ID128_FORMAT_STR ", because /etc/machine-id is not initialized.", SD_ID128_FORMAT_VAL(mode)); + return; + } + if (ERRNO_IS_NEG_NOT_SUPPORTED(r)) { + log_notice_errno(r, "Skipping test encryption mode " SD_ID128_FORMAT_STR ", because encrypted credentials are not supported.", SD_ID128_FORMAT_VAL(mode)); + return; + } + + assert_se(r >= 0); + + _cleanup_(iovec_done) struct iovec decrypted = {}; + r = decrypt_credential_and_warn( + "bar", + /* validate_timestamp= */ USEC_INFINITY, + /* tpm2_device= */ NULL, + /* tpm2_signature_path= */ NULL, + uid, + &encrypted, + CREDENTIAL_ALLOW_NULL, + &decrypted); + assert_se(r == -EREMOTE); /* name didn't match */ + + r = decrypt_credential_and_warn( + "foo", + /* validate_timestamp= */ USEC_INFINITY, + /* tpm2_device= */ NULL, + /* tpm2_signature_path= */ NULL, + uid, + &encrypted, + CREDENTIAL_ALLOW_NULL, + &decrypted); + assert_se(r >= 0); + + assert_se(iovec_memcmp(&plaintext, &decrypted) == 0); +} + +static bool try_tpm2(void) { +#if HAVE_TPM2 + _cleanup_(tpm2_context_unrefp) Tpm2Context *tpm2_context = NULL; + int r; + + r = tpm2_context_new(/* device= */ NULL, &tpm2_context); + if (r < 0) + log_notice_errno(r, "Failed to create TPM2 context, assuming no TPM2 support or privileges: %m"); + + return r >= 0; +#else + return false; +#endif +} + +TEST(credential_encrypt_decrypt) { + _cleanup_(rm_rf_physical_and_freep) char *d = NULL; + _cleanup_free_ char *j = NULL; + + log_set_max_level(LOG_DEBUG); + + test_encrypt_decrypt_with(CRED_AES256_GCM_BY_NULL, UID_INVALID); + + assert_se(mkdtemp_malloc(NULL, &d) >= 0); + j = path_join(d, "secret"); + assert_se(j); + + const char *e = getenv("SYSTEMD_CREDENTIAL_SECRET"); + _cleanup_free_ char *ec = NULL; + + if (e) + assert_se(ec = strdup(e)); + + assert_se(setenv("SYSTEMD_CREDENTIAL_SECRET", j, true) >= 0); + + test_encrypt_decrypt_with(CRED_AES256_GCM_BY_HOST, UID_INVALID); + test_encrypt_decrypt_with(CRED_AES256_GCM_BY_HOST_SCOPED, 0); + + if (try_tpm2()) { + test_encrypt_decrypt_with(CRED_AES256_GCM_BY_TPM2_HMAC, UID_INVALID); + test_encrypt_decrypt_with(CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC, UID_INVALID); + test_encrypt_decrypt_with(CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_SCOPED, 0); + } + + if (ec) + assert_se(setenv("SYSTEMD_CREDENTIAL_SECRET", ec, true) >= 0); +} + +TEST(mime_type_matches) { + + static const sd_id128_t tags[] = { + CRED_AES256_GCM_BY_HOST, + CRED_AES256_GCM_BY_HOST_SCOPED, + CRED_AES256_GCM_BY_TPM2_HMAC, + CRED_AES256_GCM_BY_TPM2_HMAC_WITH_PK, + CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC, + CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_SCOPED, + CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK, + CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK_SCOPED, + CRED_AES256_GCM_BY_NULL, + }; + + /* Generates the right <match/> expressions for these credentials according to the shared mime-info spec */ + FOREACH_ELEMENT(t, tags) { + _cleanup_free_ char *encoded = NULL; + + assert_se(base64mem(t, sizeof(sd_id128_t), &encoded) >= 0); + + /* Validate that the size matches expectations for the 4/3 factor size increase (rounding up) */ + assert_se(strlen(encoded) == DIV_ROUND_UP((128U / 8U), 3U) * 4U); + + /* Cut off rounded string where the ID ends, but now round down to get rid of characters that might contain follow-up data */ + encoded[128 / 6] = 0; + + printf("<match type=\"string\" value=\"%s\" offset=\"0\"/>\n", encoded); + } +} + DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-cryptolib.c b/src/test/test-cryptolib.c index 6202a5d..9f9be4d 100644 --- a/src/test/test-cryptolib.c +++ b/src/test/test-cryptolib.c @@ -14,25 +14,25 @@ TEST(string_hashsum) { OPENSSL_OR_GCRYPT("SHA224", GCRY_MD_SHA224), &out1) == 0); /* echo -n 'asdf' | sha224sum - */ - assert_se(streq(out1, "7872a74bcbf298a1e77d507cd95d4f8d96131cbbd4cdfc571e776c8a")); + ASSERT_STREQ(out1, "7872a74bcbf298a1e77d507cd95d4f8d96131cbbd4cdfc571e776c8a"); assert_se(string_hashsum("asdf", 4, OPENSSL_OR_GCRYPT("SHA256", GCRY_MD_SHA256), &out2) == 0); /* echo -n 'asdf' | sha256sum - */ - assert_se(streq(out2, "f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b")); + ASSERT_STREQ(out2, "f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b"); assert_se(string_hashsum("", 0, OPENSSL_OR_GCRYPT("SHA224", GCRY_MD_SHA224), &out3) == 0); /* echo -n '' | sha224sum - */ - assert_se(streq(out3, "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")); + ASSERT_STREQ(out3, "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f"); assert_se(string_hashsum("", 0, OPENSSL_OR_GCRYPT("SHA256", GCRY_MD_SHA256), &out4) == 0); /* echo -n '' | sha256sum - */ - assert_se(streq(out4, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")); + ASSERT_STREQ(out4, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); } DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-data-fd-util.c b/src/test/test-data-fd-util.c index aa68132..4abd7a6 100644 --- a/src/test/test-data-fd-util.c +++ b/src/test/test-data-fd-util.c @@ -17,27 +17,27 @@ static void test_acquire_data_fd_one(unsigned flags) { char rbuffer[sizeof(wbuffer)]; int fd; - fd = acquire_data_fd("foo", 3, flags); + fd = acquire_data_fd_full("foo", 3, flags); assert_se(fd >= 0); zero(rbuffer); assert_se(read(fd, rbuffer, sizeof(rbuffer)) == 3); - assert_se(streq(rbuffer, "foo")); + ASSERT_STREQ(rbuffer, "foo"); fd = safe_close(fd); - fd = acquire_data_fd("", 0, flags); + fd = acquire_data_fd_full("", SIZE_MAX, flags); assert_se(fd >= 0); zero(rbuffer); assert_se(read(fd, rbuffer, sizeof(rbuffer)) == 0); - assert_se(streq(rbuffer, "")); + ASSERT_STREQ(rbuffer, ""); fd = safe_close(fd); random_bytes(wbuffer, sizeof(wbuffer)); - fd = acquire_data_fd(wbuffer, sizeof(wbuffer), flags); + fd = acquire_data_fd_full(wbuffer, sizeof(wbuffer), flags); assert_se(fd >= 0); zero(rbuffer); @@ -98,14 +98,14 @@ TEST(copy_data_fd) { fd1 = safe_close(fd1); fd2 = safe_close(fd2); - fd1 = acquire_data_fd("hallo", 6, 0); + fd1 = acquire_data_fd("hallo"); assert_se(fd1 >= 0); fd2 = copy_data_fd(fd1); assert_se(fd2 >= 0); safe_close(fd1); - fd1 = acquire_data_fd("hallo", 6, 0); + fd1 = acquire_data_fd("hallo"); assert_se(fd1 >= 0); assert_equal_fd(fd1, fd2); diff --git a/src/test/test-date.c b/src/test/test-date.c index 162ac34..c7d239e 100644 --- a/src/test/test-date.c +++ b/src/test/test-date.c @@ -1,5 +1,7 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ +#include <unistd.h> + #include "alloc-util.h" #include "string-util.h" #include "tests.h" @@ -83,9 +85,11 @@ int main(int argc, char *argv[]) { test_one("today"); test_one("tomorrow"); test_one_noutc("16:20 UTC"); - test_one_noutc("16:20 Asia/Seoul"); - test_one_noutc("tomorrow Asia/Seoul"); - test_one_noutc("2012-12-30 18:42 Asia/Seoul"); + if (access("/usr/share/zoneinfo/Asia/Seoul", F_OK) >= 0) { + test_one_noutc("16:20 Asia/Seoul"); + test_one_noutc("tomorrow Asia/Seoul"); + test_one_noutc("2012-12-30 18:42 Asia/Seoul"); + } test_one_noutc("now"); test_one_noutc("+2d"); test_one_noutc("+2y 4d"); @@ -96,9 +100,11 @@ int main(int argc, char *argv[]) { test_should_fail("1969-12-31 UTC"); test_should_fail("-1000y"); test_should_fail("today UTC UTC"); - test_should_fail("now Asia/Seoul"); - test_should_fail("+2d Asia/Seoul"); - test_should_fail("@1395716396 Asia/Seoul"); + if (access("/usr/share/zoneinfo/Asia/Seoul", F_OK) >= 0) { + test_should_fail("now Asia/Seoul"); + test_should_fail("+2d Asia/Seoul"); + test_should_fail("@1395716396 Asia/Seoul"); + } #if SIZEOF_TIME_T == 8 test_should_pass("9999-12-30 23:59:59 UTC"); test_should_fail("9999-12-31 00:00:00 UTC"); diff --git a/src/test/test-dev-setup.c b/src/test/test-dev-setup.c index b75576a..ed56710 100644 --- a/src/test/test-dev-setup.c +++ b/src/test/test-dev-setup.c @@ -25,6 +25,7 @@ int main(int argc, char *argv[]) { assert_se(mkdir_p(f, 0755) >= 0); assert_se(make_inaccessible_nodes(f, 1, 1) >= 0); + assert_se(make_inaccessible_nodes(f, 1, 1) >= 0); /* 2nd call should be a clean NOP */ f = prefix_roota(p, "/run/systemd/inaccessible/reg"); assert_se(stat(f, &st) >= 0); diff --git a/src/test/test-devnum-util.c b/src/test/test-devnum-util.c index 2068e35..ebef794 100644 --- a/src/test/test-devnum-util.c +++ b/src/test/test-devnum-util.c @@ -109,7 +109,7 @@ TEST(device_path_make_canonical) { static void test_devnum_format_str_one(dev_t devnum, const char *s) { dev_t x; - assert_se(streq(FORMAT_DEVNUM(devnum), s)); + ASSERT_STREQ(FORMAT_DEVNUM(devnum), s); assert_se(parse_devnum(s, &x) >= 0); assert_se(x == devnum); } diff --git a/src/test/test-dirent-util.c b/src/test/test-dirent-util.c new file mode 100644 index 0000000..420ccd1 --- /dev/null +++ b/src/test/test-dirent-util.c @@ -0,0 +1,218 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include <dirent.h> +#include <fcntl.h> +#include <stdio.h> +#include <sys/stat.h> + +#include "alloc-util.h" +#include "dirent-util.h" +#include "fs-util.h" +#include "mkdir.h" +#include "path-util.h" +#include "rm-rf.h" +#include "stat-util.h" +#include "string-util.h" +#include "tmpfile-util.h" +#include "tests.h" + +TEST (test_dirent_ensure_type) { + int r, dir_fd; + static struct dirent de = { + .d_type = DT_UNKNOWN, + .d_name = "test", + }; + + dir_fd = 0; + assert_se(dirent_ensure_type(dir_fd, &de) == -ENOTDIR); + + /* Test when d_name is "." or ".." */ + strcpy(de.d_name, "."); + r = dirent_ensure_type(dir_fd, &de); + assert_se(r == 0); + assert_se(de.d_type == DT_DIR); + + strcpy(de.d_name, ".."); + r = dirent_ensure_type(dir_fd, &de); + assert_se(r == 0); + assert_se(de.d_type == DT_DIR); +} + +TEST (test_dirent_is_file) { + _cleanup_(rm_rf_physical_and_freep) char *t = NULL; + const char *name, *dotfile, *name_alias, *bakfile, *tilda; + const struct dirent *de_reg, *de_lnk, *de_dot, *de_bak, *de_tilda; + DIR *dir; + + static const struct dirent de_unknown = { + .d_type = DT_UNKNOWN, + .d_name = "test_unknown", + }; + + assert_se(mkdtemp_malloc(NULL, &t) >= 0); + + name = strjoina(t, "/test.txt"); + dotfile = strjoina(t, "/.hidden_file"); + bakfile = strjoina(t, "/test.bak"); + tilda = strjoina(t, "/test~"); + name_alias = strjoina(t, "/test_link"); + + assert_se(touch(name) >= 0); + assert_se(touch(dotfile) >= 0); + assert_se(touch(bakfile) >= 0); + assert_se(touch(tilda) >= 0); + + if (symlink(name, name_alias) < 0) { + assert_se(IN_SET(errno, EINVAL, ENOSYS, ENOTTY, EPERM)); + log_tests_skipped_errno(errno, "symlink() not possible"); + } + + dir = opendir(t); + if (!dir) { + log_error_errno(errno, "Failed to open directory '%s': %m", t); + exit(EXIT_FAILURE); + } + + rewinddir(dir); + while ((de_reg = readdir_ensure_type(dir))) + if (streq(de_reg->d_name, "test.txt")) + break; + + rewinddir(dir); + while ((de_lnk = readdir_ensure_type(dir))) + if (streq(de_lnk->d_name, "test_link")) + break; + + rewinddir(dir); + while ((de_dot = readdir_ensure_type(dir))) + if (streq(de_dot->d_name, ".hidden_file")) + break; + + rewinddir(dir); + while ((de_bak = readdir(dir))) + if (streq(de_bak->d_name, "test.bak")) + break; + + rewinddir(dir); + while ((de_tilda = readdir(dir))) + if (streq(de_tilda->d_name, "test~")) + break; + + /* Test when d_type is DT_REG, DT_LNK, or DT_UNKNOWN */ + assert_se(dirent_is_file(de_reg) == true); + if (de_lnk) + assert_se(dirent_is_file(de_lnk) == true); + else + log_tests_skipped("de_lnk is NULL, skipping test"); + assert_se(dirent_is_file(&de_unknown) == true); + + /* Test for hidden files */ + assert_se(dirent_is_file(de_dot) == false); + assert_se(dirent_is_file(de_bak) == false); + assert_se(dirent_is_file(de_tilda) == false); + + closedir(dir); +} + +TEST (test_dirent_is_file_with_suffix) { + _cleanup_(rm_rf_physical_and_freep) char *t = NULL; + const char *name, *dotfile, *name_alias, *dotdot, *chr; + const struct dirent *de_reg, *de_lnk, *de_dot, *de_dotdot, *de_chr; + DIR *dir; + + static const struct dirent de_unknown = { + .d_type = DT_UNKNOWN, + .d_name = "test_unknown", + }; + + assert_se(mkdtemp_malloc(NULL, &t) >= 0); + + name = strjoina(t, "/test.txt"); + dotfile = strjoina(t, "/.hidden_file"); + dotdot = strjoina(t, "/..dotdot"); + chr = strjoina(t, "/test_chr"); + name_alias = strjoina(t, "/test_link"); + + assert_se(touch(name) >= 0); + assert_se(touch(dotfile) >= 0); + assert_se(touch(dotdot) >= 0); + /* This can fail in containers/build systems */ + if (mknod(chr, 0775 | S_IFCHR, makedev(0, 0)) < 0) { + assert(ERRNO_IS_PRIVILEGE(errno)); + chr = NULL; + } + + if (symlink(name, name_alias) < 0) { + assert_se(IN_SET(errno, EINVAL, ENOSYS, ENOTTY, EPERM)); + log_tests_skipped_errno(errno, "symlink() not possible"); + } + + dir = opendir(t); + if (!dir) { + log_error_errno(errno, "Failed to open directory '%s': %m", t); + exit(EXIT_FAILURE); + } + + rewinddir(dir); + while ((de_reg = readdir_ensure_type(dir))) + if (streq(de_reg->d_name, "test.txt")) + break; + + rewinddir(dir); + while ((de_lnk = readdir_ensure_type(dir))) + if (streq(de_lnk->d_name, "test_link")) + break; + + rewinddir(dir); + while ((de_dot = readdir_ensure_type(dir))) + if (streq(de_dot->d_name, ".hidden_file")) + break; + + rewinddir(dir); + while ((de_dotdot = readdir(dir))) + if (streq(de_dotdot->d_name, "..dotdot")) + break; + + if (chr) { + rewinddir(dir); + while ((de_chr = readdir(dir))) + if (streq(de_chr->d_name, "test_chr")) + break; + + /* Test when d_type is not DT_REG, DT_LNK, or DT_UNKNOWN */ + assert(de_chr); + assert_se(!dirent_is_file_with_suffix(de_chr, NULL)); + } + + /* Test when suffix is NULL */ + assert_se(dirent_is_file_with_suffix(de_reg, NULL) == true); + if (de_lnk) + assert_se(dirent_is_file_with_suffix(de_lnk, NULL) == true); + else + log_tests_skipped("de_lnk is NULL, skipping test"); + assert_se(dirent_is_file_with_suffix(&de_unknown, NULL) == true); + + /* Test for present suffix */ + assert_se(dirent_is_file_with_suffix(de_reg, "txt") == true); + if (de_lnk) + assert_se(dirent_is_file_with_suffix(de_lnk, "link") == true); + else + log_tests_skipped("de_lnk is NULL, skipping test"); + assert_se(dirent_is_file_with_suffix(&de_unknown, "unknown") == true); + + /* Test for absent suffix */ + assert_se(dirent_is_file_with_suffix(de_reg, "svg") == false); + if (de_lnk) + assert_se(dirent_is_file_with_suffix(de_lnk, "pdf") == false); + else + log_tests_skipped("de_lnk is NULL, skipping test"); + assert_se(dirent_is_file_with_suffix(&de_unknown, "yes") == false); + + /* Test for dot and dot-dot */ + assert_se(dirent_is_file_with_suffix(de_dot, NULL) == false); + assert_se(dirent_is_file_with_suffix(de_dotdot, NULL) == false); + + closedir(dir); +} + +DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-dlopen-so.c b/src/test/test-dlopen-so.c index e98b8da..d38dff1 100644 --- a/src/test/test-dlopen-so.c +++ b/src/test/test-dlopen-so.c @@ -4,12 +4,16 @@ #include <stdlib.h> #include "bpf-dlopen.h" +#include "compress.h" #include "cryptsetup-util.h" #include "elf-util.h" +#include "gcrypt-util.h" #include "idn-util.h" +#include "libarchive-util.h" #include "libfido2-util.h" #include "macro.h" #include "main-func.h" +#include "module-util.h" #include "password-quality-util-passwdqc.h" #include "password-quality-util-pwquality.h" #include "pcre2-util.h" @@ -70,6 +74,30 @@ static int run(int argc, char **argv) { assert_se(dlopen_p11kit() >= 0); #endif +#if HAVE_LIBARCHIVE + assert_se(dlopen_libarchive() >= 0); +#endif + +#if HAVE_LZ4 + assert_se(dlopen_lz4() >= 0); +#endif + +#if HAVE_ZSTD + assert_se(dlopen_zstd() >= 0); +#endif + +#if HAVE_XZ + assert_se(dlopen_lzma() >= 0); +#endif + +#if HAVE_GCRYPT + assert_se(initialize_libgcrypt(/* secmem= */ false) >= 0); +#endif + +#if HAVE_KMOD + assert_se(dlopen_libkmod() >= 0); +#endif + return 0; } diff --git a/src/test/test-dns-domain.c b/src/test/test-dns-domain.c index 6c107e2..d775601 100644 --- a/src/test/test-dns-domain.c +++ b/src/test/test-dns-domain.c @@ -16,20 +16,20 @@ static void test_dns_label_unescape_one(const char *what, const char *expect, si r = dns_label_unescape(&w, buffer, buffer_sz, 0); assert_se(r == ret); if (r >= 0) - assert_se(streq(buffer, expect)); + ASSERT_STREQ(buffer, expect); w = what; r = dns_label_unescape(&w, buffer, buffer_sz, DNS_LABEL_LDH); assert_se(r == ret_ldh); if (r >= 0) - assert_se(streq(buffer, expect)); + ASSERT_STREQ(buffer, expect); w = what; r = dns_label_unescape(&w, buffer, buffer_sz, DNS_LABEL_NO_ESCAPES); const int ret_noe = strchr(what, '\\') ? -EINVAL : ret; assert_se(r == ret_noe); if (r >= 0) - assert_se(streq(buffer, expect)); + ASSERT_STREQ(buffer, expect); } TEST(dns_label_unescape) { @@ -131,12 +131,12 @@ static void test_dns_label_unescape_suffix_one(const char *what, const char *exp r = dns_label_unescape_suffix(what, &label, buffer, buffer_sz); assert_se(r == ret1); if (r >= 0) - assert_se(streq(buffer, expect1)); + ASSERT_STREQ(buffer, expect1); r = dns_label_unescape_suffix(what, &label, buffer, buffer_sz); assert_se(r == ret2); if (r >= 0) - assert_se(streq(buffer, expect2)); + ASSERT_STREQ(buffer, expect2); } TEST(dns_label_unescape_suffix) { @@ -173,7 +173,7 @@ static void test_dns_label_escape_one(const char *what, size_t l, const char *ex if (r < 0) return; - assert_se(streq_ptr(expect, t)); + ASSERT_STREQ(expect, t); } TEST(dns_label_escape) { @@ -193,7 +193,7 @@ static void test_dns_name_normalize_one(const char *what, const char *expect, in if (r < 0) return; - assert_se(streq_ptr(expect, t)); + ASSERT_STREQ(expect, t); } TEST(dns_name_normalize) { @@ -332,7 +332,7 @@ static void test_dns_name_reverse_one(const char *address, const char *name) { assert_se(in_addr_from_string_auto(address, &familya, &a) >= 0); assert_se(dns_name_reverse(familya, &a, &p) >= 0); - assert_se(streq(p, name)); + ASSERT_STREQ(p, name); assert_se(dns_name_address(p, &familyb, &b) > 0); assert_se(familya == familyb); assert_se(in_addr_equal(familya, &a, &b)); @@ -349,7 +349,7 @@ static void test_dns_name_concat_one(const char *a, const char *b, int r, const _cleanup_free_ char *p = NULL; assert_se(dns_name_concat(a, b, 0, &p) == r); - assert_se(streq_ptr(p, result)); + ASSERT_STREQ(p, result); } TEST(dns_name_concat) { @@ -486,14 +486,14 @@ static void test_dns_service_join_one(const char *a, const char *b, const char * log_info("%s, %s, %s, →%d, %s", strnull(a), strnull(b), strnull(c), r, strnull(d)); assert_se(dns_service_join(a, b, c, &t) == r); - assert_se(streq_ptr(t, d)); + ASSERT_STREQ(t, d); if (r < 0) return; assert_se(dns_service_split(t, &x, &y, &z) >= 0); - assert_se(streq_ptr(a, x)); - assert_se(streq_ptr(b, y)); + ASSERT_STREQ(a, x); + ASSERT_STREQ(b, y); assert_se(dns_name_equal(c, z) > 0); } @@ -518,9 +518,9 @@ static void test_dns_service_split_one(const char *joined, const char *a, const log_info("%s, %s, %s, %s, →%d", joined, strnull(a), strnull(b), strnull(c), r); assert_se(dns_service_split(joined, &x, &y, &z) == r); - assert_se(streq_ptr(x, a)); - assert_se(streq_ptr(y, b)); - assert_se(streq_ptr(z, c)); + ASSERT_STREQ(x, a); + ASSERT_STREQ(y, b); + ASSERT_STREQ(z, c); if (r < 0) return; @@ -549,7 +549,7 @@ static void test_dns_name_change_suffix_one(const char *name, const char *old_su log_info("%s, %s, %s, →%s", name, old_suffix, new_suffix, strnull(result)); assert_se(dns_name_change_suffix(name, old_suffix, new_suffix, &s) == r); - assert_se(streq_ptr(s, result)); + ASSERT_STREQ(s, result); } TEST(dns_name_change_suffix) { @@ -570,7 +570,7 @@ static void test_dns_name_suffix_one(const char *name, unsigned n_labels, const log_info("%s, %u, → %s, %d", name, n_labels, strnull(result), ret); assert_se(ret == dns_name_suffix(name, n_labels, &p)); - assert_se(streq_ptr(p, result)); + ASSERT_STREQ(p, result); } TEST(dns_name_suffix) { @@ -660,7 +660,7 @@ static void test_dns_name_common_suffix_one(const char *a, const char *b, const log_info("%s, %s, →%s", a, b, result); assert_se(dns_name_common_suffix(a, b, &c) >= 0); - assert_se(streq(c, result)); + ASSERT_STREQ(c, result); } TEST(dns_name_common_suffix) { diff --git a/src/test/test-ellipsize.c b/src/test/test-ellipsize.c index c272c56..f181476 100644 --- a/src/test/test-ellipsize.c +++ b/src/test/test-ellipsize.c @@ -57,9 +57,9 @@ static void test_ellipsize_mem_one(const char *s, size_t old_length, size_t new_ assert_se(utf8_console_width(t3) <= max_width); if (new_length >= old_length) { - assert_se(streq(t1, n)); - assert_se(streq(t2, n)); - assert_se(streq(t3, n)); + ASSERT_STREQ(t1, n); + ASSERT_STREQ(t2, n); + ASSERT_STREQ(t3, n); } } @@ -143,17 +143,17 @@ TEST(ellipsize_ansi_cats) { e = ellipsize("01" ANSI_NORMAL "23", 4, 0); puts(e); - assert_se(streq(e, "01" ANSI_NORMAL "23")); + ASSERT_STREQ(e, "01" ANSI_NORMAL "23"); f = ellipsize("ab" ANSI_NORMAL "cd", 4, 90); puts(f); - assert_se(streq(f, "ab" ANSI_NORMAL "cd")); + ASSERT_STREQ(f, "ab" ANSI_NORMAL "cd"); g = ellipsize("🐱🐱" ANSI_NORMAL "🐱🐱" ANSI_NORMAL, 5, 0); puts(g); - assert_se(streq(g, "…" ANSI_NORMAL "🐱🐱" ANSI_NORMAL)); + ASSERT_STREQ(g, "…" ANSI_NORMAL "🐱🐱" ANSI_NORMAL); h = ellipsize("🐱🐱" ANSI_NORMAL "🐱🐱" ANSI_NORMAL, 5, 90); puts(h); - assert_se(streq(h, "🐱…" ANSI_NORMAL "🐱" ANSI_NORMAL)); + ASSERT_STREQ(h, "🐱…" ANSI_NORMAL "🐱" ANSI_NORMAL); } DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-engine.c b/src/test/test-engine.c index cf77e7c..fa64fbe 100644 --- a/src/test/test-engine.c +++ b/src/test/test-engine.c @@ -214,7 +214,7 @@ int main(int argc, char *argv[]) { assert_se(manager_load_unit(m, "unit-with-multiple-dashes.service", NULL, NULL, &unit_with_multiple_dashes) >= 0); assert_se(strv_equal(unit_with_multiple_dashes->documentation, STRV_MAKE("man:test", "man:override2", "man:override3"))); - assert_se(streq_ptr(unit_with_multiple_dashes->description, "override4")); + ASSERT_STREQ(unit_with_multiple_dashes->description, "override4"); /* Now merge a synthetic unit into the existing one */ assert_se(unit_new_for_name(m, sizeof(Service), "merged.service", &stub) >= 0); @@ -241,10 +241,10 @@ int main(int argc, char *argv[]) { assert_se( unit_has_dependency(manager_get_unit(m, "non-existing-on-failure.target"), UNIT_ATOM_ON_FAILURE_OF, a)); assert_se( unit_has_dependency(a, UNIT_ATOM_ON_SUCCESS, manager_get_unit(m, "non-existing-on-success.target"))); assert_se( unit_has_dependency(manager_get_unit(m, "non-existing-on-success.target"), UNIT_ATOM_ON_SUCCESS_OF, a)); - assert_se(!unit_has_dependency(a, UNIT_ATOM_ON_FAILURE, manager_get_unit(m, "basic.target"))); - assert_se(!unit_has_dependency(a, UNIT_ATOM_ON_SUCCESS, manager_get_unit(m, "basic.target"))); - assert_se(!unit_has_dependency(a, UNIT_ATOM_ON_FAILURE_OF, manager_get_unit(m, "basic.target"))); - assert_se(!unit_has_dependency(a, UNIT_ATOM_ON_SUCCESS_OF, manager_get_unit(m, "basic.target"))); + assert_se(!unit_has_dependency(a, UNIT_ATOM_ON_FAILURE, manager_get_unit(m, SPECIAL_BASIC_TARGET))); + assert_se(!unit_has_dependency(a, UNIT_ATOM_ON_SUCCESS, manager_get_unit(m, SPECIAL_BASIC_TARGET))); + assert_se(!unit_has_dependency(a, UNIT_ATOM_ON_FAILURE_OF, manager_get_unit(m, SPECIAL_BASIC_TARGET))); + assert_se(!unit_has_dependency(a, UNIT_ATOM_ON_SUCCESS_OF, manager_get_unit(m, SPECIAL_BASIC_TARGET))); assert_se(!unit_has_dependency(a, UNIT_ATOM_PROPAGATES_RELOAD_TO, manager_get_unit(m, "non-existing-on-failure.target"))); assert_se(unit_has_name(a, "a.service")); diff --git a/src/test/test-env-file.c b/src/test/test-env-file.c index 3fc6d62..f34b2aa 100644 --- a/src/test/test-env-file.c +++ b/src/test/test-env-file.c @@ -65,13 +65,13 @@ TEST(load_env_file_1) { _cleanup_strv_free_ char **data = NULL; assert_se(load_env_file(NULL, name, &data) == 0); - assert_se(streq(data[0], "a=a")); - assert_se(streq(data[1], "b=bc")); - assert_se(streq(data[2], "d=de f")); - assert_se(streq(data[3], "g=g ")); - assert_se(streq(data[4], "h=ąęół śćńźżμ")); - assert_se(streq(data[5], "i=i")); - assert_se(data[6] == NULL); + ASSERT_STREQ(data[0], "a=a"); + ASSERT_STREQ(data[1], "b=bc"); + ASSERT_STREQ(data[2], "d=de f"); + ASSERT_STREQ(data[3], "g=g "); + ASSERT_STREQ(data[4], "h=ąęół śćńźżμ"); + ASSERT_STREQ(data[5], "i=i"); + ASSERT_NULL(data[6]); } TEST(load_env_file_2) { @@ -80,8 +80,8 @@ TEST(load_env_file_2) { _cleanup_strv_free_ char **data = NULL; assert_se(load_env_file(NULL, name, &data) == 0); - assert_se(streq(data[0], "a=a")); - assert_se(data[1] == NULL); + ASSERT_STREQ(data[0], "a=a"); + ASSERT_NULL(data[1]); } TEST(load_env_file_3) { @@ -90,9 +90,9 @@ TEST(load_env_file_3) { _cleanup_strv_free_ char **data = NULL; assert_se(load_env_file(NULL, name, &data) == 0); - assert_se(streq(data[0], "normal1=line111")); - assert_se(streq(data[1], "normal2=line222")); - assert_se(data[2] == NULL); + ASSERT_STREQ(data[0], "normal1=line111"); + ASSERT_STREQ(data[1], "normal2=line222"); + ASSERT_NULL(data[2]); } TEST(load_env_file_4) { @@ -101,10 +101,10 @@ TEST(load_env_file_4) { _cleanup_strv_free_ char **data = NULL; assert_se(load_env_file(NULL, name, &data) == 0); - assert_se(streq(data[0], "HWMON_MODULES=coretemp f71882fg")); - assert_se(streq(data[1], "MODULE_0=coretemp")); - assert_se(streq(data[2], "MODULE_1=f71882fg")); - assert_se(data[3] == NULL); + ASSERT_STREQ(data[0], "HWMON_MODULES=coretemp f71882fg"); + ASSERT_STREQ(data[1], "MODULE_0=coretemp"); + ASSERT_STREQ(data[2], "MODULE_1=f71882fg"); + ASSERT_NULL(data[3]); } TEST(load_env_file_5) { @@ -113,9 +113,9 @@ TEST(load_env_file_5) { _cleanup_strv_free_ char **data = NULL; assert_se(load_env_file(NULL, name, &data) == 0); - assert_se(streq(data[0], "a=")); - assert_se(streq(data[1], "b=")); - assert_se(data[2] == NULL); + ASSERT_STREQ(data[0], "a="); + ASSERT_STREQ(data[1], "b="); + ASSERT_NULL(data[2]); } TEST(load_env_file_6) { @@ -124,11 +124,11 @@ TEST(load_env_file_6) { _cleanup_strv_free_ char **data = NULL; assert_se(load_env_file(NULL, name, &data) == 0); - assert_se(streq(data[0], "a= n t x y '")); - assert_se(streq(data[1], "b=$'")); - assert_se(streq(data[2], "c= \\n\\t\\$\\`\\\\\n")); - assert_se(streq(data[3], "d= \\n\\t$`\\\n")); - assert_se(data[4] == NULL); + ASSERT_STREQ(data[0], "a= n t x y '"); + ASSERT_STREQ(data[1], "b=$'"); + ASSERT_STREQ(data[2], "c= \\n\\t\\$\\`\\\\\n"); + ASSERT_STREQ(data[3], "d= \\n\\t$`\\\n"); + ASSERT_NULL(data[4]); } TEST(load_env_file_invalid_utf8) { @@ -178,13 +178,13 @@ TEST(write_and_load_env_file) { assert_se(f = popen(cmd, "re")); assert_se(read_full_stream(f, &from_shell, &sz) >= 0); assert_se(sz == strlen(v)); - assert_se(streq(from_shell, v)); + ASSERT_STREQ(from_shell, v); assert_se(load_env_file(NULL, p, &l) >= 0); assert_se(strv_equal(l, STRV_MAKE(j))); assert_se(parse_env_file(NULL, p, "TEST", &w) >= 0); - assert_se(streq_ptr(w, v)); + ASSERT_STREQ(w, v); } } diff --git a/src/test/test-env-util.c b/src/test/test-env-util.c index dffbad6..e2c009d 100644 --- a/src/test/test-env-util.c +++ b/src/test/test-env-util.c @@ -26,26 +26,26 @@ TEST(strv_env_delete) { d = strv_env_delete(a, 2, b, c); assert_se(d); - assert_se(streq(d[0], "WALDO=WALDO")); - assert_se(streq(d[1], "WALDO=")); + ASSERT_STREQ(d[0], "WALDO=WALDO"); + ASSERT_STREQ(d[1], "WALDO="); assert_se(strv_length(d) == 2); } TEST(strv_env_get) { char **l = STRV_MAKE("ONE_OR_TWO=1", "THREE=3", "ONE_OR_TWO=2", "FOUR=4"); - assert_se(streq(strv_env_get(l, "ONE_OR_TWO"), "2")); - assert_se(streq(strv_env_get(l, "THREE"), "3")); - assert_se(streq(strv_env_get(l, "FOUR"), "4")); + ASSERT_STREQ(strv_env_get(l, "ONE_OR_TWO"), "2"); + ASSERT_STREQ(strv_env_get(l, "THREE"), "3"); + ASSERT_STREQ(strv_env_get(l, "FOUR"), "4"); } TEST(strv_env_pairs_get) { char **l = STRV_MAKE("ONE_OR_TWO", "1", "THREE", "3", "ONE_OR_TWO", "2", "FOUR", "4", "FIVE", "5", "SIX", "FIVE", "SEVEN", "7"); - assert_se(streq(strv_env_pairs_get(l, "ONE_OR_TWO"), "2")); - assert_se(streq(strv_env_pairs_get(l, "THREE"), "3")); - assert_se(streq(strv_env_pairs_get(l, "FOUR"), "4")); - assert_se(streq(strv_env_pairs_get(l, "FIVE"), "5")); + ASSERT_STREQ(strv_env_pairs_get(l, "ONE_OR_TWO"), "2"); + ASSERT_STREQ(strv_env_pairs_get(l, "THREE"), "3"); + ASSERT_STREQ(strv_env_pairs_get(l, "FOUR"), "4"); + ASSERT_STREQ(strv_env_pairs_get(l, "FIVE"), "5"); } TEST(strv_env_unset) { @@ -56,8 +56,8 @@ TEST(strv_env_unset) { assert_se(strv_env_unset(l, "SCHLUMPF") == l); - assert_se(streq(l[0], "PIEP")); - assert_se(streq(l[1], "NANANANA=YES")); + ASSERT_STREQ(l[0], "PIEP"); + ASSERT_STREQ(l[1], "NANANANA=YES"); assert_se(strv_length(l) == 2); } @@ -67,22 +67,22 @@ TEST(strv_env_merge) { _cleanup_strv_free_ char **r = strv_env_merge(NULL, a, NULL, b, NULL, a, b, b, NULL); assert_se(r); - assert_se(streq(r[0], "FOO=")); - assert_se(streq(r[1], "WALDO=")); - assert_se(streq(r[2], "PIEP")); - assert_se(streq(r[3], "SCHLUMPF=SMURFF")); - assert_se(streq(r[4], "EQ===")); - assert_se(streq(r[5], "PIEP=")); - assert_se(streq(r[6], "NANANANA=YES")); + ASSERT_STREQ(r[0], "FOO="); + ASSERT_STREQ(r[1], "WALDO="); + ASSERT_STREQ(r[2], "PIEP"); + ASSERT_STREQ(r[3], "SCHLUMPF=SMURFF"); + ASSERT_STREQ(r[4], "EQ==="); + ASSERT_STREQ(r[5], "PIEP="); + ASSERT_STREQ(r[6], "NANANANA=YES"); assert_se(strv_length(r) == 7); assert_se(strv_env_clean(r) == r); - assert_se(streq(r[0], "FOO=")); - assert_se(streq(r[1], "WALDO=")); - assert_se(streq(r[2], "SCHLUMPF=SMURFF")); - assert_se(streq(r[3], "EQ===")); - assert_se(streq(r[4], "PIEP=")); - assert_se(streq(r[5], "NANANANA=YES")); + ASSERT_STREQ(r[0], "FOO="); + ASSERT_STREQ(r[1], "WALDO="); + ASSERT_STREQ(r[2], "SCHLUMPF=SMURFF"); + ASSERT_STREQ(r[3], "EQ==="); + ASSERT_STREQ(r[4], "PIEP="); + ASSERT_STREQ(r[5], "NANANANA=YES"); assert_se(strv_length(r) == 6); } @@ -96,8 +96,8 @@ TEST(strv_env_replace_strdup) { assert_se(strv_length(a) == 2); strv_sort(a); - assert_se(streq(a[0], "a=A")); - assert_se(streq(a[1], "b=b")); + ASSERT_STREQ(a[0], "a=A"); + ASSERT_STREQ(a[1], "b=b"); } TEST(strv_env_replace_strdup_passthrough) { @@ -114,9 +114,9 @@ TEST(strv_env_replace_strdup_passthrough) { assert_se(strv_env_replace_strdup_passthrough(&a, "$a") == -EINVAL); assert_se(strv_length(a) == 3); - assert_se(streq(a[0], "a=a")); - assert_se(streq(a[1], "b=")); - assert_se(streq(a[2], "c=")); + ASSERT_STREQ(a[0], "a=a"); + ASSERT_STREQ(a[1], "b="); + ASSERT_STREQ(a[2], "c="); } TEST(strv_env_assign) { @@ -130,7 +130,28 @@ TEST(strv_env_assign) { assert_se(strv_env_assign(&a, "a=", "B") == -EINVAL); assert_se(strv_length(a) == 1); - assert_se(streq(a[0], "a=A")); + ASSERT_STREQ(a[0], "a=A"); +} + +TEST(strv_env_assignf) { + _cleanup_strv_free_ char **a = NULL; + + assert_se(strv_env_assignf(&a, "a", "a") > 0); + assert_se(strv_env_assignf(&a, "a", "%c", 'a') == 0); + + assert_se(strv_env_assignf(&a, "c", "xxx%iyyy", 5) > 0); + assert_se(strv_length(a) == 2); + assert_se(strv_equal(a, STRV_MAKE("a=a", "c=xxx5yyy"))); + assert_se(strv_env_assignf(&a, "c", NULL) == 0); + + assert_se(strv_env_assignf(&a, "b", "b") > 0); + assert_se(strv_env_assignf(&a, "a", "A") == 0); + assert_se(strv_env_assignf(&a, "b", NULL) == 0); + + assert_se(strv_env_assignf(&a, "a=", "B") == -EINVAL); + + assert_se(strv_length(a) == 1); + ASSERT_STREQ(a[0], "a=A"); } TEST(strv_env_assign_many) { @@ -169,15 +190,15 @@ TEST(env_strv_get_n) { }; char **env = (char**) _env; - assert_se(streq(strv_env_get_n(env, "FOO__", 3, 0), "BAR BAR")); - assert_se(streq(strv_env_get_n(env, "FOO__", 3, REPLACE_ENV_USE_ENVIRONMENT), "BAR BAR")); - assert_se(streq(strv_env_get_n(env, "FOO", 3, 0), "BAR BAR")); - assert_se(streq(strv_env_get_n(env, "FOO", 3, REPLACE_ENV_USE_ENVIRONMENT), "BAR BAR")); + ASSERT_STREQ(strv_env_get_n(env, "FOO__", 3, 0), "BAR BAR"); + ASSERT_STREQ(strv_env_get_n(env, "FOO__", 3, REPLACE_ENV_USE_ENVIRONMENT), "BAR BAR"); + ASSERT_STREQ(strv_env_get_n(env, "FOO", 3, 0), "BAR BAR"); + ASSERT_STREQ(strv_env_get_n(env, "FOO", 3, REPLACE_ENV_USE_ENVIRONMENT), "BAR BAR"); - assert_se(streq(strv_env_get_n(env, "PATH__", 4, 0), "unset")); - assert_se(streq(strv_env_get_n(env, "PATH", 4, 0), "unset")); - assert_se(streq(strv_env_get_n(env, "PATH__", 4, REPLACE_ENV_USE_ENVIRONMENT), "unset")); - assert_se(streq(strv_env_get_n(env, "PATH", 4, REPLACE_ENV_USE_ENVIRONMENT), "unset")); + ASSERT_STREQ(strv_env_get_n(env, "PATH__", 4, 0), "unset"); + ASSERT_STREQ(strv_env_get_n(env, "PATH", 4, 0), "unset"); + ASSERT_STREQ(strv_env_get_n(env, "PATH__", 4, REPLACE_ENV_USE_ENVIRONMENT), "unset"); + ASSERT_STREQ(strv_env_get_n(env, "PATH", 4, REPLACE_ENV_USE_ENVIRONMENT), "unset"); env[3] = NULL; /* kill our $PATH */ @@ -201,19 +222,19 @@ static void test_replace_env1(bool braceless) { unsigned flags = REPLACE_ENV_ALLOW_BRACELESS*braceless; assert_se(replace_env("FOO=$FOO=${FOO}", (char**) env, flags, &t) >= 0); - assert_se(streq(t, braceless ? "FOO=BAR BAR=BAR BAR" : "FOO=$FOO=BAR BAR")); + ASSERT_STREQ(t, braceless ? "FOO=BAR BAR=BAR BAR" : "FOO=$FOO=BAR BAR"); assert_se(replace_env("BAR=$BAR=${BAR}", (char**) env, flags, &s) >= 0); - assert_se(streq(s, braceless ? "BAR=waldo=waldo" : "BAR=$BAR=waldo")); + ASSERT_STREQ(s, braceless ? "BAR=waldo=waldo" : "BAR=$BAR=waldo"); assert_se(replace_env("BARBAR=$BARBAR=${BARBAR}", (char**) env, flags, &q) >= 0); - assert_se(streq(q, braceless ? "BARBAR==" : "BARBAR=$BARBAR=")); + ASSERT_STREQ(q, braceless ? "BARBAR==" : "BARBAR=$BARBAR="); assert_se(replace_env("BAR=$BAR$BAR${BAR}${BAR}", (char**) env, flags, &r) >= 0); - assert_se(streq(r, braceless ? "BAR=waldowaldowaldowaldo" : "BAR=$BAR$BARwaldowaldo")); + ASSERT_STREQ(r, braceless ? "BAR=waldowaldowaldowaldo" : "BAR=$BAR$BARwaldowaldo"); assert_se(replace_env("${BAR}$BAR$BAR", (char**) env, flags, &p) >= 0); - assert_se(streq(p, braceless ? "waldowaldowaldo" : "waldo$BAR$BAR")); + ASSERT_STREQ(p, braceless ? "waldowaldowaldo" : "waldo$BAR$BAR"); } static void test_replace_env2(bool extended) { @@ -228,25 +249,25 @@ static void test_replace_env2(bool extended) { unsigned flags = REPLACE_ENV_ALLOW_EXTENDED*extended; assert_se(replace_env("FOO=${FOO:-${BAR}}", (char**) env, flags, &t) >= 0); - assert_se(streq(t, extended ? "FOO=foo" : "FOO=${FOO:-bar}")); + ASSERT_STREQ(t, extended ? "FOO=foo" : "FOO=${FOO:-bar}"); assert_se(replace_env("BAR=${XXX:-${BAR}}", (char**) env, flags, &s) >= 0); - assert_se(streq(s, extended ? "BAR=bar" : "BAR=${XXX:-bar}")); + ASSERT_STREQ(s, extended ? "BAR=bar" : "BAR=${XXX:-bar}"); assert_se(replace_env("XXX=${XXX:+${BAR}}", (char**) env, flags, &q) >= 0); - assert_se(streq(q, extended ? "XXX=" : "XXX=${XXX:+bar}")); + ASSERT_STREQ(q, extended ? "XXX=" : "XXX=${XXX:+bar}"); assert_se(replace_env("FOO=${FOO:+${BAR}}", (char**) env, flags, &r) >= 0); - assert_se(streq(r, extended ? "FOO=bar" : "FOO=${FOO:+bar}")); + ASSERT_STREQ(r, extended ? "FOO=bar" : "FOO=${FOO:+bar}"); assert_se(replace_env("FOO=${FOO:-${BAR}post}", (char**) env, flags, &p) >= 0); - assert_se(streq(p, extended ? "FOO=foo" : "FOO=${FOO:-barpost}")); + ASSERT_STREQ(p, extended ? "FOO=foo" : "FOO=${FOO:-barpost}"); assert_se(replace_env("XXX=${XXX:+${BAR}post}", (char**) env, flags, &x) >= 0); - assert_se(streq(x, extended ? "XXX=" : "XXX=${XXX:+barpost}")); + ASSERT_STREQ(x, extended ? "XXX=" : "XXX=${XXX:+barpost}"); assert_se(replace_env("FOO=${FOO}between${BAR:-baz}", (char**) env, flags, &y) >= 0); - assert_se(streq(y, extended ? "FOO=foobetweenbar" : "FOO=foobetween${BAR:-baz}")); + ASSERT_STREQ(y, extended ? "FOO=foobetweenbar" : "FOO=foobetween${BAR:-baz}"); } TEST(replace_env) { @@ -286,23 +307,23 @@ TEST(replace_env_argv) { assert_se(replace_env_argv((char**) line, (char**) env, &r, NULL, NULL) >= 0); assert_se(r); - assert_se(streq(r[0], "FOO$FOO")); - assert_se(streq(r[1], "FOO$FOOFOO")); - assert_se(streq(r[2], "FOOBAR BAR$FOO")); - assert_se(streq(r[3], "FOOBAR BAR")); - assert_se(streq(r[4], "BAR BAR")); - assert_se(streq(r[5], "BAR")); - assert_se(streq(r[6], "BAR")); - assert_se(streq(r[7], "BAR BARwaldo")); - assert_se(streq(r[8], "${FOO")); - assert_se(streq(r[9], "FOO$BAR BAR")); - assert_se(streq(r[10], "$FOOBAR BAR")); - assert_se(streq(r[11], "${FOO:-waldo}")); - assert_se(streq(r[12], "${QUUX:-BAR BAR}")); - assert_se(streq(r[13], "${FOO:+waldo}")); - assert_se(streq(r[14], "${QUUX:+waldo}")); - assert_se(streq(r[15], "${FOO:+|waldo|}}")); - assert_se(streq(r[16], "${FOO:+|waldo{|}")); + ASSERT_STREQ(r[0], "FOO$FOO"); + ASSERT_STREQ(r[1], "FOO$FOOFOO"); + ASSERT_STREQ(r[2], "FOOBAR BAR$FOO"); + ASSERT_STREQ(r[3], "FOOBAR BAR"); + ASSERT_STREQ(r[4], "BAR BAR"); + ASSERT_STREQ(r[5], "BAR"); + ASSERT_STREQ(r[6], "BAR"); + ASSERT_STREQ(r[7], "BAR BARwaldo"); + ASSERT_STREQ(r[8], "${FOO"); + ASSERT_STREQ(r[9], "FOO$BAR BAR"); + ASSERT_STREQ(r[10], "$FOOBAR BAR"); + ASSERT_STREQ(r[11], "${FOO:-waldo}"); + ASSERT_STREQ(r[12], "${QUUX:-BAR BAR}"); + ASSERT_STREQ(r[13], "${FOO:+waldo}"); + ASSERT_STREQ(r[14], "${QUUX:+waldo}"); + ASSERT_STREQ(r[15], "${FOO:+|waldo|}}"); + ASSERT_STREQ(r[16], "${FOO:+|waldo{|}"); assert_se(strv_length(r) == 17); } @@ -372,15 +393,15 @@ TEST(env_clean) { assert_se(strv_env_clean(e) == e); assert_se(strv_env_is_valid(e)); - assert_se(streq(e[0], "FOOBAR=WALDO")); - assert_se(streq(e[1], "X=")); - assert_se(streq(e[2], "F=F")); - assert_se(streq(e[3], "abcd=äöüß")); - assert_se(streq(e[4], "xyz=xyz\n")); - assert_se(streq(e[5], "another=final one")); - assert_se(streq(e[6], "CRLF=\r\n")); - assert_se(streq(e[7], "LESS_TERMCAP_mb=\x1b[01;31m")); - assert_se(e[8] == NULL); + ASSERT_STREQ(e[0], "FOOBAR=WALDO"); + ASSERT_STREQ(e[1], "X="); + ASSERT_STREQ(e[2], "F=F"); + ASSERT_STREQ(e[3], "abcd=äöüß"); + ASSERT_STREQ(e[4], "xyz=xyz\n"); + ASSERT_STREQ(e[5], "another=final one"); + ASSERT_STREQ(e[6], "CRLF=\r\n"); + ASSERT_STREQ(e[7], "LESS_TERMCAP_mb=\x1b[01;31m"); + ASSERT_NULL(e[8]); } TEST(env_name_is_valid) { @@ -430,13 +451,13 @@ TEST(env_assignment_is_valid) { TEST(putenv_dup) { assert_se(putenv_dup("A=a1", true) == 0); - assert_se(streq_ptr(getenv("A"), "a1")); + ASSERT_STREQ(getenv("A"), "a1"); assert_se(putenv_dup("A=a1", true) == 0); - assert_se(streq_ptr(getenv("A"), "a1")); + ASSERT_STREQ(getenv("A"), "a1"); assert_se(putenv_dup("A=a2", false) == 0); - assert_se(streq_ptr(getenv("A"), "a1")); + ASSERT_STREQ(getenv("A"), "a1"); assert_se(putenv_dup("A=a2", true) == 0); - assert_se(streq_ptr(getenv("A"), "a2")); + ASSERT_STREQ(getenv("A"), "a2"); } TEST(setenv_systemd_exec_pid) { @@ -455,7 +476,7 @@ TEST(setenv_systemd_exec_pid) { assert_se(setenv("SYSTEMD_EXEC_PID", "*", 1) >= 0); assert_se(setenv_systemd_exec_pid(true) == 0); assert_se(e = getenv("SYSTEMD_EXEC_PID")); - assert_se(streq(e, "*")); + ASSERT_STREQ(e, "*"); assert_se(setenv("SYSTEMD_EXEC_PID", "123abc", 1) >= 0); assert_se(setenv_systemd_exec_pid(true) == 1); @@ -502,10 +523,10 @@ TEST(getenv_steal_erase) { copy1 = strdup(eq + 1); assert_se(copy1); - assert_se(streq_ptr(getenv(n), copy1)); + ASSERT_STREQ(getenv(n), copy1); assert_se(getenv(n) == eq + 1); assert_se(getenv_steal_erase(n, ©2) > 0); - assert_se(streq_ptr(copy1, copy2)); + ASSERT_STREQ(copy1, copy2); assert_se(isempty(eq + 1)); assert_se(!getenv(n)); } @@ -550,12 +571,12 @@ TEST(getenv_path_list) { /* Finally some valid paths */ assert_se(setenv("TEST_GETENV_PATH_LIST", "/foo:/bar/baz:/hello/world:/path with spaces:/final", 1) >= 0); assert_se(getenv_path_list("TEST_GETENV_PATH_LIST", &path_list) >= 0); - assert_se(streq(path_list[0], "/foo")); - assert_se(streq(path_list[1], "/bar/baz")); - assert_se(streq(path_list[2], "/hello/world")); - assert_se(streq(path_list[3], "/path with spaces")); - assert_se(streq(path_list[4], "/final")); - assert_se(path_list[5] == NULL); + ASSERT_STREQ(path_list[0], "/foo"); + ASSERT_STREQ(path_list[1], "/bar/baz"); + ASSERT_STREQ(path_list[2], "/hello/world"); + ASSERT_STREQ(path_list[3], "/path with spaces"); + ASSERT_STREQ(path_list[4], "/final"); + ASSERT_NULL(path_list[5]); assert_se(unsetenv("TEST_GETENV_PATH_LIST") >= 0); } diff --git a/src/test/test-errno-list.c b/src/test/test-errno-list.c index f91a1f7..77f4187 100644 --- a/src/test/test-errno-list.c +++ b/src/test/test-errno-list.c @@ -11,22 +11,22 @@ TEST(errno_list) { for (size_t i = 0; i < ELEMENTSOF(errno_names); i++) { if (errno_names[i]) { - assert_se(streq(errno_to_name(i), errno_names[i])); + ASSERT_STREQ(errno_to_name(i), errno_names[i]); assert_se(errno_from_name(errno_names[i]) == (int) i); } } #ifdef ECANCELLED /* ECANCELLED is an alias of ECANCELED. */ - assert_se(streq(errno_to_name(ECANCELLED), "ECANCELED")); + ASSERT_STREQ(errno_to_name(ECANCELLED), "ECANCELED"); #endif - assert_se(streq(errno_to_name(ECANCELED), "ECANCELED")); + ASSERT_STREQ(errno_to_name(ECANCELED), "ECANCELED"); #ifdef EREFUSED /* EREFUSED is an alias of ECONNREFUSED. */ - assert_se(streq(errno_to_name(EREFUSED), "ECONNREFUSED")); + ASSERT_STREQ(errno_to_name(EREFUSED), "ECONNREFUSED"); #endif - assert_se(streq(errno_to_name(ECONNREFUSED), "ECONNREFUSED")); + ASSERT_STREQ(errno_to_name(ECONNREFUSED), "ECONNREFUSED"); } DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-errno-util.c b/src/test/test-errno-util.c index 376d532..ab463bd 100644 --- a/src/test/test-errno-util.c +++ b/src/test/test-errno-util.c @@ -31,8 +31,8 @@ TEST(STRERROR) { assert_se(strstr(b, "201")); /* Check with negative values */ - assert_se(streq(a, STRERROR(-200))); - assert_se(streq(b, STRERROR(-201))); + ASSERT_STREQ(a, STRERROR(-200)); + ASSERT_STREQ(b, STRERROR(-201)); const char *c = STRERROR(INT_MAX); char buf[DECIMAL_STR_MAX(int)]; diff --git a/src/test/test-escape.c b/src/test/test-escape.c index 21786ae..89a25fe 100644 --- a/src/test/test-escape.c +++ b/src/test/test-escape.c @@ -9,14 +9,14 @@ TEST(cescape) { _cleanup_free_ char *t = NULL; assert_se(t = cescape("abc\\\"\b\f\n\r\t\v\a\003\177\234\313")); - assert_se(streq(t, "abc\\\\\\\"\\b\\f\\n\\r\\t\\v\\a\\003\\177\\234\\313")); + ASSERT_STREQ(t, "abc\\\\\\\"\\b\\f\\n\\r\\t\\v\\a\\003\\177\\234\\313"); } TEST(xescape) { _cleanup_free_ char *t = NULL; assert_se(t = xescape("abc\\\"\b\f\n\r\t\v\a\003\177\234\313", "")); - assert_se(streq(t, "abc\\x5c\"\\x08\\x0c\\x0a\\x0d\\x09\\x0b\\x07\\x03\\x7f\\x9c\\xcb")); + ASSERT_STREQ(t, "abc\\x5c\"\\x08\\x0c\\x0a\\x0d\\x09\\x0b\\x07\\x03\\x7f\\x9c\\xcb"); } static void test_xescape_full_one(bool eight_bits) { @@ -36,7 +36,7 @@ static void test_xescape_full_one(bool eight_bits) { log_info("%02u: <%s>", i, t); if (i >= full_fit) - assert_se(streq(t, escaped)); + ASSERT_STREQ(t, escaped); else if (i >= 3) { /* We need up to four columns, so up to three columns may be wasted */ assert_se(strlen(t) == i || strlen(t) == i - 1 || strlen(t) == i - 2 || strlen(t) == i - 3); @@ -69,50 +69,50 @@ TEST(cunescape) { assert_se(cunescape("abc\\\\\\\"\\b\\f\\a\\n\\r\\t\\v\\003\\177\\234\\313\\000\\x00", 0, &unescaped) < 0); assert_se(cunescape("abc\\\\\\\"\\b\\f\\a\\n\\r\\t\\v\\003\\177\\234\\313\\000\\x00", UNESCAPE_RELAX, &unescaped) >= 0); - assert_se(streq_ptr(unescaped, "abc\\\"\b\f\a\n\r\t\v\003\177\234\313\\000\\x00")); + ASSERT_STREQ(unescaped, "abc\\\"\b\f\a\n\r\t\v\003\177\234\313\\000\\x00"); unescaped = mfree(unescaped); /* incomplete sequences */ assert_se(cunescape("\\x0", 0, &unescaped) < 0); assert_se(cunescape("\\x0", UNESCAPE_RELAX, &unescaped) >= 0); - assert_se(streq_ptr(unescaped, "\\x0")); + ASSERT_STREQ(unescaped, "\\x0"); unescaped = mfree(unescaped); assert_se(cunescape("\\x", 0, &unescaped) < 0); assert_se(cunescape("\\x", UNESCAPE_RELAX, &unescaped) >= 0); - assert_se(streq_ptr(unescaped, "\\x")); + ASSERT_STREQ(unescaped, "\\x"); unescaped = mfree(unescaped); assert_se(cunescape("\\", 0, &unescaped) < 0); assert_se(cunescape("\\", UNESCAPE_RELAX, &unescaped) >= 0); - assert_se(streq_ptr(unescaped, "\\")); + ASSERT_STREQ(unescaped, "\\"); unescaped = mfree(unescaped); assert_se(cunescape("\\11", 0, &unescaped) < 0); assert_se(cunescape("\\11", UNESCAPE_RELAX, &unescaped) >= 0); - assert_se(streq_ptr(unescaped, "\\11")); + ASSERT_STREQ(unescaped, "\\11"); unescaped = mfree(unescaped); assert_se(cunescape("\\1", 0, &unescaped) < 0); assert_se(cunescape("\\1", UNESCAPE_RELAX, &unescaped) >= 0); - assert_se(streq_ptr(unescaped, "\\1")); + ASSERT_STREQ(unescaped, "\\1"); unescaped = mfree(unescaped); assert_se(cunescape("\\u0000", 0, &unescaped) < 0); assert_se(cunescape("\\u00DF\\U000000df\\u03a0\\U00000041", UNESCAPE_RELAX, &unescaped) >= 0); - assert_se(streq_ptr(unescaped, "ßßΠA")); + ASSERT_STREQ(unescaped, "ßßΠA"); unescaped = mfree(unescaped); assert_se(cunescape("\\073", 0, &unescaped) >= 0); - assert_se(streq_ptr(unescaped, ";")); + ASSERT_STREQ(unescaped, ";"); unescaped = mfree(unescaped); assert_se(cunescape("A=A\\\\x0aB", 0, &unescaped) >= 0); - assert_se(streq_ptr(unescaped, "A=A\\x0aB")); + ASSERT_STREQ(unescaped, "A=A\\x0aB"); unescaped = mfree(unescaped); assert_se(cunescape("A=A\\\\x0aB", UNESCAPE_RELAX, &unescaped) >= 0); - assert_se(streq_ptr(unescaped, "A=A\\x0aB")); + ASSERT_STREQ(unescaped, "A=A\\x0aB"); unescaped = mfree(unescaped); assert_se(cunescape("\\x00\\x00\\x00", UNESCAPE_ACCEPT_NUL, &unescaped) == 3); @@ -136,7 +136,7 @@ static void test_shell_escape_one(const char *s, const char *bad, const char *ex assert_se(r = shell_escape(s, bad)); log_debug("%s → %s (expected %s)", s, r, expected); - assert_se(streq_ptr(r, expected)); + ASSERT_STREQ(r, expected); } TEST(shell_escape) { @@ -153,7 +153,7 @@ static void test_shell_maybe_quote_one(const char *s, ShellEscapeFlags flags, co assert_se(ret = shell_maybe_quote(s, flags)); log_debug("[%s] → [%s] (%s)", s, ret, expected); - assert_se(streq(ret, expected)); + ASSERT_STREQ(ret, expected); } TEST(shell_maybe_quote) { @@ -207,7 +207,7 @@ static void test_quote_command_line_one(char **argv, const char *expected) { assert_se(s = quote_command_line(argv, SHELL_ESCAPE_EMPTY)); log_info("%s", s); - assert_se(streq(s, expected)); + ASSERT_STREQ(s, expected); } TEST(quote_command_line) { @@ -228,7 +228,7 @@ static void test_octescape_one(const char *s, const char *expected) { assert_se(ret = octescape(s, strlen_ptr(s))); log_debug("octescape(\"%s\") → \"%s\" (expected: \"%s\")", strnull(s), ret, expected); - assert_se(streq(ret, expected)); + ASSERT_STREQ(ret, expected); } TEST(octescape) { @@ -239,4 +239,22 @@ TEST(octescape) { test_octescape_one("\123\213\222", "\123\\213\\222"); } +static void test_decescape_one(const char *s, const char *bad, const char *expected) { + _cleanup_free_ char *ret = NULL; + + assert_se(ret = decescape(s, bad, strlen_ptr(s))); + log_debug("decescape(\"%s\") → \"%s\" (expected: \"%s\")", strnull(s), ret, expected); + ASSERT_STREQ(ret, expected); +} + +TEST(decescape) { + test_decescape_one(NULL, "bad", ""); + test_decescape_one("foo", "", "foo"); + test_decescape_one("foo", "f", "\\102oo"); + test_decescape_one("foo", "o", "f\\111\\111"); + test_decescape_one("go\"bb\\ledyg\x03ook\r\n", "", "go\\034bb\\092ledyg\\003ook\\013\\010"); + test_decescape_one("\\xff\xff" "f", "f", "\\092x\\102\\102\\255\\102"); + test_decescape_one("all", "all", "\\097\\108\\108"); +} + DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-ether-addr-util.c b/src/test/test-ether-addr-util.c index d680f80..4826a6f 100644 --- a/src/test/test-ether-addr-util.c +++ b/src/test/test-ether-addr-util.c @@ -72,7 +72,7 @@ static void test_parse_hw_addr_full_one(const char *in, size_t expected_len, con if (r >= 0) { if (!IN_SET(expected_len, 0, SIZE_MAX)) assert_se(h.length == expected_len); - assert_se(streq(HW_ADDR_TO_STR(&h), expected)); + ASSERT_STREQ(HW_ADDR_TO_STR(&h), expected); } } diff --git a/src/test/test-exec-util.c b/src/test/test-exec-util.c index 2304f6a..533c988 100644 --- a/src/test/test-exec-util.c +++ b/src/test/test-exec-util.c @@ -195,7 +195,7 @@ TEST(execution_order) { execute_directories(dirs, DEFAULT_TIMEOUT_USEC, ignore_stdout, ignore_stdout_args, NULL, NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS); assert_se(read_full_file(output, &contents, NULL) >= 0); - assert_se(streq(contents, "30-override\n80-foo\n90-bar\nlast\n")); + ASSERT_STREQ(contents, "30-override\n80-foo\n90-bar\nlast\n"); } static int gather_stdout_one(int fd, void *arg) { @@ -279,7 +279,7 @@ TEST(stdout_gathering) { log_info("got: %s", output); - assert_se(streq(output, "a\nb\nc\nd\n")); + ASSERT_STREQ(output, "a\nb\nc\nd\n"); } TEST(environment_gathering) { @@ -331,7 +331,7 @@ TEST(environment_gathering) { assert_se(chmod(name3, 0755) == 0); /* When booting in containers or without initrd there might not be any PATH in the environment and if - * there is no PATH /bin/sh built-in PATH may leak and override systemd's DEFAULT_PATH which is not + * there is no PATH /bin/sh built-in PATH may leak and override systemd's default path which is not * good. Force our own PATH in environment, to prevent expansion of sh built-in $PATH */ old = getenv("PATH"); r = setenv("PATH", "no-sh-built-in-path", 1); @@ -346,15 +346,14 @@ TEST(environment_gathering) { STRV_FOREACH(p, env) log_info("got env: \"%s\"", *p); - assert_se(streq(strv_env_get(env, "A"), "22:23:24")); - assert_se(streq(strv_env_get(env, "B"), "12")); - assert_se(streq(strv_env_get(env, "C"), "001")); - assert_se(streq(strv_env_get(env, "PATH"), "no-sh-built-in-path:/no/such/file")); + ASSERT_STREQ(strv_env_get(env, "A"), "22:23:24"); + ASSERT_STREQ(strv_env_get(env, "B"), "12"); + ASSERT_STREQ(strv_env_get(env, "C"), "001"); + ASSERT_STREQ(strv_env_get(env, "PATH"), "no-sh-built-in-path:/no/such/file"); - /* now retest with "default" path passed in, as created by - * manager_default_environment */ + /* Now retest with some "default" path passed. */ env = strv_free(env); - env = strv_new("PATH=" DEFAULT_PATH); + env = strv_new("PATH=" DEFAULT_PATH_WITHOUT_SBIN); assert_se(env); r = execute_directories(dirs, DEFAULT_TIMEOUT_USEC, gather_environment, args, NULL, env, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS); @@ -363,10 +362,10 @@ TEST(environment_gathering) { STRV_FOREACH(p, env) log_info("got env: \"%s\"", *p); - assert_se(streq(strv_env_get(env, "A"), "22:23:24")); - assert_se(streq(strv_env_get(env, "B"), "12")); - assert_se(streq(strv_env_get(env, "C"), "001")); - assert_se(streq(strv_env_get(env, "PATH"), DEFAULT_PATH ":/no/such/file")); + ASSERT_STREQ(strv_env_get(env, "A"), "22:23:24"); + ASSERT_STREQ(strv_env_get(env, "B"), "12"); + ASSERT_STREQ(strv_env_get(env, "C"), "001"); + ASSERT_STREQ(strv_env_get(env, "PATH"), DEFAULT_PATH_WITHOUT_SBIN ":/no/such/file"); /* reset environ PATH */ assert_se(set_unset_env("PATH", old, true) == 0); diff --git a/src/test/test-execute.c b/src/test/test-execute.c index 4f6ad5d..4b8daa4 100644 --- a/src/test/test-execute.c +++ b/src/test/test-execute.c @@ -7,6 +7,7 @@ #include "sd-event.h" +#include "build-path.h" #include "capability-util.h" #include "cpu-set-util.h" #include "copy.h" @@ -28,6 +29,7 @@ #include "signal-util.h" #include "static-destruct.h" #include "stat-util.h" +#include "sysctl-util.h" #include "tests.h" #include "tmpfile-util.h" #include "unit.h" @@ -57,8 +59,13 @@ static void wait_for_service_finish(Manager *m, Unit *unit) { usec_t ts; usec_t timeout = 2 * USEC_PER_MINUTE; - assert_se(m); - assert_se(unit); + ASSERT_NOT_NULL(m); + ASSERT_NOT_NULL(unit); + + /* Bump the timeout when running in plain QEMU, as some more involved tests might start hitting the + * default 2m timeout (like exec-dynamicuser-statedir.service) */ + if (detect_virtualization() == VIRTUALIZATION_QEMU) + timeout *= 2; service = SERVICE(unit); printf("%s\n", unit->id); @@ -69,7 +76,7 @@ static void wait_for_service_finish(Manager *m, Unit *unit) { usec_t n; r = sd_event_run(m->event, 100 * USEC_PER_MSEC); - assert_se(r >= 0); + ASSERT_OK(r); n = now(CLOCK_MONOTONIC); if (ts + timeout < n) { @@ -86,8 +93,8 @@ static void check_main_result(const char *file, unsigned line, const char *func, Manager *m, Unit *unit, int status_expected, int code_expected) { Service *service = NULL; - assert_se(m); - assert_se(unit); + ASSERT_NOT_NULL(m); + ASSERT_NOT_NULL(unit); wait_for_service_finish(m, unit); @@ -113,8 +120,8 @@ static void check_service_result(const char *file, unsigned line, const char *fu Manager *m, Unit *unit, ServiceResult result_expected) { Service *service = NULL; - assert_se(m); - assert_se(unit); + ASSERT_NOT_NULL(m); + ASSERT_NOT_NULL(unit); wait_for_service_finish(m, unit); @@ -178,7 +185,7 @@ static bool check_user_has_group_with_same_name(const char *name) { struct passwd *p; struct group *g; - assert_se(name); + ASSERT_NOT_NULL(name); p = getpwnam(name); if (!p || @@ -214,20 +221,41 @@ static void start_parent_slices(Unit *unit) { if (slice) { start_parent_slices(slice); int r = unit_start(slice, NULL); - assert_se(r >= 0 || r == -EALREADY); + if (r != -EALREADY) + ASSERT_OK(r); + } +} + +static bool apparmor_restrict_unprivileged_userns(void) { + _cleanup_free_ char *v = NULL; + int r; + + /* If kernel.apparmor_restrict_unprivileged_userns=1, then we cannot + * use unprivileged user namespaces. */ + r = sysctl_read("kernel/apparmor_restrict_unprivileged_userns", &v); + if (r < 0) { + if (r != -ENOENT) + log_debug_errno(r, "Failed to read kernel.apparmor_restrict_unprivileged_userns sysctl, ignoring: %m"); + + return false; } + + return streq(v, "1"); } static bool have_userns_privileges(void) { pid_t pid; int r; + if (apparmor_restrict_unprivileged_userns()) + return false; + r = safe_fork("(sd-test-check-userns)", FORK_RESET_SIGNALS | FORK_CLOSE_ALL_FDS | FORK_DEATHSIG_SIGKILL, &pid); - assert(r >= 0); + ASSERT_OK(r); if (r == 0) { /* Keep CAP_SYS_ADMIN if we have it to ensure we give an * accurate result to the caller. Some kernels have a @@ -263,13 +291,13 @@ static void _test(const char *file, unsigned line, const char *func, Manager *m, const char *unit_name, int status_expected, int code_expected) { Unit *unit; - assert_se(unit_name); + ASSERT_NOT_NULL(unit_name); - assert_se(manager_load_startable_unit_or_warn(m, unit_name, NULL, &unit) >= 0); + ASSERT_OK(manager_load_startable_unit_or_warn(m, unit_name, NULL, &unit)); /* We need to start the slices as well otherwise the slice cgroups might be pruned * in on_cgroup_empty_event. */ start_parent_slices(unit); - assert_se(unit_start(unit, NULL) >= 0); + ASSERT_OK(unit_start(unit, NULL)); check_main_result(file, line, func, m, unit, status_expected, code_expected); ++n_ran_tests; @@ -281,18 +309,18 @@ static void _test_service(const char *file, unsigned line, const char *func, Manager *m, const char *unit_name, ServiceResult result_expected) { Unit *unit; - assert_se(unit_name); + ASSERT_NOT_NULL(unit_name); - assert_se(manager_load_startable_unit_or_warn(m, unit_name, NULL, &unit) >= 0); - assert_se(unit_start(unit, NULL) >= 0); + ASSERT_OK(manager_load_startable_unit_or_warn(m, unit_name, NULL, &unit)); + ASSERT_OK(unit_start(unit, NULL)); check_service_result(file, line, func, m, unit, result_expected); } #define test_service(m, unit_name, result_expected) \ _test_service(PROJECT_FILE, __LINE__, __func__, m, unit_name, result_expected) static void test_exec_bindpaths(Manager *m) { - assert_se(mkdir_p("/tmp/test-exec-bindpaths", 0755) >= 0); - assert_se(mkdir_p("/tmp/test-exec-bindreadonlypaths", 0755) >= 0); + ASSERT_OK(mkdir_p("/tmp/test-exec-bindpaths", 0755)); + ASSERT_OK(mkdir_p("/tmp/test-exec-bindreadonlypaths", 0755)); test(m, "exec-bindpaths.service", can_unshare ? 0 : EXIT_NAMESPACE, CLD_EXITED); @@ -303,8 +331,8 @@ static void test_exec_bindpaths(Manager *m) { static void test_exec_cpuaffinity(Manager *m) { _cleanup_(cpu_set_reset) CPUSet c = {}; - assert_se(cpu_set_realloc(&c, 8192) >= 0); /* just allocate the maximum possible size */ - assert_se(sched_getaffinity(0, c.allocated, c.set) >= 0); + ASSERT_OK(cpu_set_realloc(&c, 8192)); /* just allocate the maximum possible size */ + ASSERT_OK_ERRNO(sched_getaffinity(0, c.allocated, c.set)); if (!CPU_ISSET_S(0, c.allocated, c.set)) { log_notice("Cannot use CPU 0, skipping %s", __func__); @@ -330,7 +358,7 @@ static void test_exec_credentials(Manager *m) { } static void test_exec_workingdirectory(Manager *m) { - assert_se(mkdir_p("/tmp/test-exec_workingdirectory", 0755) >= 0); + ASSERT_OK(mkdir_p("/tmp/test-exec_workingdirectory", 0755)); test(m, "exec-workingdirectory.service", 0, CLD_EXITED); test(m, "exec-workingdirectory-trailing-dot.service", 0, CLD_EXITED); @@ -339,13 +367,13 @@ static void test_exec_workingdirectory(Manager *m) { } static void test_exec_execsearchpath(Manager *m) { - assert_se(mkdir_p("/tmp/test-exec_execsearchpath", 0755) >= 0); + ASSERT_OK(mkdir_p("/tmp/test-exec_execsearchpath", 0755)); - assert_se(copy_file("/bin/ls", "/tmp/test-exec_execsearchpath/ls_temp", 0, 0777, COPY_REPLACE) >= 0); + ASSERT_OK(copy_file("/bin/ls", "/tmp/test-exec_execsearchpath/ls_temp", 0, 0777, COPY_REPLACE)); test(m, "exec-execsearchpath.service", 0, CLD_EXITED); - assert_se(rm_rf("/tmp/test-exec_execsearchpath", REMOVE_ROOT|REMOVE_PHYSICAL) >= 0); + ASSERT_OK(rm_rf("/tmp/test-exec_execsearchpath", REMOVE_ROOT|REMOVE_PHYSICAL)); test(m, "exec-execsearchpath.service", EXIT_EXEC, CLD_EXITED); } @@ -388,8 +416,7 @@ static void test_exec_execsearchpath_environment_files(Manager *m) { int r; r = write_string_file("/tmp/test-exec_execsearchpath_environmentfile.conf", path_not_set, WRITE_STRING_FILE_CREATE); - - assert_se(r == 0); + ASSERT_OK(r); test(m, "exec-execsearchpath-environmentfile.service", 0, CLD_EXITED); @@ -397,8 +424,7 @@ static void test_exec_execsearchpath_environment_files(Manager *m) { r = write_string_file("/tmp/test-exec_execsearchpath_environmentfile-set.conf", path_set, WRITE_STRING_FILE_CREATE); - - assert_se(r == 0); + ASSERT_OK(r); test(m, "exec-execsearchpath-environmentfile-set.service", 0, CLD_EXITED); @@ -406,29 +432,32 @@ static void test_exec_execsearchpath_environment_files(Manager *m) { } static void test_exec_execsearchpath_passenvironment(Manager *m) { - assert_se(setenv("VAR1", "word1 word2", 1) == 0); - assert_se(setenv("VAR2", "word3", 1) == 0); - assert_se(setenv("VAR3", "$word 5 6", 1) == 0); - assert_se(setenv("VAR4", "new\nline", 1) == 0); - assert_se(setenv("VAR5", "passwordwithbackslashes", 1) == 0); + ASSERT_OK_ERRNO(setenv("VAR1", "word1 word2", 1)); + ASSERT_OK_ERRNO(setenv("VAR2", "word3", 1)); + ASSERT_OK_ERRNO(setenv("VAR3", "$word 5 6", 1)); + ASSERT_OK_ERRNO(setenv("VAR4", "new\nline", 1)); + ASSERT_OK_ERRNO(setenv("VAR5", "passwordwithbackslashes", 1)); test(m, "exec-execsearchpath-passenvironment.service", 0, CLD_EXITED); - assert_se(setenv("PATH", "/usr", 1) == 0); + ASSERT_OK_ERRNO(setenv("PATH", "/usr", 1)); test(m, "exec-execsearchpath-passenvironment-set.service", 0, CLD_EXITED); - assert_se(unsetenv("VAR1") == 0); - assert_se(unsetenv("VAR2") == 0); - assert_se(unsetenv("VAR3") == 0); - assert_se(unsetenv("VAR4") == 0); - assert_se(unsetenv("VAR5") == 0); - assert_se(unsetenv("PATH") == 0); + ASSERT_OK_ERRNO(unsetenv("VAR1")); + ASSERT_OK_ERRNO(unsetenv("VAR2")); + ASSERT_OK_ERRNO(unsetenv("VAR3")); + ASSERT_OK_ERRNO(unsetenv("VAR4")); + ASSERT_OK_ERRNO(unsetenv("VAR5")); + ASSERT_OK_ERRNO(unsetenv("PATH")); } static void test_exec_personality(Manager *m) { #if defined(__x86_64__) test(m, "exec-personality-x86-64.service", 0, CLD_EXITED); +#elif defined(__s390x__) + test(m, "exec-personality-s390x.service", 0, CLD_EXITED); + #elif defined(__s390__) test(m, "exec-personality-s390.service", 0, CLD_EXITED); @@ -457,7 +486,7 @@ static void test_exec_ignoresigpipe(Manager *m) { } static void test_exec_privatetmp(Manager *m) { - assert_se(touch("/tmp/test-exec_privatetmp") >= 0); + ASSERT_OK(touch("/tmp/test-exec_privatetmp")); if (MANAGER_IS_SYSTEM(m) || have_userns_privileges()) { test(m, "exec-privatetmp-yes.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED); @@ -586,13 +615,14 @@ static void test_exec_inaccessiblepaths(Manager *m) { test(m, "exec-inaccessiblepaths-mount-propagation.service", can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_FAILURE : EXIT_NAMESPACE, CLD_EXITED); } +#if !HAS_FEATURE_ADDRESS_SANITIZER static int on_spawn_io(sd_event_source *s, int fd, uint32_t revents, void *userdata) { char **result = userdata; char buf[4096]; ssize_t l; - assert_se(s); - assert_se(fd >= 0); + ASSERT_NOT_NULL(s); + ASSERT_GT(fd, 0); l = read(fd, buf, sizeof(buf) - 1); if (l < 0) { @@ -606,20 +636,20 @@ static int on_spawn_io(sd_event_source *s, int fd, uint32_t revents, void *userd buf[l] = '\0'; if (result) - assert_se(strextend(result, buf)); + ASSERT_NOT_NULL(strextend(result, buf)); else log_error("ldd: %s", buf); reenable: /* Re-enable the event source if we did not encounter EOF */ - assert_se(sd_event_source_set_enabled(s, SD_EVENT_ONESHOT) >= 0); + ASSERT_OK(sd_event_source_set_enabled(s, SD_EVENT_ONESHOT)); return 0; } static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) { pid_t *pid = userdata; - assert_se(pid); + ASSERT_NOT_NULL(pid); (void) kill(*pid, SIGKILL); @@ -629,7 +659,7 @@ static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) { static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) { int ret = -EIO; - assert_se(si); + ASSERT_NOT_NULL(si); if (si->si_code == CLD_EXITED) ret = si->si_status; @@ -649,19 +679,19 @@ static int find_libraries(const char *exec, char ***ret) { pid_t pid; int r; - assert_se(exec); - assert_se(ret); + ASSERT_NOT_NULL(exec); + ASSERT_NOT_NULL(ret); - assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD, -1) >= 0); + ASSERT_OK(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD)); - assert_se(pipe2(outpipe, O_NONBLOCK|O_CLOEXEC) == 0); - assert_se(pipe2(errpipe, O_NONBLOCK|O_CLOEXEC) == 0); + ASSERT_OK_ERRNO(pipe2(outpipe, O_NONBLOCK|O_CLOEXEC)); + ASSERT_OK_ERRNO(pipe2(errpipe, O_NONBLOCK|O_CLOEXEC)); r = safe_fork_full("(spawn-ldd)", (int[]) { -EBADF, outpipe[1], errpipe[1] }, NULL, 0, FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGTERM|FORK_REARRANGE_STDIO|FORK_LOG, &pid); - assert_se(r >= 0); + ASSERT_OK(r); if (r == 0) { execlp("ldd", "ldd", exec, NULL); _exit(EXIT_FAILURE); @@ -670,40 +700,40 @@ static int find_libraries(const char *exec, char ***ret) { outpipe[1] = safe_close(outpipe[1]); errpipe[1] = safe_close(errpipe[1]); - assert_se(sd_event_new(&e) >= 0); + ASSERT_OK(sd_event_new(&e)); - assert_se(sd_event_add_time_relative(e, NULL, CLOCK_MONOTONIC, - 10 * USEC_PER_SEC, USEC_PER_SEC, on_spawn_timeout, &pid) >= 0); - assert_se(sd_event_add_io(e, &stdout_source, outpipe[0], EPOLLIN, on_spawn_io, &result) >= 0); - assert_se(sd_event_source_set_enabled(stdout_source, SD_EVENT_ONESHOT) >= 0); - assert_se(sd_event_add_io(e, &stderr_source, errpipe[0], EPOLLIN, on_spawn_io, NULL) >= 0); - assert_se(sd_event_source_set_enabled(stderr_source, SD_EVENT_ONESHOT) >= 0); - assert_se(sd_event_add_child(e, &sigchld_source, pid, WEXITED, on_spawn_sigchld, NULL) >= 0); + ASSERT_OK(sd_event_add_time_relative(e, NULL, CLOCK_MONOTONIC, + 10 * USEC_PER_SEC, USEC_PER_SEC, on_spawn_timeout, &pid)); + ASSERT_OK(sd_event_add_io(e, &stdout_source, outpipe[0], EPOLLIN, on_spawn_io, &result)); + ASSERT_OK(sd_event_source_set_enabled(stdout_source, SD_EVENT_ONESHOT)); + ASSERT_OK(sd_event_add_io(e, &stderr_source, errpipe[0], EPOLLIN, on_spawn_io, NULL)); + ASSERT_OK(sd_event_source_set_enabled(stderr_source, SD_EVENT_ONESHOT)); + ASSERT_OK(sd_event_add_child(e, &sigchld_source, pid, WEXITED, on_spawn_sigchld, NULL)); /* SIGCHLD should be processed after IO is complete */ - assert_se(sd_event_source_set_priority(sigchld_source, SD_EVENT_PRIORITY_NORMAL + 1) >= 0); + ASSERT_OK(sd_event_source_set_priority(sigchld_source, SD_EVENT_PRIORITY_NORMAL + 1)); - assert_se(sd_event_loop(e) >= 0); + ASSERT_OK(sd_event_loop(e)); _cleanup_strv_free_ char **v = NULL; - assert_se(strv_split_newlines_full(&v, result, 0) >= 0); + ASSERT_OK(strv_split_newlines_full(&v, result, 0)); STRV_FOREACH(q, v) { _cleanup_free_ char *word = NULL; const char *p = *q; r = extract_first_word(&p, &word, NULL, 0); - assert_se(r >= 0); + ASSERT_OK(r); if (r == 0) continue; if (path_is_absolute(word)) { - assert_se(strv_consume(&libraries, TAKE_PTR(word)) >= 0); + ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word))); continue; } word = mfree(word); r = extract_first_word(&p, &word, NULL, 0); - assert_se(r >= 0); + ASSERT_OK(r); if (r == 0) continue; @@ -712,12 +742,12 @@ static int find_libraries(const char *exec, char ***ret) { word = mfree(word); r = extract_first_word(&p, &word, NULL, 0); - assert_se(r >= 0); + ASSERT_OK(r); if (r == 0) continue; if (path_is_absolute(word)) { - assert_se(strv_consume(&libraries, TAKE_PTR(word)) >= 0); + ASSERT_OK(strv_consume(&libraries, TAKE_PTR(word))); continue; } } @@ -725,13 +755,15 @@ static int find_libraries(const char *exec, char ***ret) { *ret = TAKE_PTR(libraries); return 0; } +#endif static void test_exec_mount_apivfs(Manager *m) { +#if !HAS_FEATURE_ADDRESS_SANITIZER _cleanup_free_ char *fullpath_touch = NULL, *fullpath_test = NULL, *data = NULL; _cleanup_strv_free_ char **libraries = NULL, **libraries_test = NULL; int r; - assert_se(user_runtime_unit_dir); + ASSERT_NOT_NULL(user_runtime_unit_dir); r = find_executable("ldd", NULL); if (r < 0) { @@ -752,26 +784,27 @@ static void test_exec_mount_apivfs(Manager *m) { if (MANAGER_IS_USER(m) && !have_userns_privileges()) return (void)log_notice("Skipping %s, do not have user namespace privileges", __func__); - assert_se(find_libraries(fullpath_touch, &libraries) >= 0); - assert_se(find_libraries(fullpath_test, &libraries_test) >= 0); - assert_se(strv_extend_strv(&libraries, libraries_test, true) >= 0); + ASSERT_OK(find_libraries(fullpath_touch, &libraries)); + ASSERT_OK(find_libraries(fullpath_test, &libraries_test)); + ASSERT_OK(strv_extend_strv(&libraries, libraries_test, true)); - assert_se(strextend(&data, "[Service]\n")); - assert_se(strextend(&data, "ExecStart=", fullpath_touch, " /aaa\n")); - assert_se(strextend(&data, "ExecStart=", fullpath_test, " -f /aaa\n")); - assert_se(strextend(&data, "BindReadOnlyPaths=", fullpath_touch, "\n")); - assert_se(strextend(&data, "BindReadOnlyPaths=", fullpath_test, "\n")); + ASSERT_NOT_NULL(strextend(&data, "[Service]\n")); + ASSERT_NOT_NULL(strextend(&data, "ExecStart=", fullpath_touch, " /aaa\n")); + ASSERT_NOT_NULL(strextend(&data, "ExecStart=", fullpath_test, " -f /aaa\n")); + ASSERT_NOT_NULL(strextend(&data, "BindReadOnlyPaths=", fullpath_touch, "\n")); + ASSERT_NOT_NULL(strextend(&data, "BindReadOnlyPaths=", fullpath_test, "\n")); STRV_FOREACH(p, libraries) - assert_se(strextend(&data, "BindReadOnlyPaths=", *p, "\n")); + ASSERT_NOT_NULL(strextend(&data, "BindReadOnlyPaths=", *p, "\n")); - assert_se(write_drop_in(user_runtime_unit_dir, "exec-mount-apivfs-no.service", 10, "bind-mount", data) >= 0); + ASSERT_OK(write_drop_in(user_runtime_unit_dir, "exec-mount-apivfs-no.service", 10, "bind-mount", data)); - assert_se(mkdir_p("/tmp/test-exec-mount-apivfs-no/root", 0755) >= 0); + ASSERT_OK(mkdir_p("/tmp/test-exec-mount-apivfs-no/root", 0755)); test(m, "exec-mount-apivfs-no.service", can_unshare || !MANAGER_IS_SYSTEM(m) ? 0 : EXIT_NAMESPACE, CLD_EXITED); (void) rm_rf("/tmp/test-exec-mount-apivfs-no/root", REMOVE_ROOT|REMOVE_PHYSICAL); +#endif } static void test_exec_noexecpaths(Manager *m) { @@ -791,7 +824,7 @@ static void test_exec_temporaryfilesystem(Manager *m) { } static void test_exec_systemcallfilter(Manager *m) { -#if HAVE_SECCOMP +#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER int r; if (!is_seccomp_available()) { @@ -834,7 +867,7 @@ static void test_exec_systemcallfilter(Manager *m) { } static void test_exec_systemcallerrornumber(Manager *m) { -#if HAVE_SECCOMP +#if HAVE_SECCOMP && !HAS_FEATURE_ADDRESS_SANITIZER int r; if (!is_seccomp_available()) { @@ -947,7 +980,7 @@ static char* private_directory_bad(Manager *m) { _cleanup_free_ char *p = NULL; struct stat st; - assert_se(p = path_join(m->prefix[dt], "private")); + ASSERT_NOT_NULL(p = path_join(m->prefix[dt], "private")); if (stat(p, &st) >= 0 && (st.st_mode & (S_IRWXG|S_IRWXO))) @@ -958,6 +991,11 @@ static char* private_directory_bad(Manager *m) { } static void test_exec_dynamicuser(Manager *m) { + if (MANAGER_IS_USER(m)) { + log_notice("Skipping %s for user manager", __func__); + return; + } + _cleanup_free_ char *bad = private_directory_bad(m); if (bad) { log_warning("%s: %s has bad permissions, skipping test.", __func__, bad); @@ -969,7 +1007,7 @@ static void test_exec_dynamicuser(Manager *m) { return; } - int status = can_unshare ? 0 : MANAGER_IS_SYSTEM(m) ? EXIT_NAMESPACE : EXIT_GROUP; + int status = can_unshare ? 0 : EXIT_NAMESPACE; test(m, "exec-dynamicuser-fixeduser.service", status, CLD_EXITED); if (check_user_has_group_with_same_name("adm")) @@ -1025,7 +1063,7 @@ static void test_exec_environmentfile(Manager *m) { int r; r = write_string_file("/tmp/test-exec_environmentfile.conf", e, WRITE_STRING_FILE_CREATE); - assert_se(r == 0); + ASSERT_OK(r); test(m, "exec-environmentfile.service", 0, CLD_EXITED); @@ -1044,19 +1082,19 @@ static void test_exec_passenvironment(Manager *m) { * This is still a good approximation of how a test for MANAGER_SYSTEM * would work. */ - assert_se(setenv("VAR1", "word1 word2", 1) == 0); - assert_se(setenv("VAR2", "word3", 1) == 0); - assert_se(setenv("VAR3", "$word 5 6", 1) == 0); - assert_se(setenv("VAR4", "new\nline", 1) == 0); - assert_se(setenv("VAR5", "passwordwithbackslashes", 1) == 0); + ASSERT_OK_ERRNO(setenv("VAR1", "word1 word2", 1)); + ASSERT_OK_ERRNO(setenv("VAR2", "word3", 1)); + ASSERT_OK_ERRNO(setenv("VAR3", "$word 5 6", 1)); + ASSERT_OK_ERRNO(setenv("VAR4", "new\nline", 1)); + ASSERT_OK_ERRNO(setenv("VAR5", "passwordwithbackslashes", 1)); test(m, "exec-passenvironment.service", 0, CLD_EXITED); test(m, "exec-passenvironment-repeated.service", 0, CLD_EXITED); test(m, "exec-passenvironment-empty.service", 0, CLD_EXITED); - assert_se(unsetenv("VAR1") == 0); - assert_se(unsetenv("VAR2") == 0); - assert_se(unsetenv("VAR3") == 0); - assert_se(unsetenv("VAR4") == 0); - assert_se(unsetenv("VAR5") == 0); + ASSERT_OK_ERRNO(unsetenv("VAR1")); + ASSERT_OK_ERRNO(unsetenv("VAR2")); + ASSERT_OK_ERRNO(unsetenv("VAR3")); + ASSERT_OK_ERRNO(unsetenv("VAR4")); + ASSERT_OK_ERRNO(unsetenv("VAR5")); test(m, "exec-passenvironment-absent.service", 0, CLD_EXITED); } @@ -1237,7 +1275,11 @@ static void test_exec_specifier(Manager *m) { static void test_exec_standardinput(Manager *m) { test(m, "exec-standardinput-data.service", 0, CLD_EXITED); test(m, "exec-standardinput-file.service", 0, CLD_EXITED); + + ExecOutput saved = m->defaults.std_output; + m->defaults.std_output = EXEC_OUTPUT_NULL; test(m, "exec-standardinput-file-cat.service", 0, CLD_EXITED); + m->defaults.std_output = saved; } static void test_exec_standardoutput(Manager *m) { @@ -1334,34 +1376,34 @@ static void run_tests(RuntimeScope scope, char **patterns) { {}, }; - assert_se(unsetenv("USER") == 0); - assert_se(unsetenv("LOGNAME") == 0); - assert_se(unsetenv("SHELL") == 0); - assert_se(unsetenv("HOME") == 0); - assert_se(unsetenv("TMPDIR") == 0); + ASSERT_OK_ERRNO(unsetenv("USER")); + ASSERT_OK_ERRNO(unsetenv("LOGNAME")); + ASSERT_OK_ERRNO(unsetenv("SHELL")); + ASSERT_OK_ERRNO(unsetenv("HOME")); + ASSERT_OK_ERRNO(unsetenv("TMPDIR")); /* Unset VARx, especially, VAR1, VAR2 and VAR3, which are used in the PassEnvironment test cases, * otherwise (and if they are present in the environment), `manager_default_environment` will copy * them into the default environment which is passed to each created job, which will make the tests * that expect those not to be present to fail. */ - assert_se(unsetenv("VAR1") == 0); - assert_se(unsetenv("VAR2") == 0); - assert_se(unsetenv("VAR3") == 0); - assert_se(unsetenv("VAR4") == 0); - assert_se(unsetenv("VAR5") == 0); + ASSERT_OK_ERRNO(unsetenv("VAR1")); + ASSERT_OK_ERRNO(unsetenv("VAR2")); + ASSERT_OK_ERRNO(unsetenv("VAR3")); + ASSERT_OK_ERRNO(unsetenv("VAR4")); + ASSERT_OK_ERRNO(unsetenv("VAR5")); - assert_se(runtime_dir = setup_fake_runtime_dir()); - assert_se(user_runtime_unit_dir = path_join(runtime_dir, "systemd/user")); - assert_se(unit_paths = strjoin(PRIVATE_UNIT_DIR, ":", user_runtime_unit_dir)); - assert_se(set_unit_path(unit_paths) >= 0); + ASSERT_NOT_NULL(runtime_dir = setup_fake_runtime_dir()); + ASSERT_NOT_NULL(user_runtime_unit_dir = path_join(runtime_dir, "systemd/user")); + ASSERT_NOT_NULL(unit_paths = strjoin(PRIVATE_UNIT_DIR, ":", user_runtime_unit_dir)); + ASSERT_OK(set_unit_path(unit_paths)); r = manager_new(scope, MANAGER_TEST_RUN_BASIC, &m); if (manager_errno_skip_test(r)) return (void) log_tests_skipped_errno(r, "manager_new"); - assert_se(r >= 0); + ASSERT_OK(r); - m->defaults.std_output = EXEC_OUTPUT_NULL; /* don't rely on host journald */ - assert_se(manager_startup(m, NULL, NULL, NULL) >= 0); + m->defaults.std_output = EXEC_OUTPUT_INHERIT; /* don't rely on host journald */ + ASSERT_OK(manager_startup(m, NULL, NULL, NULL)); /* Uncomment below if you want to make debugging logs stored to journal. */ //manager_override_log_target(m, LOG_TARGET_AUTO); @@ -1400,36 +1442,66 @@ static int prepare_ns(const char *process_name) { FORK_NEW_MOUNTNS | FORK_MOUNTNS_SLAVE, NULL); - assert_se(r >= 0); + ASSERT_OK(r); if (r == 0) { - _cleanup_free_ char *unit_dir = NULL; + _cleanup_free_ char *unit_dir = NULL, *build_dir = NULL, *build_dir_mount = NULL; + int ret; /* Make "/" read-only. */ - assert_se(mount_nofollow_verbose(LOG_DEBUG, NULL, "/", NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL) >= 0); + ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, NULL, "/", NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL)); /* Creating a new user namespace in the above means all MS_SHARED mounts become MS_SLAVE. * Let's put them back to MS_SHARED here, since that's what we want as defaults. (This will * not reconnect propagation, but simply create new peer groups for all our mounts). */ - assert_se(mount_follow_verbose(LOG_DEBUG, NULL, "/", NULL, MS_SHARED|MS_REC, NULL) >= 0); + ASSERT_OK(mount_follow_verbose(LOG_DEBUG, NULL, "/", NULL, MS_SHARED|MS_REC, NULL)); - assert_se(mkdir_p(PRIVATE_UNIT_DIR, 0755) >= 0); - assert_se(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", PRIVATE_UNIT_DIR, "tmpfs", MS_NOSUID|MS_NODEV, NULL) >= 0); + ASSERT_OK(mkdir_p(PRIVATE_UNIT_DIR, 0755)); + ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", PRIVATE_UNIT_DIR, "tmpfs", MS_NOSUID|MS_NODEV, NULL)); + /* Mark our test "playground" as MS_SLAVE, so we can MS_MOVE mounts underneath it. */ + ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, NULL, PRIVATE_UNIT_DIR, NULL, MS_SLAVE, NULL)); /* Copy unit files to make them accessible even when unprivileged. */ - assert_se(get_testdata_dir("test-execute/", &unit_dir) >= 0); - assert_se(copy_directory_at(AT_FDCWD, unit_dir, AT_FDCWD, PRIVATE_UNIT_DIR, COPY_MERGE_EMPTY) >= 0); + ASSERT_OK(get_testdata_dir("test-execute/", &unit_dir)); + ASSERT_OK(copy_directory_at(AT_FDCWD, unit_dir, AT_FDCWD, PRIVATE_UNIT_DIR, COPY_MERGE_EMPTY)); /* Mount tmpfs on the following directories to make not StateDirectory= or friends disturb the host. */ + ret = get_build_exec_dir(&build_dir); + if (ret != -ENOEXEC) + ASSERT_OK(ret); + + if (build_dir) { + /* Account for a build directory being in one of the soon-to-be-tmpfs directories. If we + * overmount it with an empty tmpfs, manager_new() will pin the wrong systemd-executor binary, + * which can then lead to unexpected (and painful to debug) test fails. */ + ASSERT_OK_ERRNO(access(build_dir, F_OK)); + ASSERT_NOT_NULL(build_dir_mount = path_join(PRIVATE_UNIT_DIR, "build_dir")); + ASSERT_OK(mkdir_p(build_dir_mount, 0755)); + ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, build_dir, build_dir_mount, NULL, MS_BIND, NULL)); + } + FOREACH_STRING(p, "/dev/shm", "/root", "/tmp", "/var/tmp", "/var/lib") - assert_se(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, NULL) >= 0); + ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, NULL)); + + if (build_dir_mount) { + ret = RET_NERRNO(access(build_dir, F_OK)); + if (ret != -ENOENT) + ASSERT_OK(ret); + + if (ret == -ENOENT) { + /* The build directory got overmounted by tmpfs, so let's use the "backup" bind mount to + * bring it back. */ + ASSERT_OK(mkdir_p(build_dir, 0755)); + ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, build_dir_mount, build_dir, NULL, MS_MOVE, NULL)); + } + } /* Prepare credstore like tmpfiles.d/credstore.conf for LoadCredential= tests. */ FOREACH_STRING(p, "/run/credstore", "/run/credstore.encrypted") { - assert_se(mkdir_p(p, 0) >= 0); - assert_se(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, "mode=0000") >= 0); + ASSERT_OK(mkdir_p(p, 0)); + ASSERT_OK(mount_nofollow_verbose(LOG_DEBUG, "tmpfs", p, "tmpfs", MS_NOSUID|MS_NODEV, "mode=0000")); } - assert_se(write_string_file("/run/credstore/test-execute.load-credential", "foo", WRITE_STRING_FILE_CREATE) >= 0); + ASSERT_OK(write_string_file("/run/credstore/test-execute.load-credential", "foo", WRITE_STRING_FILE_CREATE)); } return r; @@ -1442,7 +1514,7 @@ TEST(run_tests_root) { return (void) log_tests_skipped("unshare() is disabled"); /* safe_fork() clears saved_argv in the child process. Let's copy it. */ - assert_se(filters = strv_copy(strv_skip(saved_argv, 1))); + ASSERT_NOT_NULL(filters = strv_copy(strv_skip(saved_argv, 1))); if (prepare_ns("(test-execute-root)") == 0) { can_unshare = true; @@ -1468,19 +1540,18 @@ TEST(run_tests_without_unshare) { return (void) log_tests_skipped("Seccomp not available, cannot run unshare() filtered tests"); /* safe_fork() clears saved_argv in the child process. Let's copy it. */ - assert_se(filters = strv_copy(strv_skip(saved_argv, 1))); + ASSERT_NOT_NULL(filters = strv_copy(strv_skip(saved_argv, 1))); if (prepare_ns("(test-execute-without-unshare)") == 0) { _cleanup_hashmap_free_ Hashmap *s = NULL; r = seccomp_syscall_resolve_name("unshare"); - assert_se(r != __NR_SCMP_ERROR); - assert_se(hashmap_ensure_put(&s, NULL, UINT32_TO_PTR(r + 1), INT_TO_PTR(-1)) >= 0); - assert_se(seccomp_load_syscall_filter_set_raw(SCMP_ACT_ALLOW, s, SCMP_ACT_ERRNO(EOPNOTSUPP), true) >= 0); + ASSERT_NE(r, __NR_SCMP_ERROR); + ASSERT_OK(hashmap_ensure_put(&s, NULL, UINT32_TO_PTR(r + 1), INT_TO_PTR(-1))); + ASSERT_OK(seccomp_load_syscall_filter_set_raw(SCMP_ACT_ALLOW, s, SCMP_ACT_ERRNO(EOPNOTSUPP), true)); /* Check unshare() is actually filtered. */ - assert_se(unshare(CLONE_NEWNS) < 0); - assert_se(errno == EOPNOTSUPP); + ASSERT_ERROR_ERRNO(unshare(CLONE_NEWNS), EOPNOTSUPP); can_unshare = false; run_tests(RUNTIME_SCOPE_SYSTEM, filters); @@ -1498,10 +1569,10 @@ TEST(run_tests_unprivileged) { return (void) log_tests_skipped("unshare() is disabled"); /* safe_fork() clears saved_argv in the child process. Let's copy it. */ - assert_se(filters = strv_copy(strv_skip(saved_argv, 1))); + ASSERT_NOT_NULL(filters = strv_copy(strv_skip(saved_argv, 1))); if (prepare_ns("(test-execute-unprivileged)") == 0) { - assert_se(capability_bounding_set_drop(0, /* right_now = */ true) >= 0); + ASSERT_OK(capability_bounding_set_drop(0, /* right_now = */ true)); can_unshare = false; run_tests(RUNTIME_SCOPE_USER, filters); diff --git a/src/test/test-exit-status.c b/src/test/test-exit-status.c index 86d3976..aab8193 100644 --- a/src/test/test-exit-status.c +++ b/src/test/test-exit-status.c @@ -29,8 +29,8 @@ TEST(exit_status_from_string) { } TEST(exit_status_NUMA_POLICY) { - assert_se(streq(exit_status_to_string(EXIT_NUMA_POLICY, EXIT_STATUS_FULL), "NUMA_POLICY")); - assert_se(streq(exit_status_to_string(EXIT_NUMA_POLICY, EXIT_STATUS_SYSTEMD), "NUMA_POLICY")); + ASSERT_STREQ(exit_status_to_string(EXIT_NUMA_POLICY, EXIT_STATUS_FULL), "NUMA_POLICY"); + ASSERT_STREQ(exit_status_to_string(EXIT_NUMA_POLICY, EXIT_STATUS_SYSTEMD), "NUMA_POLICY"); assert_se(!exit_status_to_string(EXIT_NUMA_POLICY, EXIT_STATUS_BSD)); assert_se(!exit_status_to_string(EXIT_NUMA_POLICY, EXIT_STATUS_LSB)); } diff --git a/src/test/test-extract-word.c b/src/test/test-extract-word.c index 6e12fbe..1bc4088 100644 --- a/src/test/test-extract-word.c +++ b/src/test/test-extract-word.c @@ -14,12 +14,12 @@ TEST(extract_first_word) { p = original = "foobar waldo"; assert_se(extract_first_word(&p, &t, NULL, 0) > 0); - assert_se(streq(t, "foobar")); + ASSERT_STREQ(t, "foobar"); free(t); assert_se(p == original + 7); assert_se(extract_first_word(&p, &t, NULL, 0) > 0); - assert_se(streq(t, "waldo")); + ASSERT_STREQ(t, "waldo"); free(t); assert_se(isempty(p)); @@ -29,12 +29,12 @@ TEST(extract_first_word) { p = original = "\"foobar\" \'waldo\'"; assert_se(extract_first_word(&p, &t, NULL, 0) > 0); - assert_se(streq(t, "\"foobar\"")); + ASSERT_STREQ(t, "\"foobar\""); free(t); assert_se(p == original + 9); assert_se(extract_first_word(&p, &t, NULL, 0) > 0); - assert_se(streq(t, "\'waldo\'")); + ASSERT_STREQ(t, "\'waldo\'"); free(t); assert_se(isempty(p)); @@ -44,12 +44,12 @@ TEST(extract_first_word) { p = original = "\"foobar\" \'waldo\'"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE) > 0); - assert_se(streq(t, "foobar")); + ASSERT_STREQ(t, "foobar"); free(t); assert_se(p == original + 9); assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE) > 0); - assert_se(streq(t, "waldo")); + ASSERT_STREQ(t, "waldo"); free(t); assert_se(isempty(p)); @@ -59,7 +59,7 @@ TEST(extract_first_word) { p = original = "\""; assert_se(extract_first_word(&p, &t, NULL, 0) == 1); - assert_se(streq(t, "\"")); + ASSERT_STREQ(t, "\""); free(t); assert_se(isempty(p)); @@ -69,7 +69,7 @@ TEST(extract_first_word) { p = original = "\'"; assert_se(extract_first_word(&p, &t, NULL, 0) == 1); - assert_se(streq(t, "\'")); + ASSERT_STREQ(t, "\'"); free(t); assert_se(isempty(p)); @@ -79,31 +79,31 @@ TEST(extract_first_word) { p = original = "\'fooo"; assert_se(extract_first_word(&p, &t, NULL, 0) == 1); - assert_se(streq(t, "\'fooo")); + ASSERT_STREQ(t, "\'fooo"); free(t); assert_se(isempty(p)); p = original = "KEY=val \"KEY2=val with space\" \"KEY3=val with \\\"quotation\\\"\""; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE) == 1); - assert_se(streq(t, "KEY=val")); + ASSERT_STREQ(t, "KEY=val"); free(t); assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE) == 1); - assert_se(streq(t, "KEY2=val with space")); + ASSERT_STREQ(t, "KEY2=val with space"); free(t); assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE) == 1); - assert_se(streq(t, "KEY3=val with \"quotation\"")); + ASSERT_STREQ(t, "KEY3=val with \"quotation\""); free(t); assert_se(isempty(p)); p = original = "KEY=val \"KEY2=val space\" \"KEY3=val with \\\"quotation\\\"\""; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_RETAIN_ESCAPE) == 1); - assert_se(streq(t, "KEY=val")); + ASSERT_STREQ(t, "KEY=val"); free(t); assert_se(extract_first_word(&p, &t, NULL, EXTRACT_RETAIN_ESCAPE) == 1); - assert_se(streq(t, "\"KEY2=val")); + ASSERT_STREQ(t, "\"KEY2=val"); free(t); assert_se(extract_first_word(&p, &t, NULL, EXTRACT_RETAIN_ESCAPE) == 1); - assert_se(streq(t, "space\"")); + ASSERT_STREQ(t, "space\""); free(t); assert_se(startswith(p, "\"KEY3=")); @@ -113,78 +113,78 @@ TEST(extract_first_word) { p = original = "\'fooo"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE|EXTRACT_RELAX) > 0); - assert_se(streq(t, "fooo")); + ASSERT_STREQ(t, "fooo"); free(t); assert_se(isempty(p)); p = original = "\"fooo"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE|EXTRACT_RELAX) > 0); - assert_se(streq(t, "fooo")); + ASSERT_STREQ(t, "fooo"); free(t); assert_se(isempty(p)); p = original = "yay\'foo\'bar"; assert_se(extract_first_word(&p, &t, NULL, 0) > 0); - assert_se(streq(t, "yay\'foo\'bar")); + ASSERT_STREQ(t, "yay\'foo\'bar"); free(t); assert_se(isempty(p)); p = original = "yay\'foo\'bar"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE) > 0); - assert_se(streq(t, "yayfoobar")); + ASSERT_STREQ(t, "yayfoobar"); free(t); assert_se(isempty(p)); p = original = " foobar "; assert_se(extract_first_word(&p, &t, NULL, 0) > 0); - assert_se(streq(t, "foobar")); + ASSERT_STREQ(t, "foobar"); free(t); assert_se(isempty(p)); p = original = " foo\\ba\\x6ar "; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_CUNESCAPE) > 0); - assert_se(streq(t, "foo\ba\x6ar")); + ASSERT_STREQ(t, "foo\ba\x6ar"); free(t); assert_se(isempty(p)); p = original = " foo\\ba\\x6ar "; assert_se(extract_first_word(&p, &t, NULL, 0) > 0); - assert_se(streq(t, "foobax6ar")); + ASSERT_STREQ(t, "foobax6ar"); free(t); assert_se(isempty(p)); p = original = " f\\u00f6o \"pi\\U0001F4A9le\" "; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_CUNESCAPE) > 0); - assert_se(streq(t, "föo")); + ASSERT_STREQ(t, "föo"); free(t); assert_se(p == original + 13); assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE|EXTRACT_CUNESCAPE) > 0); - assert_se(streq(t, "pi\360\237\222\251le")); + ASSERT_STREQ(t, "pi\360\237\222\251le"); free(t); assert_se(isempty(p)); p = original = "fooo\\"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_RELAX) > 0); - assert_se(streq(t, "fooo")); + ASSERT_STREQ(t, "fooo"); free(t); assert_se(isempty(p)); p = original = "fooo\\"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNESCAPE_RELAX) > 0); - assert_se(streq(t, "fooo\\")); + ASSERT_STREQ(t, "fooo\\"); free(t); assert_se(isempty(p)); p = original = "fooo\\"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNESCAPE_RELAX|EXTRACT_RELAX) > 0); - assert_se(streq(t, "fooo\\")); + ASSERT_STREQ(t, "fooo\\"); free(t); assert_se(isempty(p)); p = original = "fooo\\"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_RELAX) > 0); - assert_se(streq(t, "fooo\\")); + ASSERT_STREQ(t, "fooo\\"); free(t); assert_se(isempty(p)); @@ -194,18 +194,18 @@ TEST(extract_first_word) { p = original = "\"foo\\"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE|EXTRACT_RELAX) > 0); - assert_se(streq(t, "foo")); + ASSERT_STREQ(t, "foo"); free(t); assert_se(isempty(p)); p = original = "foo::bar"; assert_se(extract_first_word(&p, &t, ":", 0) == 1); - assert_se(streq(t, "foo")); + ASSERT_STREQ(t, "foo"); free(t); assert_se(p == original + 5); assert_se(extract_first_word(&p, &t, ":", 0) == 1); - assert_se(streq(t, "bar")); + ASSERT_STREQ(t, "bar"); free(t); assert_se(isempty(p)); @@ -215,12 +215,12 @@ TEST(extract_first_word) { p = original = "foo\\:bar::waldo"; assert_se(extract_first_word(&p, &t, ":", 0) == 1); - assert_se(streq(t, "foo:bar")); + ASSERT_STREQ(t, "foo:bar"); free(t); assert_se(p == original + 10); assert_se(extract_first_word(&p, &t, ":", 0) == 1); - assert_se(streq(t, "waldo")); + ASSERT_STREQ(t, "waldo"); free(t); assert_se(isempty(p)); @@ -234,31 +234,31 @@ TEST(extract_first_word) { p = original = "\"foo\\"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE|EXTRACT_UNESCAPE_RELAX|EXTRACT_RELAX) > 0); - assert_se(streq(t, "foo\\")); + ASSERT_STREQ(t, "foo\\"); free(t); assert_se(isempty(p)); p = original = "\"foo\\"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE|EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_RELAX|EXTRACT_RELAX) > 0); - assert_se(streq(t, "foo\\")); + ASSERT_STREQ(t, "foo\\"); free(t); assert_se(isempty(p)); p = original = "fooo\\ bar quux"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_RELAX) > 0); - assert_se(streq(t, "fooo bar")); + ASSERT_STREQ(t, "fooo bar"); free(t); assert_se(p == original + 10); p = original = "fooo\\ bar quux"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNESCAPE_RELAX) > 0); - assert_se(streq(t, "fooo bar")); + ASSERT_STREQ(t, "fooo bar"); free(t); assert_se(p == original + 10); p = original = "fooo\\ bar quux"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNESCAPE_RELAX|EXTRACT_RELAX) > 0); - assert_se(streq(t, "fooo bar")); + ASSERT_STREQ(t, "fooo bar"); free(t); assert_se(p == original + 10); @@ -268,7 +268,7 @@ TEST(extract_first_word) { p = original = "fooo\\ bar quux"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_RELAX) > 0); - assert_se(streq(t, "fooo\\ bar")); + ASSERT_STREQ(t, "fooo\\ bar"); free(t); assert_se(p == original + 10); @@ -278,54 +278,54 @@ TEST(extract_first_word) { p = original = "\\w+@\\K[\\d.]+"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_RELAX) > 0); - assert_se(streq(t, "\\w+@\\K[\\d.]+")); + ASSERT_STREQ(t, "\\w+@\\K[\\d.]+"); free(t); assert_se(isempty(p)); p = original = "\\w+\\b"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_RELAX) > 0); - assert_se(streq(t, "\\w+\b")); + ASSERT_STREQ(t, "\\w+\b"); free(t); assert_se(isempty(p)); p = original = "-N ''"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE) > 0); - assert_se(streq(t, "-N")); + ASSERT_STREQ(t, "-N"); free(t); assert_se(p == original + 3); assert_se(extract_first_word(&p, &t, NULL, EXTRACT_UNQUOTE) > 0); - assert_se(streq(t, "")); + ASSERT_STREQ(t, ""); free(t); assert_se(isempty(p)); p = original = ":foo\\:bar::waldo:"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_DONT_COALESCE_SEPARATORS) == 1); assert_se(t); - assert_se(streq(t, "")); + ASSERT_STREQ(t, ""); free(t); assert_se(p == original + 1); assert_se(extract_first_word(&p, &t, ":", EXTRACT_DONT_COALESCE_SEPARATORS) == 1); - assert_se(streq(t, "foo:bar")); + ASSERT_STREQ(t, "foo:bar"); free(t); assert_se(p == original + 10); assert_se(extract_first_word(&p, &t, ":", EXTRACT_DONT_COALESCE_SEPARATORS) == 1); assert_se(t); - assert_se(streq(t, "")); + ASSERT_STREQ(t, ""); free(t); assert_se(p == original + 11); assert_se(extract_first_word(&p, &t, ":", EXTRACT_DONT_COALESCE_SEPARATORS) == 1); - assert_se(streq(t, "waldo")); + ASSERT_STREQ(t, "waldo"); free(t); assert_se(p == original + 17); assert_se(extract_first_word(&p, &t, ":", EXTRACT_DONT_COALESCE_SEPARATORS) == 1); - assert_se(streq(t, "")); + ASSERT_STREQ(t, ""); free(t); - assert_se(p == NULL); + ASSERT_NULL(p); assert_se(extract_first_word(&p, &t, ":", EXTRACT_DONT_COALESCE_SEPARATORS) == 0); assert_se(!t); @@ -333,81 +333,81 @@ TEST(extract_first_word) { p = "foo\\xbar"; assert_se(extract_first_word(&p, &t, NULL, 0) > 0); - assert_se(streq(t, "fooxbar")); + ASSERT_STREQ(t, "fooxbar"); free(t); - assert_se(p == NULL); + ASSERT_NULL(p); p = "foo\\xbar"; assert_se(extract_first_word(&p, &t, NULL, EXTRACT_RETAIN_ESCAPE) > 0); - assert_se(streq(t, "foo\\xbar")); + ASSERT_STREQ(t, "foo\\xbar"); free(t); - assert_se(p == NULL); + ASSERT_NULL(p); p = "\\:"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, ":")); + ASSERT_STREQ(t, ":"); free(t); - assert_se(p == NULL); + ASSERT_NULL(p); p = "a\\:b"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, "a:b")); + ASSERT_STREQ(t, "a:b"); free(t); - assert_se(p == NULL); + ASSERT_NULL(p); p = "a\\ b:c"; assert_se(extract_first_word(&p, &t, WHITESPACE ":", EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, "a b")); + ASSERT_STREQ(t, "a b"); free(t); assert_se(extract_first_word(&p, &t, WHITESPACE ":", EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, "c")); + ASSERT_STREQ(t, "c"); free(t); - assert_se(p == NULL); + ASSERT_NULL(p); p = "a\\ b:c\\x"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_UNESCAPE_SEPARATORS) == -EINVAL); p = "a\\\\ b:c\\\\x"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, "a\\ b")); + ASSERT_STREQ(t, "a\\ b"); free(t); assert_se(extract_first_word(&p, &t, ":", EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, "c\\x")); + ASSERT_STREQ(t, "c\\x"); free(t); - assert_se(p == NULL); + ASSERT_NULL(p); p = "\\:"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, ":")); + ASSERT_STREQ(t, ":"); free(t); - assert_se(p == NULL); + ASSERT_NULL(p); p = "a\\:b"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, "a:b")); + ASSERT_STREQ(t, "a:b"); free(t); - assert_se(p == NULL); + ASSERT_NULL(p); p = "a\\ b:c"; assert_se(extract_first_word(&p, &t, WHITESPACE ":", EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, "a b")); + ASSERT_STREQ(t, "a b"); free(t); assert_se(extract_first_word(&p, &t, WHITESPACE ":", EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, "c")); + ASSERT_STREQ(t, "c"); free(t); - assert_se(p == NULL); + ASSERT_NULL(p); p = "a\\ b:c\\x"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS) == -EINVAL); p = "a\\\\ b:c\\\\x"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, "a\\ b")); + ASSERT_STREQ(t, "a\\ b"); free(t); assert_se(extract_first_word(&p, &t, ":", EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, "c\\x")); + ASSERT_STREQ(t, "c\\x"); free(t); - assert_se(p == NULL); + ASSERT_NULL(p); p = "\\:"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_CUNESCAPE) == -EINVAL); @@ -415,124 +415,138 @@ TEST(extract_first_word) { p = "a\\:b"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_CUNESCAPE) == -EINVAL); assert_se(extract_first_word(&p, &t, ":", EXTRACT_CUNESCAPE) == 1); - assert_se(streq(t, "b")); + ASSERT_STREQ(t, "b"); free(t); p = "a\\ b:c"; assert_se(extract_first_word(&p, &t, WHITESPACE ":", EXTRACT_CUNESCAPE) == -EINVAL); assert_se(extract_first_word(&p, &t, WHITESPACE ":", EXTRACT_CUNESCAPE) == 1); - assert_se(streq(t, "b")); + ASSERT_STREQ(t, "b"); free(t); assert_se(extract_first_word(&p, &t, WHITESPACE ":", EXTRACT_CUNESCAPE) == 1); - assert_se(streq(t, "c")); + ASSERT_STREQ(t, "c"); free(t); - assert_se(p == NULL); + ASSERT_NULL(p); p = original = "foobar=\"waldo\"maldo, baldo"; assert_se(extract_first_word(&p, &t, "=\", ", 0) > 0); - assert_se(streq(t, "foobar")); + ASSERT_STREQ(t, "foobar"); free(t); assert_se(extract_first_word(&p, &t, "=\", ", 0) > 0); - assert_se(streq(t, "waldo")); + ASSERT_STREQ(t, "waldo"); free(t); assert_se(extract_first_word(&p, &t, "=\", ", 0) > 0); - assert_se(streq(t, "maldo")); + ASSERT_STREQ(t, "maldo"); free(t); assert_se(extract_first_word(&p, &t, "=\", ", 0) > 0); - assert_se(streq(t, "baldo")); + ASSERT_STREQ(t, "baldo"); free(t); p = original = "mode=\"1777\",size=\"10%\",nr_inodes=\"400\"k,uid=\"496,,107\"520,gi\"\"'d=49610,'\"\"7520,context=\"system_u:object_r:svirt_sandbox_file_t:s0:c0,c1\""; assert_se(extract_first_word(&p, &t, ",", EXTRACT_KEEP_QUOTE) > 0); - assert_se(streq(t, "mode=\"1777\"")); + ASSERT_STREQ(t, "mode=\"1777\""); free(t); assert_se(extract_first_word(&p, &t, ",", EXTRACT_KEEP_QUOTE) > 0); - assert_se(streq(t, "size=\"10%\"")); + ASSERT_STREQ(t, "size=\"10%\""); free(t); assert_se(extract_first_word(&p, &t, ",", EXTRACT_KEEP_QUOTE) > 0); - assert_se(streq(t, "nr_inodes=\"400\"k")); + ASSERT_STREQ(t, "nr_inodes=\"400\"k"); free(t); assert_se(extract_first_word(&p, &t, ",", EXTRACT_KEEP_QUOTE) > 0); - assert_se(streq(t, "uid=\"496,,107\"520")); + ASSERT_STREQ(t, "uid=\"496,,107\"520"); free(t); assert_se(extract_first_word(&p, &t, ",", EXTRACT_KEEP_QUOTE) > 0); - assert_se(streq(t, "gi\"\"'d=49610,'\"\"7520")); + ASSERT_STREQ(t, "gi\"\"'d=49610,'\"\"7520"); free(t); assert_se(extract_first_word(&p, &t, ",", EXTRACT_KEEP_QUOTE) > 0); - assert_se(streq(t, "context=\"system_u:object_r:svirt_sandbox_file_t:s0:c0,c1\"")); + ASSERT_STREQ(t, "context=\"system_u:object_r:svirt_sandbox_file_t:s0:c0,c1\""); free(t); p = original = "mode=\"1777\",size=\"10%\",nr_inodes=\"400\"k,uid=\"496,,107\"520,gi\"\"'d=49610,'\"\"7520,context=\"system_u:object_r:svirt_sandbox_file_t:s0:c0,c1\""; assert_se(extract_first_word(&p, &t, ",", EXTRACT_UNQUOTE) > 0); - assert_se(streq(t, "mode=1777")); + ASSERT_STREQ(t, "mode=1777"); free(t); assert_se(extract_first_word(&p, &t, ",", EXTRACT_UNQUOTE) > 0); - assert_se(streq(t, "size=10%")); + ASSERT_STREQ(t, "size=10%"); free(t); assert_se(extract_first_word(&p, &t, ",", EXTRACT_UNQUOTE) > 0); - assert_se(streq(t, "nr_inodes=400k")); + ASSERT_STREQ(t, "nr_inodes=400k"); free(t); assert_se(extract_first_word(&p, &t, ",", EXTRACT_UNQUOTE) > 0); - assert_se(streq(t, "uid=496,,107520")); + ASSERT_STREQ(t, "uid=496,,107520"); free(t); assert_se(extract_first_word(&p, &t, ",", EXTRACT_UNQUOTE) > 0); - assert_se(streq(t, "gid=49610,7520")); + ASSERT_STREQ(t, "gid=49610,7520"); free(t); assert_se(extract_first_word(&p, &t, ",", EXTRACT_UNQUOTE) > 0); - assert_se(streq(t, "context=system_u:object_r:svirt_sandbox_file_t:s0:c0,c1")); + ASSERT_STREQ(t, "context=system_u:object_r:svirt_sandbox_file_t:s0:c0,c1"); free(t); p = "a:b"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_RETAIN_SEPARATORS) == 1); - assert_se(streq(t, "a")); - assert_se(streq(p, ":b")); + ASSERT_STREQ(t, "a"); + ASSERT_STREQ(p, ":b"); free(t); assert_se(extract_first_word(&p, &t, ":", EXTRACT_RETAIN_SEPARATORS) == 1); - assert_se(streq(t, "b")); + ASSERT_STREQ(t, "b"); free(t); p = "a>:b"; assert_se(extract_first_word(&p, &t, ">:", EXTRACT_RETAIN_SEPARATORS) == 1); - assert_se(streq(t, "a")); - assert_se(streq(p, ">:b")); + ASSERT_STREQ(t, "a"); + ASSERT_STREQ(p, ">:b"); free(t); assert_se(extract_first_word(&p, &t, ">:", EXTRACT_RETAIN_SEPARATORS) == 1); - assert_se(streq(t, "b")); + ASSERT_STREQ(t, "b"); free(t); p = "a>:b"; assert_se(extract_first_word(&p, &t, ">:", EXTRACT_RETAIN_SEPARATORS|EXTRACT_DONT_COALESCE_SEPARATORS) == 1); - assert_se(streq(t, "a")); - assert_se(streq(p, ">:b")); + ASSERT_STREQ(t, "a"); + ASSERT_STREQ(p, ">:b"); free(t); assert_se(extract_first_word(&p, &t, ">:", EXTRACT_RETAIN_SEPARATORS|EXTRACT_DONT_COALESCE_SEPARATORS) == 1); - assert_se(streq(t, "")); - assert_se(streq(p, ">:b")); + ASSERT_STREQ(t, ""); + ASSERT_STREQ(p, ">:b"); free(t); p = "a\\:b"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_RETAIN_SEPARATORS|EXTRACT_RETAIN_ESCAPE) == 1); - assert_se(streq(t, "a\\")); - assert_se(streq(p, ":b")); + ASSERT_STREQ(t, "a\\"); + ASSERT_STREQ(p, ":b"); free(t); p = "a\\:b"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_RETAIN_SEPARATORS) == 1); - assert_se(streq(t, "a:b")); + ASSERT_STREQ(t, "a:b"); assert_se(!p); free(t); p = "a\\:b"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_RETAIN_SEPARATORS|EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, "a:b")); + ASSERT_STREQ(t, "a:b"); assert_se(!p); free(t); p = "a\\:a:b"; assert_se(extract_first_word(&p, &t, ":", EXTRACT_RETAIN_SEPARATORS|EXTRACT_UNESCAPE_SEPARATORS) == 1); - assert_se(streq(t, "a:a")); - assert_se(streq(p, ":b")); + ASSERT_STREQ(t, "a:a"); + ASSERT_STREQ(p, ":b"); free(t); + + p = original = "zażółcić 👊🔪💐 가너도루"; + assert_se(extract_first_word(&p, &t, NULL, 0) > 0); + ASSERT_STREQ(t, "zażółcić"); + free(t); + assert_se(p == original + 13); + + assert_se(extract_first_word(&p, &t, NULL, 0) > 0); + ASSERT_STREQ(t, "👊🔪💐"); + free(t); + assert_se(extract_first_word(&p, &t, NULL, 0) > 0); + ASSERT_STREQ(t, "가너도루"); + free(t); + assert_se(isempty(p)); } TEST(extract_first_word_and_warn) { @@ -541,12 +555,12 @@ TEST(extract_first_word_and_warn) { p = original = "foobar waldo"; assert_se(extract_first_word_and_warn(&p, &t, NULL, 0, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "foobar")); + ASSERT_STREQ(t, "foobar"); free(t); assert_se(p == original + 7); assert_se(extract_first_word_and_warn(&p, &t, NULL, 0, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "waldo")); + ASSERT_STREQ(t, "waldo"); free(t); assert_se(isempty(p)); @@ -556,12 +570,12 @@ TEST(extract_first_word_and_warn) { p = original = "\"foobar\" \'waldo\'"; assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_UNQUOTE, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "foobar")); + ASSERT_STREQ(t, "foobar"); free(t); assert_se(p == original + 9); assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_UNQUOTE, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "waldo")); + ASSERT_STREQ(t, "waldo"); free(t); assert_se(isempty(p)); @@ -583,48 +597,48 @@ TEST(extract_first_word_and_warn) { p = original = "\'fooo"; assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_UNQUOTE|EXTRACT_RELAX, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "fooo")); + ASSERT_STREQ(t, "fooo"); free(t); assert_se(isempty(p)); p = original = " foo\\ba\\x6ar "; assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_CUNESCAPE, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "foo\ba\x6ar")); + ASSERT_STREQ(t, "foo\ba\x6ar"); free(t); assert_se(isempty(p)); p = original = " foo\\ba\\x6ar "; assert_se(extract_first_word_and_warn(&p, &t, NULL, 0, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "foobax6ar")); + ASSERT_STREQ(t, "foobax6ar"); free(t); assert_se(isempty(p)); p = original = " f\\u00f6o \"pi\\U0001F4A9le\" "; assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_CUNESCAPE, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "föo")); + ASSERT_STREQ(t, "föo"); free(t); assert_se(p == original + 13); assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_UNQUOTE|EXTRACT_CUNESCAPE, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "pi\360\237\222\251le")); + ASSERT_STREQ(t, "pi\360\237\222\251le"); free(t); assert_se(isempty(p)); p = original = "fooo\\"; assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_RELAX, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "fooo")); + ASSERT_STREQ(t, "fooo"); free(t); assert_se(isempty(p)); p = original = "fooo\\"; assert_se(extract_first_word_and_warn(&p, &t, NULL, 0, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "fooo\\")); + ASSERT_STREQ(t, "fooo\\"); free(t); assert_se(isempty(p)); p = original = "fooo\\"; assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_CUNESCAPE, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "fooo\\")); + ASSERT_STREQ(t, "fooo\\"); free(t); assert_se(isempty(p)); @@ -634,7 +648,7 @@ TEST(extract_first_word_and_warn) { p = original = "\"foo\\"; assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_UNQUOTE|EXTRACT_RELAX, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "foo")); + ASSERT_STREQ(t, "foo"); free(t); assert_se(isempty(p)); @@ -644,37 +658,37 @@ TEST(extract_first_word_and_warn) { p = original = "\"foo\\"; assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_UNQUOTE|EXTRACT_CUNESCAPE|EXTRACT_RELAX, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "foo")); + ASSERT_STREQ(t, "foo"); free(t); assert_se(isempty(p)); p = original = "fooo\\ bar quux"; assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_RELAX, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "fooo bar")); + ASSERT_STREQ(t, "fooo bar"); free(t); assert_se(p == original + 10); p = original = "fooo\\ bar quux"; assert_se(extract_first_word_and_warn(&p, &t, NULL, 0, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "fooo bar")); + ASSERT_STREQ(t, "fooo bar"); free(t); assert_se(p == original + 10); p = original = "fooo\\ bar quux"; assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_CUNESCAPE, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "fooo\\ bar")); + ASSERT_STREQ(t, "fooo\\ bar"); free(t); assert_se(p == original + 10); p = original = "\\w+@\\K[\\d.]+"; assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_CUNESCAPE, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "\\w+@\\K[\\d.]+")); + ASSERT_STREQ(t, "\\w+@\\K[\\d.]+"); free(t); assert_se(isempty(p)); p = original = "\\w+\\b"; assert_se(extract_first_word_and_warn(&p, &t, NULL, EXTRACT_CUNESCAPE, NULL, "fake", 1, original) > 0); - assert_se(streq(t, "\\w+\b")); + ASSERT_STREQ(t, "\\w+\b"); free(t); assert_se(isempty(p)); } @@ -684,25 +698,25 @@ TEST(extract_many_words) { char *a, *b, *c, *d, *e, *f; p = original = "foobar waldi piep"; - assert_se(extract_many_words(&p, NULL, 0, &a, &b, &c, NULL) == 3); + assert_se(extract_many_words(&p, NULL, 0, &a, &b, &c) == 3); assert_se(isempty(p)); - assert_se(streq_ptr(a, "foobar")); - assert_se(streq_ptr(b, "waldi")); - assert_se(streq_ptr(c, "piep")); + ASSERT_STREQ(a, "foobar"); + ASSERT_STREQ(b, "waldi"); + ASSERT_STREQ(c, "piep"); free(a); free(b); free(c); p = original = "foobar:waldi:piep ba1:ba2"; - assert_se(extract_many_words(&p, ":" WHITESPACE, 0, &a, &b, &c, NULL) == 3); + assert_se(extract_many_words(&p, ":" WHITESPACE, 0, &a, &b, &c) == 3); assert_se(!isempty(p)); - assert_se(streq_ptr(a, "foobar")); - assert_se(streq_ptr(b, "waldi")); - assert_se(streq_ptr(c, "piep")); - assert_se(extract_many_words(&p, ":" WHITESPACE, 0, &d, &e, &f, NULL) == 2); + ASSERT_STREQ(a, "foobar"); + ASSERT_STREQ(b, "waldi"); + ASSERT_STREQ(c, "piep"); + assert_se(extract_many_words(&p, ":" WHITESPACE, 0, &d, &e, &f) == 2); assert_se(isempty(p)); - assert_se(streq_ptr(d, "ba1")); - assert_se(streq_ptr(e, "ba2")); + ASSERT_STREQ(d, "ba1"); + ASSERT_STREQ(e, "ba2"); assert_se(isempty(f)); free(a); free(b); @@ -712,52 +726,62 @@ TEST(extract_many_words) { free(f); p = original = "'foobar' wa\"ld\"i "; - assert_se(extract_many_words(&p, NULL, 0, &a, &b, &c, NULL) == 2); + assert_se(extract_many_words(&p, NULL, 0, &a, &b, &c) == 2); assert_se(isempty(p)); - assert_se(streq_ptr(a, "'foobar'")); - assert_se(streq_ptr(b, "wa\"ld\"i")); - assert_se(streq_ptr(c, NULL)); + ASSERT_STREQ(a, "'foobar'"); + ASSERT_STREQ(b, "wa\"ld\"i"); + ASSERT_STREQ(c, NULL); free(a); free(b); p = original = "'foobar' wa\"ld\"i "; - assert_se(extract_many_words(&p, NULL, EXTRACT_UNQUOTE, &a, &b, &c, NULL) == 2); + assert_se(extract_many_words(&p, NULL, EXTRACT_UNQUOTE, &a, &b, &c) == 2); assert_se(isempty(p)); - assert_se(streq_ptr(a, "foobar")); - assert_se(streq_ptr(b, "waldi")); - assert_se(streq_ptr(c, NULL)); + ASSERT_STREQ(a, "foobar"); + ASSERT_STREQ(b, "waldi"); + ASSERT_STREQ(c, NULL); free(a); free(b); p = original = ""; - assert_se(extract_many_words(&p, NULL, 0, &a, &b, &c, NULL) == 0); + assert_se(extract_many_words(&p, NULL, 0, &a, &b, &c) == 0); assert_se(isempty(p)); - assert_se(streq_ptr(a, NULL)); - assert_se(streq_ptr(b, NULL)); - assert_se(streq_ptr(c, NULL)); + ASSERT_STREQ(a, NULL); + ASSERT_STREQ(b, NULL); + ASSERT_STREQ(c, NULL); p = original = " "; - assert_se(extract_many_words(&p, NULL, 0, &a, &b, &c, NULL) == 0); + assert_se(extract_many_words(&p, NULL, 0, &a, &b, &c) == 0); assert_se(isempty(p)); - assert_se(streq_ptr(a, NULL)); - assert_se(streq_ptr(b, NULL)); - assert_se(streq_ptr(c, NULL)); + ASSERT_STREQ(a, NULL); + ASSERT_STREQ(b, NULL); + ASSERT_STREQ(c, NULL); p = original = "foobar"; - assert_se(extract_many_words(&p, NULL, 0, NULL) == 0); + assert_se(extract_many_words(&p, NULL, 0) == 0); assert_se(p == original); p = original = "foobar waldi"; - assert_se(extract_many_words(&p, NULL, 0, &a, NULL) == 1); + assert_se(extract_many_words(&p, NULL, 0, &a) == 1); assert_se(p == original+7); - assert_se(streq_ptr(a, "foobar")); + ASSERT_STREQ(a, "foobar"); free(a); p = original = " foobar "; - assert_se(extract_many_words(&p, NULL, 0, &a, NULL) == 1); + assert_se(extract_many_words(&p, NULL, 0, &a) == 1); assert_se(isempty(p)); - assert_se(streq_ptr(a, "foobar")); + ASSERT_STREQ(a, "foobar"); free(a); + + p = original = "gęślą:👊🔪💐 가너도루"; + assert_se(extract_many_words(&p, ":" WHITESPACE, 0, &a, &b, &c) == 3); + assert_se(isempty(p)); + ASSERT_STREQ(a, "gęślą"); + ASSERT_STREQ(b, "👊🔪💐"); + ASSERT_STREQ(c, "가너도루"); + free(a); + free(b); + free(c); } DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-fd-util.c b/src/test/test-fd-util.c index 021d4b4..f2b65d4 100644 --- a/src/test/test-fd-util.c +++ b/src/test/test-fd-util.c @@ -138,6 +138,7 @@ TEST(rearrange_stdio) { if (r == 0) { _cleanup_free_ char *path = NULL; + int pipe_read_fd, pair[2]; char buffer[10]; /* Child */ @@ -145,6 +146,10 @@ TEST(rearrange_stdio) { safe_close(STDERR_FILENO); /* Let's close an fd < 2, to make it more interesting */ assert_se(rearrange_stdio(-EBADF, -EBADF, -EBADF) >= 0); + /* Reconfigure logging after rearranging stdout/stderr, so we still log to somewhere if the + * following tests fail, making it slightly less annoying to debug */ + log_set_target(LOG_TARGET_JOURNAL_OR_KMSG); + log_open(); assert_se(fd_get_path(STDIN_FILENO, &path) >= 0); assert_se(path_equal(path, "/dev/null")); @@ -162,21 +167,20 @@ TEST(rearrange_stdio) { safe_close(STDOUT_FILENO); safe_close(STDERR_FILENO); - { - int pair[2]; - assert_se(pipe(pair) >= 0); - assert_se(pair[0] == 0); - assert_se(pair[1] == 1); - assert_se(fd_move_above_stdio(0) == 3); - } + assert_se(pipe(pair) >= 0); + assert_se(pair[0] == 0); + assert_se(pair[1] == 1); + pipe_read_fd = fd_move_above_stdio(0); + assert_se(pipe_read_fd >= 3); + assert_se(open("/dev/full", O_WRONLY|O_CLOEXEC) == 0); - assert_se(acquire_data_fd("foobar", 6, 0) == 2); + assert_se(acquire_data_fd("foobar") == 2); assert_se(rearrange_stdio(2, 0, 1) >= 0); assert_se(write(1, "x", 1) < 0 && errno == ENOSPC); assert_se(write(2, "z", 1) == 1); - assert_se(read(3, buffer, sizeof(buffer)) == 1); + assert_se(read(pipe_read_fd, buffer, sizeof(buffer)) == 1); assert_se(buffer[0] == 'z'); assert_se(read(0, buffer, sizeof(buffer)) == 6); assert_se(memcmp(buffer, "foobar", 6) == 0); @@ -184,7 +188,7 @@ TEST(rearrange_stdio) { assert_se(rearrange_stdio(-EBADF, 1, 2) >= 0); assert_se(write(1, "a", 1) < 0 && errno == ENOSPC); assert_se(write(2, "y", 1) == 1); - assert_se(read(3, buffer, sizeof(buffer)) == 1); + assert_se(read(pipe_read_fd, buffer, sizeof(buffer)) == 1); assert_se(buffer[0] == 'y'); assert_se(fd_get_path(0, &path) >= 0); @@ -393,11 +397,11 @@ TEST(close_all_fds) { } TEST(format_proc_fd_path) { - assert_se(streq_ptr(FORMAT_PROC_FD_PATH(0), "/proc/self/fd/0")); - assert_se(streq_ptr(FORMAT_PROC_FD_PATH(1), "/proc/self/fd/1")); - assert_se(streq_ptr(FORMAT_PROC_FD_PATH(2), "/proc/self/fd/2")); - assert_se(streq_ptr(FORMAT_PROC_FD_PATH(3), "/proc/self/fd/3")); - assert_se(streq_ptr(FORMAT_PROC_FD_PATH(2147483647), "/proc/self/fd/2147483647")); + ASSERT_STREQ(FORMAT_PROC_FD_PATH(0), "/proc/self/fd/0"); + ASSERT_STREQ(FORMAT_PROC_FD_PATH(1), "/proc/self/fd/1"); + ASSERT_STREQ(FORMAT_PROC_FD_PATH(2), "/proc/self/fd/2"); + ASSERT_STREQ(FORMAT_PROC_FD_PATH(3), "/proc/self/fd/3"); + ASSERT_STREQ(FORMAT_PROC_FD_PATH(2147483647), "/proc/self/fd/2147483647"); } TEST(fd_reopen) { @@ -409,7 +413,7 @@ TEST(fd_reopen) { fd1 = open("/proc", O_DIRECTORY|O_PATH|O_CLOEXEC); assert_se(fd1 >= 0); - assert_se(fstat(fd1, &st1) >= 0); + ASSERT_OK_ERRNO(fstat(fd1, &st1)); assert_se(S_ISDIR(st1.st_mode)); fl = fcntl(fd1, F_GETFL); @@ -424,7 +428,7 @@ TEST(fd_reopen) { fd2 = fd_reopen(fd1, O_RDONLY|O_DIRECTORY|O_CLOEXEC); /* drop the O_PATH */ assert_se(fd2 >= 0); - assert_se(fstat(fd2, &st2) >= 0); + ASSERT_OK_ERRNO(fstat(fd2, &st2)); assert_se(S_ISDIR(st2.st_mode)); assert_se(stat_inode_same(&st1, &st2)); @@ -438,7 +442,7 @@ TEST(fd_reopen) { fd1 = fd_reopen(fd2, O_DIRECTORY|O_PATH|O_CLOEXEC); /* reacquire the O_PATH */ assert_se(fd1 >= 0); - assert_se(fstat(fd1, &st1) >= 0); + ASSERT_OK_ERRNO(fstat(fd1, &st1)); assert_se(S_ISDIR(st1.st_mode)); assert_se(stat_inode_same(&st1, &st2)); @@ -453,7 +457,7 @@ TEST(fd_reopen) { fd1 = open("/proc/version", O_PATH|O_CLOEXEC); assert_se(fd1 >= 0); - assert_se(fstat(fd1, &st1) >= 0); + ASSERT_OK_ERRNO(fstat(fd1, &st1)); assert_se(S_ISREG(st1.st_mode)); fl = fcntl(fd1, F_GETFL); @@ -465,7 +469,7 @@ TEST(fd_reopen) { fd2 = fd_reopen(fd1, O_RDONLY|O_CLOEXEC); /* drop the O_PATH */ assert_se(fd2 >= 0); - assert_se(fstat(fd2, &st2) >= 0); + ASSERT_OK_ERRNO(fstat(fd2, &st2)); assert_se(S_ISREG(st2.st_mode)); assert_se(stat_inode_same(&st1, &st2)); @@ -480,7 +484,7 @@ TEST(fd_reopen) { fd1 = fd_reopen(fd2, O_PATH|O_CLOEXEC); /* reacquire the O_PATH */ assert_se(fd1 >= 0); - assert_se(fstat(fd1, &st1) >= 0); + ASSERT_OK_ERRNO(fstat(fd1, &st1)); assert_se(S_ISREG(st1.st_mode)); assert_se(stat_inode_same(&st1, &st2)); @@ -497,12 +501,12 @@ TEST(fd_reopen) { /* Validate what happens if we reopen a symlink */ fd1 = open("/proc/self", O_PATH|O_CLOEXEC|O_NOFOLLOW); assert_se(fd1 >= 0); - assert_se(fstat(fd1, &st1) >= 0); + ASSERT_OK_ERRNO(fstat(fd1, &st1)); assert_se(S_ISLNK(st1.st_mode)); fd2 = fd_reopen(fd1, O_PATH|O_CLOEXEC); assert_se(fd2 >= 0); - assert_se(fstat(fd2, &st2) >= 0); + ASSERT_OK_ERRNO(fstat(fd2, &st2)); assert_se(S_ISLNK(st2.st_mode)); assert_se(stat_inode_same(&st1, &st2)); fd2 = safe_close(fd2); @@ -646,6 +650,24 @@ TEST(dir_fd_is_root) { assert_se(dir_fd_is_root_or_cwd(fd) == 0); } +TEST(fds_are_same_mount) { + _cleanup_close_ int fd1 = -EBADF, fd2 = -EBADF, fd3 = -EBADF, fd4 = -EBADF; + + fd1 = open("/sys", O_CLOEXEC|O_PATH|O_DIRECTORY|O_NOFOLLOW); + fd2 = open("/proc", O_CLOEXEC|O_PATH|O_DIRECTORY|O_NOFOLLOW); + fd3 = open("/proc", O_CLOEXEC|O_PATH|O_DIRECTORY|O_NOFOLLOW); + fd4 = open("/", O_CLOEXEC|O_PATH|O_DIRECTORY|O_NOFOLLOW); + + if (fd1 < 0 || fd2 < 0 || fd3 < 0 || fd4 < 0) + return (void) log_tests_skipped_errno(errno, "Failed to open /sys or /proc or /"); + + if (fds_are_same_mount(fd1, fd4) > 0 && fds_are_same_mount(fd2, fd4) > 0) + return (void) log_tests_skipped("Cannot test fds_are_same_mount() as /sys and /proc are not mounted"); + + assert_se(fds_are_same_mount(fd1, fd2) == 0); + assert_se(fds_are_same_mount(fd2, fd3) > 0); +} + TEST(fd_get_path) { _cleanup_(rm_rf_physical_and_freep) char *t = NULL; _cleanup_close_ int tfd = -EBADF, fd = -EBADF; @@ -654,7 +676,7 @@ TEST(fd_get_path) { tfd = mkdtemp_open(NULL, O_PATH, &t); assert_se(tfd >= 0); assert_se(fd_get_path(tfd, &p) >= 0); - assert_se(streq(p, t)); + ASSERT_STREQ(p, t); p = mfree(p); @@ -662,7 +684,7 @@ TEST(fd_get_path) { assert_se(chdir(t) >= 0); assert_se(fd_get_path(AT_FDCWD, &p) >= 0); - assert_se(streq(p, t)); + ASSERT_STREQ(p, t); p = mfree(p); @@ -675,7 +697,7 @@ TEST(fd_get_path) { fd = openat(tfd, "regular", O_CLOEXEC|O_PATH); assert_se(fd >= 0); assert_se(fd_get_path(fd, &p) >= 0); - assert_se(streq(p, q)); + ASSERT_STREQ(p, q); p = mfree(p); fd = safe_close(fd); @@ -683,7 +705,7 @@ TEST(fd_get_path) { fd = openat(AT_FDCWD, "regular", O_CLOEXEC|O_PATH); assert_se(fd >= 0); assert_se(fd_get_path(fd, &p) >= 0); - assert_se(streq(p, q)); + ASSERT_STREQ(p, q); p = mfree(p); fd = safe_close(fd); @@ -692,7 +714,7 @@ TEST(fd_get_path) { assert_se(fd >= 0); assert_se(fd_verify_regular(fd) >= 0); assert_se(fd_get_path(fd, &p) >= 0); - assert_se(streq(p, q)); + ASSERT_STREQ(p, q); p = mfree(p); fd = safe_close(fd); @@ -701,7 +723,7 @@ TEST(fd_get_path) { assert_se(fd >= 0); assert_se(fd_verify_regular(fd) >= 0); assert_se(fd_get_path(fd, &p) >= 0); - assert_se(streq(p, q)); + ASSERT_STREQ(p, q); p = mfree(p); fd = safe_close(fd); @@ -710,7 +732,7 @@ TEST(fd_get_path) { assert_se(fd >= 0); assert_se(fd_verify_regular(fd) >= 0); assert_se(fd_get_path(fd, &p) >= 0); - assert_se(streq(p, q)); + ASSERT_STREQ(p, q); p = mfree(p); fd = safe_close(fd); @@ -719,7 +741,7 @@ TEST(fd_get_path) { assert_se(fd >= 0); assert_se(fd_verify_regular(fd) >= 0); assert_se(fd_get_path(fd, &p) >= 0); - assert_se(streq(p, q)); + ASSERT_STREQ(p, q); p = mfree(p); q = mfree(q); @@ -730,7 +752,7 @@ TEST(fd_get_path) { assert_se(fd >= 0); assert_se(fd_verify_regular(fd) == -ELOOP); assert_se(fd_get_path(fd, &p) >= 0); - assert_se(streq(p, q)); + ASSERT_STREQ(p, q); p = mfree(p); fd = safe_close(fd); @@ -739,7 +761,7 @@ TEST(fd_get_path) { assert_se(fd >= 0); assert_se(fd_verify_regular(fd) == -ELOOP); assert_se(fd_get_path(fd, &p) >= 0); - assert_se(streq(p, q)); + ASSERT_STREQ(p, q); p = mfree(p); fd = safe_close(fd); @@ -748,7 +770,7 @@ TEST(fd_get_path) { assert_se(fd >= 0); assert_se(fd_verify_regular(fd) == -ELOOP); assert_se(fd_get_path(fd, &p) >= 0); - assert_se(streq(p, q)); + ASSERT_STREQ(p, q); p = mfree(p); fd = safe_close(fd); @@ -757,7 +779,7 @@ TEST(fd_get_path) { assert_se(fd >= 0); assert_se(fd_verify_regular(fd) == -ELOOP); assert_se(fd_get_path(fd, &p) >= 0); - assert_se(streq(p, q)); + ASSERT_STREQ(p, q); assert_se(chdir(saved_cwd) >= 0); } diff --git a/src/test/test-fdset.c b/src/test/test-fdset.c index 8f00e59..cfbd8e2 100644 --- a/src/test/test-fdset.c +++ b/src/test/test-fdset.c @@ -116,9 +116,18 @@ TEST(fdset_close_others) { copyfd = fdset_put_dup(fdset, fd); assert_se(copyfd >= 0); + /* fdset_close_others() will close any logging file descriptors as well, so close them beforehand + * and reopen them again afterwards. */ + log_close(); assert_se(fdset_close_others(fdset) >= 0); + flags = fcntl(fd, F_GETFD); assert_se(flags < 0); + + /* Open log again after checking that fd is invalid, since reopening the log might make fd a valid + * file descriptor again. */ + (void) log_open(); + flags = fcntl(copyfd, F_GETFD); assert_se(flags >= 0); } diff --git a/src/test/test-fileio.c b/src/test/test-fileio.c index ad98a92..474eaca 100644 --- a/src/test/test-fileio.c +++ b/src/test/test-fileio.c @@ -71,27 +71,27 @@ TEST(parse_env_file) { STRV_FOREACH(i, a) log_info("Got: <%s>", *i); - assert_se(streq_ptr(a[0], "one=BAR")); - assert_se(streq_ptr(a[1], "two=bar")); - assert_se(streq_ptr(a[2], "three=333\nxxxx")); - assert_se(streq_ptr(a[3], "four=44\\\"44")); - assert_se(streq_ptr(a[4], "five=55\"55FIVEcinco")); - assert_se(streq_ptr(a[5], "six=seis sechs sis")); - assert_se(streq_ptr(a[6], "seven=sevenval#nocomment")); - assert_se(streq_ptr(a[7], "eight=eightval #nocomment")); - assert_se(streq_ptr(a[8], "export nine=nineval")); - assert_se(streq_ptr(a[9], "ten=")); - assert_se(streq_ptr(a[10], "eleven=value")); - assert_se(streq_ptr(a[11], "twelve=\\value")); - assert_se(streq_ptr(a[12], "thirteen=\\value")); - assert_se(a[13] == NULL); + ASSERT_STREQ(a[0], "one=BAR"); + ASSERT_STREQ(a[1], "two=bar"); + ASSERT_STREQ(a[2], "three=333\nxxxx"); + ASSERT_STREQ(a[3], "four=44\\\"44"); + ASSERT_STREQ(a[4], "five=55\"55FIVEcinco"); + ASSERT_STREQ(a[5], "six=seis sechs sis"); + ASSERT_STREQ(a[6], "seven=sevenval#nocomment"); + ASSERT_STREQ(a[7], "eight=eightval #nocomment"); + ASSERT_STREQ(a[8], "export nine=nineval"); + ASSERT_STREQ(a[9], "ten="); + ASSERT_STREQ(a[10], "eleven=value"); + ASSERT_STREQ(a[11], "twelve=\\value"); + ASSERT_STREQ(a[12], "thirteen=\\value"); + ASSERT_NULL(a[13]); strv_env_clean(a); k = 0; STRV_FOREACH(i, b) { log_info("Got2: <%s>", *i); - assert_se(streq(*i, a[k++])); + ASSERT_STREQ(*i, a[k++]); } r = parse_env_file( @@ -125,19 +125,19 @@ TEST(parse_env_file) { log_info("twelve=[%s]", strna(twelve)); log_info("thirteen=[%s]", strna(thirteen)); - assert_se(streq(one, "BAR")); - assert_se(streq(two, "bar")); - assert_se(streq(three, "333\nxxxx")); - assert_se(streq(four, "44\\\"44")); - assert_se(streq(five, "55\"55FIVEcinco")); - assert_se(streq(six, "seis sechs sis")); - assert_se(streq(seven, "sevenval#nocomment")); - assert_se(streq(eight, "eightval #nocomment")); - assert_se(streq(nine, "nineval")); - assert_se(ten == NULL); - assert_se(streq(eleven, "value")); - assert_se(streq(twelve, "\\value")); - assert_se(streq(thirteen, "\\value")); + ASSERT_STREQ(one, "BAR"); + ASSERT_STREQ(two, "bar"); + ASSERT_STREQ(three, "333\nxxxx"); + ASSERT_STREQ(four, "44\\\"44"); + ASSERT_STREQ(five, "55\"55FIVEcinco"); + ASSERT_STREQ(six, "seis sechs sis"); + ASSERT_STREQ(seven, "sevenval#nocomment"); + ASSERT_STREQ(eight, "eightval #nocomment"); + ASSERT_STREQ(nine, "nineval"); + ASSERT_NULL(ten); + ASSERT_STREQ(eleven, "value"); + ASSERT_STREQ(twelve, "\\value"); + ASSERT_STREQ(thirteen, "\\value"); { /* prepare a temporary file to write the environment to */ @@ -161,7 +161,7 @@ static void test_one_shell_var(const char *file, const char *variable, const cha assert_se(f = popen(cmd, "re")); assert_se(read_full_stream(f, &from_shell, &sz) >= 0); assert_se(sz == strlen(value)); - assert_se(streq(from_shell, value)); + ASSERT_STREQ(from_shell, value); } TEST(parse_multiline_env_file) { @@ -198,10 +198,10 @@ TEST(parse_multiline_env_file) { STRV_FOREACH(i, a) log_info("Got: <%s>", *i); - assert_se(streq_ptr(a[0], "one=BAR VAR\tGAR")); - assert_se(streq_ptr(a[1], "two=bar var\tgar")); - assert_se(streq_ptr(a[2], "tri=bar var \tgar ")); - assert_se(a[3] == NULL); + ASSERT_STREQ(a[0], "one=BAR VAR\tGAR"); + ASSERT_STREQ(a[1], "two=bar var\tgar"); + ASSERT_STREQ(a[2], "tri=bar var \tgar "); + ASSERT_NULL(a[3]); { _cleanup_close_ int fd = mkostemp_safe(p); @@ -246,17 +246,17 @@ TEST(merge_env_file) { STRV_FOREACH(i, a) log_info("Got: <%s>", *i); - assert_se(streq(a[0], "one=2")); - assert_se(streq(a[1], "twelve=12")); - assert_se(streq(a[2], "twentyone=21")); - assert_se(streq(a[3], "twentytwo=22")); - assert_se(streq(a[4], "xxx=0x222")); - assert_se(streq(a[5], "xxx_minus_three= - 3")); - assert_se(streq(a[6], "yyy=2")); - assert_se(streq(a[7], "zzz=replacement")); - assert_se(streq(a[8], "zzzz=")); - assert_se(streq(a[9], "zzzzz=")); - assert_se(a[10] == NULL); + ASSERT_STREQ(a[0], "one=2"); + ASSERT_STREQ(a[1], "twelve=12"); + ASSERT_STREQ(a[2], "twentyone=21"); + ASSERT_STREQ(a[3], "twentytwo=22"); + ASSERT_STREQ(a[4], "xxx=0x222"); + ASSERT_STREQ(a[5], "xxx_minus_three= - 3"); + ASSERT_STREQ(a[6], "yyy=2"); + ASSERT_STREQ(a[7], "zzz=replacement"); + ASSERT_STREQ(a[8], "zzzz="); + ASSERT_STREQ(a[9], "zzzzz="); + ASSERT_NULL(a[10]); r = merge_env_file(&a, NULL, t); assert_se(r >= 0); @@ -265,17 +265,17 @@ TEST(merge_env_file) { STRV_FOREACH(i, a) log_info("Got2: <%s>", *i); - assert_se(streq(a[0], "one=2")); - assert_se(streq(a[1], "twelve=12")); - assert_se(streq(a[2], "twentyone=21")); - assert_se(streq(a[3], "twentytwo=22")); - assert_se(streq(a[4], "xxx=0x222")); - assert_se(streq(a[5], "xxx_minus_three=0x222 - 3")); - assert_se(streq(a[6], "yyy=2")); - assert_se(streq(a[7], "zzz=replacement")); - assert_se(streq(a[8], "zzzz=")); - assert_se(streq(a[9], "zzzzz=")); - assert_se(a[10] == NULL); + ASSERT_STREQ(a[0], "one=2"); + ASSERT_STREQ(a[1], "twelve=12"); + ASSERT_STREQ(a[2], "twentyone=21"); + ASSERT_STREQ(a[3], "twentytwo=22"); + ASSERT_STREQ(a[4], "xxx=0x222"); + ASSERT_STREQ(a[5], "xxx_minus_three=0x222 - 3"); + ASSERT_STREQ(a[6], "yyy=2"); + ASSERT_STREQ(a[7], "zzz=replacement"); + ASSERT_STREQ(a[8], "zzzz="); + ASSERT_STREQ(a[9], "zzzzz="); + ASSERT_NULL(a[10]); } TEST(merge_env_file_invalid) { @@ -323,7 +323,7 @@ TEST(executable_is_script) { r = executable_is_script(t, &command); assert_se(r > 0); - assert_se(streq(command, "/bin/script")); + ASSERT_STREQ(command, "/bin/script"); free(command); r = executable_is_script("/bin/sh", &command); @@ -398,27 +398,27 @@ TEST(read_one_line_file) { assert_se(f); assert_se(read_one_line_file(fn, &buf) == 0); - assert_se(streq_ptr(buf, "")); + ASSERT_STREQ(buf, ""); assert_se(read_one_line_file(fn, &buf2) == 0); - assert_se(streq_ptr(buf2, "")); + ASSERT_STREQ(buf2, ""); assert_se(write_string_stream(f, "x", WRITE_STRING_FILE_AVOID_NEWLINE) >= 0); fflush(f); assert_se(read_one_line_file(fn, &buf3) == 1); - assert_se(streq_ptr(buf3, "x")); + ASSERT_STREQ(buf3, "x"); assert_se(write_string_stream(f, "\n", WRITE_STRING_FILE_AVOID_NEWLINE) >= 0); fflush(f); assert_se(read_one_line_file(fn, &buf4) == 2); - assert_se(streq_ptr(buf4, "x")); + ASSERT_STREQ(buf4, "x"); assert_se(write_string_stream(f, "\n", WRITE_STRING_FILE_AVOID_NEWLINE) >= 0); fflush(f); assert_se(read_one_line_file(fn, &buf5) == 2); - assert_se(streq_ptr(buf5, "x")); + ASSERT_STREQ(buf5, "x"); } TEST(write_string_stream) { @@ -442,7 +442,7 @@ TEST(write_string_stream) { rewind(f); assert_se(fgets(buf, sizeof(buf), f)); - assert_se(streq(buf, "boohoo\n")); + ASSERT_STREQ(buf, "boohoo\n"); f = safe_fclose(f); f = fopen(fn, "w+"); @@ -453,7 +453,7 @@ TEST(write_string_stream) { assert_se(fgets(buf, sizeof(buf), f)); printf(">%s<", buf); - assert_se(streq(buf, "boohoo")); + ASSERT_STREQ(buf, "boohoo"); } TEST(write_string_file) { @@ -467,7 +467,7 @@ TEST(write_string_file) { assert_se(write_string_file(fn, "boohoo", WRITE_STRING_FILE_CREATE) == 0); assert_se(read(fd, buf, sizeof(buf)) == 7); - assert_se(streq(buf, "boohoo\n")); + ASSERT_STREQ(buf, "boohoo\n"); } TEST(write_string_file_no_create) { @@ -482,7 +482,7 @@ TEST(write_string_file_no_create) { assert_se(write_string_file(fn, "boohoo", 0) == 0); assert_se(read(fd, buf, sizeof buf) == (ssize_t) strlen("boohoo\n")); - assert_se(streq(buf, "boohoo\n")); + ASSERT_STREQ(buf, "boohoo\n"); } TEST(write_string_file_verify) { @@ -578,14 +578,14 @@ TEST(search_and_fopen) { r = search_and_fopen(basename(name), "re", NULL, (const char**) dirs, &f, &p); assert_se(r >= 0); assert_se(e = path_startswith(p, "/tmp/")); - assert_se(streq(basename(name), e)); + ASSERT_STREQ(basename(name), e); f = safe_fclose(f); p = mfree(p); r = search_and_fopen(basename(name), NULL, NULL, (const char**) dirs, NULL, &p); assert_se(r >= 0); assert_se(e = path_startswith(p, "/tmp/")); - assert_se(streq(basename(name), e)); + ASSERT_STREQ(basename(name), e); p = mfree(p); r = search_and_fopen(name, "re", NULL, (const char**) dirs, &f, &p); @@ -602,14 +602,14 @@ TEST(search_and_fopen) { r = search_and_fopen(basename(name), "re", "/", (const char**) dirs, &f, &p); assert_se(r >= 0); assert_se(e = path_startswith(p, "/tmp/")); - assert_se(streq(basename(name), e)); + ASSERT_STREQ(basename(name), e); f = safe_fclose(f); p = mfree(p); r = search_and_fopen(basename(name), NULL, "/", (const char**) dirs, NULL, &p); assert_se(r >= 0); assert_se(e = path_startswith(p, "/tmp/")); - assert_se(streq(basename(name), e)); + ASSERT_STREQ(basename(name), e); p = mfree(p); r = search_and_fopen("/a/file/which/does/not/exist/i/guess", "re", NULL, (const char**) dirs, &f, &p); @@ -649,7 +649,7 @@ TEST(search_and_fopen_nulstr) { r = search_and_fopen_nulstr(basename(name), "re", NULL, dirs, &f, &p); assert_se(r >= 0); assert_se(e = path_startswith(p, "/tmp/")); - assert_se(streq(basename(name), e)); + ASSERT_STREQ(basename(name), e); f = safe_fclose(f); p = mfree(p); @@ -693,18 +693,18 @@ TEST(writing_tmpfile) { r = read_full_file(name, &contents, &size); assert_se(r == 0); printf("contents: %s", contents); - assert_se(streq(contents, "abc\n" ALPHANUMERICAL "\n")); + ASSERT_STREQ(contents, "abc\n" ALPHANUMERICAL "\n"); } TEST(tempfn) { char *ret = NULL, *p; assert_se(tempfn_xxxxxx("/foo/bar/waldo", NULL, &ret) >= 0); - assert_se(streq_ptr(ret, "/foo/bar/.#waldoXXXXXX")); + ASSERT_STREQ(ret, "/foo/bar/.#waldoXXXXXX"); free(ret); assert_se(tempfn_xxxxxx("/foo/bar/waldo", "[miau]", &ret) >= 0); - assert_se(streq_ptr(ret, "/foo/bar/.#[miau]waldoXXXXXX")); + ASSERT_STREQ(ret, "/foo/bar/.#[miau]waldoXXXXXX"); free(ret); assert_se(tempfn_random("/foo/bar/waldo", NULL, &ret) >= 0); @@ -900,7 +900,7 @@ TEST(read_line4) { r = read_line(f, SIZE_MAX, &s); assert_se((size_t) r == eof_endings[i].length); - assert_se(streq_ptr(s, "foo")); + ASSERT_STREQ(s, "foo"); assert_se(read_line(f, SIZE_MAX, NULL) == 0); /* Ensure we hit EOF */ } @@ -985,7 +985,7 @@ TEST(read_full_file_socket) { assert_se(peer.un.sun_family == AF_UNIX); assert_se(peerlen > offsetof(struct sockaddr_un, sun_path)); assert_se(peer.un.sun_path[0] == 0); - assert_se(streq(peer.un.sun_path + 1, clientname + 1)); + ASSERT_STREQ(peer.un.sun_path + 1, clientname + 1); #define TEST_STR "This is a test\nreally." @@ -996,7 +996,7 @@ TEST(read_full_file_socket) { assert_se(read_full_file_full(AT_FDCWD, jj, UINT64_MAX, SIZE_MAX, 0, NULL, &data, &size) == -ENXIO); assert_se(read_full_file_full(AT_FDCWD, jj, UINT64_MAX, SIZE_MAX, READ_FULL_FILE_CONNECT_SOCKET, clientname, &data, &size) >= 0); assert_se(size == strlen(TEST_STR)); - assert_se(streq(data, TEST_STR)); + ASSERT_STREQ(data, TEST_STR); assert_se(wait_for_terminate_and_check("(server)", pid, WAIT_LOG) >= 0); #undef TEST_STR @@ -1125,7 +1125,7 @@ TEST(fdopen_independent) { assert_se(fdopen_independent(fd, "re", &f) >= 0); zero(buf); assert_se(fread(buf, 1, sizeof(buf), f) == strlen(TEST_TEXT)); - assert_se(streq(buf, TEST_TEXT)); + ASSERT_STREQ(buf, TEST_TEXT); assert_se((fcntl(fileno(f), F_GETFL) & O_ACCMODE) == O_RDONLY); assert_se(FLAGS_SET(fcntl(fileno(f), F_GETFD), FD_CLOEXEC)); f = safe_fclose(f); @@ -1133,7 +1133,7 @@ TEST(fdopen_independent) { assert_se(fdopen_independent(fd, "r", &f) >= 0); zero(buf); assert_se(fread(buf, 1, sizeof(buf), f) == strlen(TEST_TEXT)); - assert_se(streq(buf, TEST_TEXT)); + ASSERT_STREQ(buf, TEST_TEXT); assert_se((fcntl(fileno(f), F_GETFL) & O_ACCMODE) == O_RDONLY); assert_se(!FLAGS_SET(fcntl(fileno(f), F_GETFD), FD_CLOEXEC)); f = safe_fclose(f); @@ -1141,7 +1141,7 @@ TEST(fdopen_independent) { assert_se(fdopen_independent(fd, "r+e", &f) >= 0); zero(buf); assert_se(fread(buf, 1, sizeof(buf), f) == strlen(TEST_TEXT)); - assert_se(streq(buf, TEST_TEXT)); + ASSERT_STREQ(buf, TEST_TEXT); assert_se((fcntl(fileno(f), F_GETFL) & O_ACCMODE) == O_RDWR); assert_se(FLAGS_SET(fcntl(fileno(f), F_GETFD), FD_CLOEXEC)); f = safe_fclose(f); diff --git a/src/test/test-format-table.c b/src/test/test-format-table.c index 7d544b1..3dbfda7 100644 --- a/src/test/test-format-table.c +++ b/src/test/test-format-table.c @@ -551,7 +551,7 @@ TEST(vertical) { assert_se(streq(formatted, " pfft aa: foo\n" - " uuu o: 1.0K\n" + " uuu o: 1K\n" "lllllllllllo: jjjjjjjjjjjjjjjjj\n")); _cleanup_(json_variant_unrefp) JsonVariant *a = NULL, *b = NULL; @@ -580,7 +580,7 @@ TEST(path_basename) { assert_se(table_format(t, &formatted) >= 0); - assert_se(streq(formatted, "bar\nbar\nbaz\n")); + ASSERT_STREQ(formatted, "bar\nbar\nbaz\n"); } TEST(dup_cell) { @@ -626,6 +626,41 @@ TEST(dup_cell) { "aaa 0 65535 4294967295 100% ../ hello hello hello\n")); } +TEST(table_bps) { + _cleanup_(table_unrefp) Table *table = NULL; + _cleanup_free_ char *formatted = NULL; + + assert_se(table = table_new("uint64", "size", "bps")); + uint64_t v; + FOREACH_ARGUMENT(v, + 2500, + 10000000, + 20000000, + 25000000, + 1000000000, + 2000000000, + 2500000000) + assert_se(table_add_many(table, + TABLE_UINT64, v, + TABLE_SIZE, v, + TABLE_BPS, v) >= 0); + + table_set_width(table, 50); + assert_se(table_format(table, &formatted) >= 0); + + printf("%s", formatted); + assert_se(streq(formatted, + "UINT64 SIZE BPS\n" + "2500 2.4K 2.5Kbps\n" + "10000000 9.5M 10Mbps\n" + "20000000 19M 20Mbps\n" + "25000000 23.8M 25Mbps\n" + "1000000000 953.6M 1Gbps\n" + "2000000000 1.8G 2Gbps\n" + "2500000000 2.3G 2.5Gbps\n" + )); +} + static int intro(void) { assert_se(setenv("SYSTEMD_COLORS", "0", 1) >= 0); assert_se(setenv("COLUMNS", "40", 1) >= 0); diff --git a/src/test/test-format-util.c b/src/test/test-format-util.c index 3063509..8afba4e 100644 --- a/src/test/test-format-util.c +++ b/src/test/test-format-util.c @@ -34,26 +34,26 @@ static void test_format_bytes_one(uint64_t val, bool trailing_B, const char *iec const char *si_with_p, const char *si_without_p) { char buf[FORMAT_BYTES_MAX]; - assert_se(streq_ptr(format_bytes_full(buf, sizeof buf, val, FORMAT_BYTES_USE_IEC | FORMAT_BYTES_BELOW_POINT | (trailing_B ? FORMAT_BYTES_TRAILING_B : 0)), iec_with_p)); - assert_se(streq_ptr(format_bytes_full(buf, sizeof buf, val, FORMAT_BYTES_USE_IEC | (trailing_B ? FORMAT_BYTES_TRAILING_B : 0)), iec_without_p)); - assert_se(streq_ptr(format_bytes_full(buf, sizeof buf, val, FORMAT_BYTES_BELOW_POINT | (trailing_B ? FORMAT_BYTES_TRAILING_B : 0)), si_with_p)); - assert_se(streq_ptr(format_bytes_full(buf, sizeof buf, val, trailing_B ? FORMAT_BYTES_TRAILING_B : 0), si_without_p)); + ASSERT_STREQ(format_bytes_full(buf, sizeof buf, val, FORMAT_BYTES_USE_IEC | FORMAT_BYTES_BELOW_POINT | (trailing_B ? FORMAT_BYTES_TRAILING_B : 0)), iec_with_p); + ASSERT_STREQ(format_bytes_full(buf, sizeof buf, val, FORMAT_BYTES_USE_IEC | (trailing_B ? FORMAT_BYTES_TRAILING_B : 0)), iec_without_p); + ASSERT_STREQ(format_bytes_full(buf, sizeof buf, val, FORMAT_BYTES_BELOW_POINT | (trailing_B ? FORMAT_BYTES_TRAILING_B : 0)), si_with_p); + ASSERT_STREQ(format_bytes_full(buf, sizeof buf, val, trailing_B ? FORMAT_BYTES_TRAILING_B : 0), si_without_p); } TEST(format_bytes) { test_format_bytes_one(900, true, "900B", "900B", "900B", "900B"); test_format_bytes_one(900, false, "900", "900", "900", "900"); - test_format_bytes_one(1023, true, "1023B", "1023B", "1.0K", "1K"); - test_format_bytes_one(1023, false, "1023", "1023", "1.0K", "1K"); - test_format_bytes_one(1024, true, "1.0K", "1K", "1.0K", "1K"); - test_format_bytes_one(1024, false, "1.0K", "1K", "1.0K", "1K"); - test_format_bytes_one(1100, true, "1.0K", "1K", "1.1K", "1K"); + test_format_bytes_one(1023, true, "1023B", "1023B", "1K", "1K"); + test_format_bytes_one(1023, false, "1023", "1023", "1K", "1K"); + test_format_bytes_one(1024, true, "1K", "1K", "1K", "1K"); + test_format_bytes_one(1024, false, "1K", "1K", "1K", "1K"); + test_format_bytes_one(1100, true, "1K", "1K", "1.1K", "1K"); test_format_bytes_one(1500, true, "1.4K", "1K", "1.5K", "1K"); - test_format_bytes_one(UINT64_C(3)*1024*1024, true, "3.0M", "3M", "3.1M", "3M"); - test_format_bytes_one(UINT64_C(3)*1024*1024*1024, true, "3.0G", "3G", "3.2G", "3G"); - test_format_bytes_one(UINT64_C(3)*1024*1024*1024*1024, true, "3.0T", "3T", "3.2T", "3T"); - test_format_bytes_one(UINT64_C(3)*1024*1024*1024*1024*1024, true, "3.0P", "3P", "3.3P", "3P"); - test_format_bytes_one(UINT64_C(3)*1024*1024*1024*1024*1024*1024, true, "3.0E", "3E", "3.4E", "3E"); + test_format_bytes_one(UINT64_C(3)*1024*1024, true, "3M", "3M", "3.1M", "3M"); + test_format_bytes_one(UINT64_C(3)*1024*1024*1024, true, "3G", "3G", "3.2G", "3G"); + test_format_bytes_one(UINT64_C(3)*1024*1024*1024*1024, true, "3T", "3T", "3.2T", "3T"); + test_format_bytes_one(UINT64_C(3)*1024*1024*1024*1024*1024, true, "3P", "3P", "3.3P", "3P"); + test_format_bytes_one(UINT64_C(3)*1024*1024*1024*1024*1024*1024, true, "3E", "3E", "3.4E", "3E"); test_format_bytes_one(UINT64_MAX, true, NULL, NULL, NULL, NULL); test_format_bytes_one(UINT64_MAX, false, NULL, NULL, NULL, NULL); } diff --git a/src/test/test-fs-util.c b/src/test/test-fs-util.c index b32feff..d44e043 100644 --- a/src/test/test-fs-util.c +++ b/src/test/test-fs-util.c @@ -45,7 +45,7 @@ TEST(readlink_and_make_absolute) { log_tests_skipped_errno(errno, "symlink() not possible"); } else { assert_se(readlink_and_make_absolute(name_alias, &r1) >= 0); - assert_se(streq(r1, name)); + ASSERT_STREQ(r1, name); assert_se(unlink(name_alias) >= 0); assert_se(safe_getcwd(&pwd) >= 0); @@ -53,7 +53,7 @@ TEST(readlink_and_make_absolute) { assert_se(chdir(tempdir) >= 0); assert_se(symlink(name2, name_alias) >= 0); assert_se(readlink_and_make_absolute(name_alias, &r2) >= 0); - assert_se(streq(r2, name)); + ASSERT_STREQ(r2, name); assert_se(unlink(name_alias) >= 0); assert_se(chdir(pwd) >= 0); @@ -97,33 +97,33 @@ TEST(var_tmp) { assert_se(unsetenv("TMP") >= 0); assert_se(var_tmp_dir(&tmp_dir) >= 0); - assert_se(streq(tmp_dir, "/var/tmp")); + ASSERT_STREQ(tmp_dir, "/var/tmp"); assert_se(setenv("TMPDIR", "/tmp", true) >= 0); - assert_se(streq(getenv("TMPDIR"), "/tmp")); + ASSERT_STREQ(getenv("TMPDIR"), "/tmp"); assert_se(var_tmp_dir(&tmp_dir) >= 0); - assert_se(streq(tmp_dir, "/tmp")); + ASSERT_STREQ(tmp_dir, "/tmp"); assert_se(setenv("TMPDIR", "/88_does_not_exist_88", true) >= 0); - assert_se(streq(getenv("TMPDIR"), "/88_does_not_exist_88")); + ASSERT_STREQ(getenv("TMPDIR"), "/88_does_not_exist_88"); assert_se(var_tmp_dir(&tmp_dir) >= 0); - assert_se(streq(tmp_dir, "/var/tmp")); + ASSERT_STREQ(tmp_dir, "/var/tmp"); if (tmpdir_backup) { assert_se(setenv("TMPDIR", tmpdir_backup, true) >= 0); - assert_se(streq(getenv("TMPDIR"), tmpdir_backup)); + ASSERT_STREQ(getenv("TMPDIR"), tmpdir_backup); } if (temp_backup) { assert_se(setenv("TEMP", temp_backup, true) >= 0); - assert_se(streq(getenv("TEMP"), temp_backup)); + ASSERT_STREQ(getenv("TEMP"), temp_backup); } if (tmp_backup) { assert_se(setenv("TMP", tmp_backup, true) >= 0); - assert_se(streq(getenv("TMP"), tmp_backup)); + ASSERT_STREQ(getenv("TMP"), tmp_backup); } } @@ -275,14 +275,14 @@ TEST(unlinkat_deallocate) { assert_se(write(fd, "hallo\n", 6) == 6); - assert_se(fstat(fd, &st) >= 0); + ASSERT_OK_ERRNO(fstat(fd, &st)); assert_se(st.st_size == 6); assert_se(st.st_blocks > 0); assert_se(st.st_nlink == 1); assert_se(unlinkat_deallocate(AT_FDCWD, p, UNLINK_ERASE) >= 0); - assert_se(fstat(fd, &st) >= 0); + ASSERT_OK_ERRNO(fstat(fd, &st)); assert_se(IN_SET(st.st_size, 0, 6)); /* depending on whether hole punching worked the size will be 6 (it worked) or 0 (we had to resort to truncation) */ assert_se(st.st_blocks == 0); @@ -522,9 +522,9 @@ static void test_parse_cifs_service_one(const char *f, const char *h, const char _cleanup_free_ char *a = NULL, *b = NULL, *c = NULL; assert_se(parse_cifs_service(f, &a, &b, &c) == ret); - assert_se(streq_ptr(a, h)); - assert_se(streq_ptr(b, s)); - assert_se(streq_ptr(c, d)); + ASSERT_STREQ(a, h); + ASSERT_STREQ(b, s); + ASSERT_STREQ(c, d); } TEST(parse_cifs_service) { @@ -557,13 +557,13 @@ TEST(open_mkdir_at) { fd = open_mkdir_at(AT_FDCWD, "/", O_CLOEXEC, 0); assert_se(fd >= 0); assert_se(stat("/", &sta) >= 0); - assert_se(fstat(fd, &stb) >= 0); + ASSERT_OK_ERRNO(fstat(fd, &stb)); assert_se(stat_inode_same(&sta, &stb)); fd = safe_close(fd); fd = open_mkdir_at(AT_FDCWD, ".", O_CLOEXEC, 0); assert_se(stat(".", &sta) >= 0); - assert_se(fstat(fd, &stb) >= 0); + ASSERT_OK_ERRNO(fstat(fd, &stb)); assert_se(stat_inode_same(&sta, &stb)); fd = safe_close(fd); @@ -753,6 +753,36 @@ TEST(xopenat_lock_full) { assert_se(xopenat_lock_full(tfd, "def", O_DIRECTORY, 0, 0755, LOCK_POSIX, LOCK_EX) == -EBADF); } +TEST(linkat_replace) { + _cleanup_(rm_rf_physical_and_freep) char *t = NULL; + _cleanup_close_ int tfd = -EBADF; + + assert_se((tfd = mkdtemp_open(NULL, 0, &t)) >= 0); + + _cleanup_close_ int fd1 = openat(tfd, "foo", O_CREAT|O_RDWR|O_CLOEXEC, 0600); + assert_se(fd1 >= 0); + + assert_se(linkat_replace(tfd, "foo", tfd, "bar") >= 0); + assert_se(linkat_replace(tfd, "foo", tfd, "bar") >= 0); + + _cleanup_close_ int fd1_check = openat(tfd, "bar", O_RDWR|O_CLOEXEC); + assert_se(fd1_check >= 0); + + assert_se(inode_same_at(fd1, NULL, fd1_check, NULL, AT_EMPTY_PATH) > 0); + + _cleanup_close_ int fd2 = openat(tfd, "baz", O_CREAT|O_RDWR|O_CLOEXEC, 0600); + assert_se(fd2 >= 0); + + assert_se(inode_same_at(fd1, NULL, fd2, NULL, AT_EMPTY_PATH) == 0); + + assert_se(linkat_replace(tfd, "foo", tfd, "baz") >= 0); + + _cleanup_close_ int fd2_check = openat(tfd, "baz", O_RDWR|O_CLOEXEC); + + assert_se(inode_same_at(fd2, NULL, fd2_check, NULL, AT_EMPTY_PATH) == 0); + assert_se(inode_same_at(fd1, NULL, fd2_check, NULL, AT_EMPTY_PATH) > 0); +} + static int intro(void) { arg_test_dir = saved_argv[1]; return EXIT_SUCCESS; @@ -770,25 +800,25 @@ TEST(readlinkat_malloc) { assert_se(symlinkat(expect, tfd, "linkname") >= 0); assert_se(readlinkat_malloc(tfd, "linkname", &p) >= 0); - assert_se(streq(p, expect)); + ASSERT_STREQ(p, expect); p = mfree(p); fd = openat(tfd, "linkname", O_PATH | O_NOFOLLOW | O_CLOEXEC); assert_se(fd >= 0); assert_se(readlinkat_malloc(fd, NULL, &p) >= 0); - assert_se(streq(p, expect)); + ASSERT_STREQ(p, expect); p = mfree(p); assert_se(readlinkat_malloc(fd, "", &p) >= 0); - assert_se(streq(p, expect)); + ASSERT_STREQ(p, expect); p = mfree(p); fd = safe_close(fd); assert_se(q = path_join(t, "linkname")); assert_se(readlinkat_malloc(AT_FDCWD, q, &p) >= 0); - assert_se(streq(p, expect)); + ASSERT_STREQ(p, expect); p = mfree(p); assert_se(readlinkat_malloc(INT_MAX, q, &p) >= 0); - assert_se(streq(p, expect)); + ASSERT_STREQ(p, expect); p = mfree(p); q = mfree(q); } diff --git a/src/test/test-fstab-util.c b/src/test/test-fstab-util.c index 89365b0..773b1f9 100644 --- a/src/test/test-fstab-util.c +++ b/src/test/test-fstab-util.c @@ -39,9 +39,9 @@ static void do_fstab_filter_options(const char *opts, opts, r, strnull(name), value, filtered, r_expected, strnull(name_expected), strnull(value_expected), filtered_expected ?: opts); assert_se(r == r_expected); - assert_se(streq_ptr(name, name_expected)); - assert_se(streq_ptr(value, value_expected)); - assert_se(streq_ptr(filtered, filtered_expected ?: opts)); + ASSERT_STREQ(name, name_expected); + ASSERT_STREQ(value, value_expected); + ASSERT_STREQ(filtered, filtered_expected ?: opts); /* test mode which returns all the values */ @@ -51,8 +51,8 @@ static void do_fstab_filter_options(const char *opts, opts, r, strnull(name), joined, r_values_expected, strnull(name_expected), strnull(values_expected)); assert_se(r == r_values_expected); - assert_se(streq_ptr(name, r_values_expected > 0 ? name_expected : NULL)); - assert_se(streq_ptr(joined, values_expected)); + ASSERT_STREQ(name, r_values_expected > 0 ? name_expected : NULL); + ASSERT_STREQ(joined, values_expected); /* also test the malloc-less mode */ r = fstab_filter_options(opts, remove, &name, NULL, NULL, NULL); @@ -60,7 +60,7 @@ static void do_fstab_filter_options(const char *opts, opts, r, strnull(name), r_expected, strnull(name_expected)); assert_se(r == r_expected); - assert_se(streq_ptr(name, name_expected)); + ASSERT_STREQ(name, name_expected); } TEST(fstab_filter_options) { @@ -116,7 +116,7 @@ TEST(fstab_filter_options) { do_fstab_filter_options(" opt ", "opt\0x-opt\0", 0, 0, NULL, NULL, "", NULL); /* check function with NULL args */ - do_fstab_filter_options(NULL, "opt\0", 0, 0, NULL, NULL, "", ""); + do_fstab_filter_options(NULL, "opt\0", 0, 0, NULL, NULL, "", NULL); do_fstab_filter_options("", "opt\0", 0, 0, NULL, NULL, "", ""); /* unnecessary comma separators */ @@ -160,32 +160,32 @@ TEST(fstab_node_to_udev_node) { n = fstab_node_to_udev_node("LABEL=applé/jack"); puts(n); - assert_se(streq(n, "/dev/disk/by-label/applé\\x2fjack")); + ASSERT_STREQ(n, "/dev/disk/by-label/applé\\x2fjack"); free(n); n = fstab_node_to_udev_node("PARTLABEL=pinkié pie"); puts(n); - assert_se(streq(n, "/dev/disk/by-partlabel/pinkié\\x20pie")); + ASSERT_STREQ(n, "/dev/disk/by-partlabel/pinkié\\x20pie"); free(n); n = fstab_node_to_udev_node("UUID=037b9d94-148e-4ee4-8d38-67bfe15bb535"); puts(n); - assert_se(streq(n, "/dev/disk/by-uuid/037b9d94-148e-4ee4-8d38-67bfe15bb535")); + ASSERT_STREQ(n, "/dev/disk/by-uuid/037b9d94-148e-4ee4-8d38-67bfe15bb535"); free(n); n = fstab_node_to_udev_node("PARTUUID=037b9d94-148e-4ee4-8d38-67bfe15bb535"); puts(n); - assert_se(streq(n, "/dev/disk/by-partuuid/037b9d94-148e-4ee4-8d38-67bfe15bb535")); + ASSERT_STREQ(n, "/dev/disk/by-partuuid/037b9d94-148e-4ee4-8d38-67bfe15bb535"); free(n); n = fstab_node_to_udev_node("PONIES=awesome"); puts(n); - assert_se(streq(n, "PONIES=awesome")); + ASSERT_STREQ(n, "PONIES=awesome"); free(n); n = fstab_node_to_udev_node("/dev/xda1"); puts(n); - assert_se(streq(n, "/dev/xda1")); + ASSERT_STREQ(n, "/dev/xda1"); free(n); } diff --git a/src/test/test-glob-util.c b/src/test/test-glob-util.c index 9b3e73c..49d71f1 100644 --- a/src/test/test-glob-util.c +++ b/src/test/test-glob-util.c @@ -24,14 +24,14 @@ TEST(glob_first) { r = glob_first("/tmp/test-glob_first*", &first); assert_se(r == 1); - assert_se(streq(name, first)); + ASSERT_STREQ(name, first); first = mfree(first); r = unlink(name); assert_se(r == 0); r = glob_first("/tmp/test-glob_first*", &first); assert_se(r == 0); - assert_se(first == NULL); + ASSERT_NULL(first); } TEST(glob_exists) { @@ -109,8 +109,8 @@ TEST(safe_glob) { r = safe_glob(fn2, GLOB_NOSORT|GLOB_BRACE, &g); assert_se(r == 0); assert_se(g.gl_pathc == 1); - assert_se(streq(g.gl_pathv[0], fname)); - assert_se(g.gl_pathv[1] == NULL); + ASSERT_STREQ(g.gl_pathv[0], fname); + ASSERT_NULL(g.gl_pathv[1]); (void) rm_rf(template, REMOVE_ROOT|REMOVE_PHYSICAL); } @@ -119,7 +119,7 @@ static void test_glob_non_glob_prefix_one(const char *path, const char *expected _cleanup_free_ char *t; assert_se(glob_non_glob_prefix(path, &t) == 0); - assert_se(streq(t, expected)); + ASSERT_STREQ(t, expected); } TEST(glob_non_glob) { diff --git a/src/test/test-gpt.c b/src/test/test-gpt.c index fa5923e..28b53d4 100644 --- a/src/test/test-gpt.c +++ b/src/test/test-gpt.c @@ -34,15 +34,15 @@ TEST(gpt_types_against_architectures) { printf("%s %s\n", GREEN_CHECK_MARK(), joined); if (streq(prefix, "root-") && streq(suffix, "")) - assert_se(type.designator == PARTITION_ROOT); + ASSERT_EQ(type.designator, PARTITION_ROOT); if (streq(prefix, "root-") && streq(suffix, "-verity")) - assert_se(type.designator == PARTITION_ROOT_VERITY); + ASSERT_EQ(type.designator, PARTITION_ROOT_VERITY); if (streq(prefix, "usr-") && streq(suffix, "")) - assert_se(type.designator == PARTITION_USR); + ASSERT_EQ(type.designator, PARTITION_USR); if (streq(prefix, "usr-") && streq(suffix, "-verity")) - assert_se(type.designator == PARTITION_USR_VERITY); + ASSERT_EQ(type.designator, PARTITION_USR_VERITY); - assert_se(type.arch == a); + ASSERT_EQ(type.arch, a); } } @@ -72,40 +72,40 @@ TEST(type_alias_same) { GptPartitionType x, y; x = gpt_partition_type_from_uuid(t->uuid); /* search first by uuid */ - assert_se(gpt_partition_type_from_string(t->name, &y) >= 0); /* search first by name */ + ASSERT_GE(gpt_partition_type_from_string(t->name, &y), 0); /* search first by name */ - assert_se(t->arch == x.arch); - assert_se(t->arch == y.arch); - assert_se(t->designator == x.designator); - assert_se(t->designator == y.designator); + ASSERT_EQ(t->arch, x.arch); + ASSERT_EQ(t->arch, y.arch); + ASSERT_EQ(t->designator, x.designator); + ASSERT_EQ(t->designator, y.designator); } } TEST(override_architecture) { GptPartitionType x, y; - assert_se(gpt_partition_type_from_string("root-x86-64", &x) >= 0); - assert_se(x.arch == ARCHITECTURE_X86_64); + ASSERT_GE(gpt_partition_type_from_string("root-x86-64", &x), 0); + ASSERT_EQ(x.arch, ARCHITECTURE_X86_64); - assert_se(gpt_partition_type_from_string("root-arm64", &y) >= 0); - assert(y.arch == ARCHITECTURE_ARM64); + ASSERT_GE(gpt_partition_type_from_string("root-arm64", &y), 0); + ASSERT_EQ(y.arch, ARCHITECTURE_ARM64); x = gpt_partition_type_override_architecture(x, ARCHITECTURE_ARM64); - assert_se(x.arch == y.arch); - assert_se(x.designator == y.designator); + ASSERT_EQ(x.arch, y.arch); + ASSERT_EQ(x.designator, y.designator); assert_se(sd_id128_equal(x.uuid, y.uuid)); - assert_se(streq(x.name, y.name)); + ASSERT_STREQ(x.name, y.name); /* If the partition type does not have an architecture, nothing should change. */ - assert_se(gpt_partition_type_from_string("esp", &x) >= 0); + ASSERT_GE(gpt_partition_type_from_string("esp", &x), 0); y = x; x = gpt_partition_type_override_architecture(x, ARCHITECTURE_ARM64); - assert_se(x.arch == y.arch); - assert_se(x.designator == y.designator); + ASSERT_EQ(x.arch, y.arch); + ASSERT_EQ(x.designator, y.designator); assert_se(sd_id128_equal(x.uuid, y.uuid)); - assert_se(streq(x.name, y.name)); + ASSERT_STREQ(x.name, y.name); } DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-hashmap-plain.c b/src/test/test-hashmap-plain.c index 152b1c0..f2d2d4f 100644 --- a/src/test/test-hashmap-plain.c +++ b/src/test/test-hashmap-plain.c @@ -10,6 +10,13 @@ #include "tests.h" #include "time-util.h" +/* PROJECT_FILE, which is used by ASSERT_XYZ(), cannot be used in generated files, as the build directory + * may be outside of the source directory. */ +#ifdef ORDERED +# undef PROJECT_FILE +# define PROJECT_FILE __FILE__ +#endif + TEST(hashmap_replace) { _cleanup_hashmap_free_ Hashmap *m = NULL; _cleanup_free_ char *val1 = NULL, *val2 = NULL, *val3 = NULL, *val4 = NULL, *val5 = NULL; @@ -35,11 +42,11 @@ TEST(hashmap_replace) { hashmap_replace(m, "key 3", val1); r = hashmap_get(m, "key 3"); - assert_se(streq(r, "val1")); + ASSERT_STREQ(r, "val1"); hashmap_replace(m, "key 5", val5); r = hashmap_get(m, "key 5"); - assert_se(streq(r, "val5")); + ASSERT_STREQ(r, "val5"); } TEST(hashmap_copy) { @@ -66,13 +73,13 @@ TEST(hashmap_copy) { copy = hashmap_copy(m); r = hashmap_get(copy, "key 1"); - assert_se(streq(r, "val1")); + ASSERT_STREQ(r, "val1"); r = hashmap_get(copy, "key 2"); - assert_se(streq(r, "val2")); + ASSERT_STREQ(r, "val2"); r = hashmap_get(copy, "key 3"); - assert_se(streq(r, "val3")); + ASSERT_STREQ(r, "val3"); r = hashmap_get(copy, "key 4"); - assert_se(streq(r, "val4")); + ASSERT_STREQ(r, "val4"); } TEST(hashmap_get_strv) { @@ -102,10 +109,10 @@ TEST(hashmap_get_strv) { strv = strv_sort(strv); #endif - assert_se(streq(strv[0], "val1")); - assert_se(streq(strv[1], "val2")); - assert_se(streq(strv[2], "val3")); - assert_se(streq(strv[3], "val4")); + ASSERT_STREQ(strv[0], "val1"); + ASSERT_STREQ(strv[1], "val2"); + ASSERT_STREQ(strv[2], "val3"); + ASSERT_STREQ(strv[3], "val4"); } TEST(hashmap_move_one) { @@ -196,15 +203,15 @@ TEST(hashmap_update) { hashmap_put(m, "key 1", val1); r = hashmap_get(m, "key 1"); - assert_se(streq(r, "old_value")); + ASSERT_STREQ(r, "old_value"); assert_se(hashmap_update(m, "key 2", val2) == -ENOENT); r = hashmap_get(m, "key 1"); - assert_se(streq(r, "old_value")); + ASSERT_STREQ(r, "old_value"); assert_se(hashmap_update(m, "key 1", val2) == 0); r = hashmap_get(m, "key 1"); - assert_se(streq(r, "new_value")); + ASSERT_STREQ(r, "new_value"); } TEST(hashmap_put) { @@ -231,22 +238,22 @@ TEST(hashmap_remove1) { char *r; r = hashmap_remove(NULL, "key 1"); - assert_se(r == NULL); + ASSERT_NULL(r); m = hashmap_new(&string_hash_ops); assert_se(m); r = hashmap_remove(m, "no such key"); - assert_se(r == NULL); + ASSERT_NULL(r); hashmap_put(m, "key 1", (void*) "val 1"); hashmap_put(m, "key 2", (void*) "val 2"); r = hashmap_remove(m, "key 1"); - assert_se(streq(r, "val 1")); + ASSERT_STREQ(r, "val 1"); r = hashmap_get(m, "key 2"); - assert_se(streq(r, "val 2")); + ASSERT_STREQ(r, "val 2"); assert_se(!hashmap_get(m, "key 1")); } @@ -259,25 +266,25 @@ TEST(hashmap_remove2) { void *r, *r2; r = hashmap_remove2(NULL, "key 1", &r2); - assert_se(r == NULL); + ASSERT_NULL(r); m = hashmap_new(&string_hash_ops); assert_se(m); r = hashmap_remove2(m, "no such key", &r2); - assert_se(r == NULL); + ASSERT_NULL(r); hashmap_put(m, strdup(key1), strdup(val1)); hashmap_put(m, strdup(key2), strdup(val2)); r = hashmap_remove2(m, key1, &r2); - assert_se(streq(r, val1)); - assert_se(streq(r2, key1)); + ASSERT_STREQ(r, val1); + ASSERT_STREQ(r2, key1); free(r); free(r2); r = hashmap_get(m, key2); - assert_se(streq(r, val2)); + ASSERT_STREQ(r, val2); assert_se(!hashmap_get(m, key1)); } @@ -289,29 +296,29 @@ TEST(hashmap_remove_value) { char val2[] = "val 2"; r = hashmap_remove_value(NULL, "key 1", val1); - assert_se(r == NULL); + ASSERT_NULL(r); m = hashmap_new(&string_hash_ops); assert_se(m); r = hashmap_remove_value(m, "key 1", val1); - assert_se(r == NULL); + ASSERT_NULL(r); hashmap_put(m, "key 1", val1); hashmap_put(m, "key 2", val2); r = hashmap_remove_value(m, "key 1", val1); - assert_se(streq(r, "val 1")); + ASSERT_STREQ(r, "val 1"); r = hashmap_get(m, "key 2"); - assert_se(streq(r, "val 2")); + ASSERT_STREQ(r, "val 2"); assert_se(!hashmap_get(m, "key 1")); r = hashmap_remove_value(m, "key 2", val1); - assert_se(r == NULL); + ASSERT_NULL(r); r = hashmap_get(m, "key 2"); - assert_se(streq(r, "val 2")); + ASSERT_STREQ(r, "val 2"); assert_se(!hashmap_get(m, "key 1")); } @@ -336,7 +343,7 @@ TEST(hashmap_remove_and_put) { assert_se(valid == 0); r = hashmap_get(m, "key 2"); - assert_se(streq(r, "val 2")); + ASSERT_STREQ(r, "val 2"); assert_se(!hashmap_get(m, "key 1")); valid = hashmap_put(m, "key 3", (void*) (const char *) "val 3"); @@ -599,17 +606,17 @@ TEST(hashmap_get) { assert_se(val); r = hashmap_get(NULL, "Key 1"); - assert_se(r == NULL); + ASSERT_NULL(r); m = hashmap_new(&string_hash_ops); hashmap_put(m, "Key 1", val); r = hashmap_get(m, "Key 1"); - assert_se(streq(r, val)); + ASSERT_STREQ(r, val); r = hashmap_get(m, "no such key"); - assert_se(r == NULL); + ASSERT_NULL(r); assert_se(m); } @@ -628,7 +635,7 @@ TEST(hashmap_get2) { assert_se(key_copy); r = hashmap_get2(NULL, key_orig, &key_copy); - assert_se(r == NULL); + ASSERT_NULL(r); m = hashmap_new(&string_hash_ops); @@ -636,12 +643,12 @@ TEST(hashmap_get2) { key_copy = NULL; r = hashmap_get2(m, key_orig, &key_copy); - assert_se(streq(r, val)); + ASSERT_STREQ(r, val); assert_se(key_orig != key_copy); - assert_se(streq(key_orig, key_copy)); + ASSERT_STREQ(key_orig, key_copy); r = hashmap_get2(m, "no such key", NULL); - assert_se(r == NULL); + ASSERT_NULL(r); assert_se(m); } @@ -780,12 +787,12 @@ TEST(hashmap_first) { assert_se(!hashmap_first(m)); assert_se(hashmap_put(m, "key 1", (void*) "val 1") == 1); - assert_se(streq(hashmap_first(m), "val 1")); + ASSERT_STREQ(hashmap_first(m), "val 1"); assert_se(hashmap_put(m, "key 2", (void*) "val 2") == 1); #ifdef ORDERED - assert_se(streq(hashmap_first(m), "val 1")); + ASSERT_STREQ(hashmap_first(m), "val 1"); assert_se(hashmap_remove(m, "key 1")); - assert_se(streq(hashmap_first(m), "val 2")); + ASSERT_STREQ(hashmap_first(m), "val 2"); #endif } @@ -797,12 +804,12 @@ TEST(hashmap_first_key) { assert_se(!hashmap_first_key(m)); assert_se(hashmap_put(m, "key 1", NULL) == 1); - assert_se(streq(hashmap_first_key(m), "key 1")); + ASSERT_STREQ(hashmap_first_key(m), "key 1"); assert_se(hashmap_put(m, "key 2", NULL) == 1); #ifdef ORDERED - assert_se(streq(hashmap_first_key(m), "key 1")); - assert_se(hashmap_remove(m, "key 1") == NULL); - assert_se(streq(hashmap_first_key(m), "key 2")); + ASSERT_STREQ(hashmap_first_key(m), "key 1"); + ASSERT_NULL(hashmap_remove(m, "key 1")); + ASSERT_STREQ(hashmap_first_key(m), "key 2"); #endif } @@ -814,7 +821,7 @@ TEST(hashmap_steal_first_key) { assert_se(!hashmap_steal_first_key(m)); assert_se(hashmap_put(m, "key 1", NULL) == 1); - assert_se(streq(hashmap_steal_first_key(m), "key 1")); + ASSERT_STREQ(hashmap_steal_first_key(m), "key 1"); assert_se(hashmap_isempty(m)); } @@ -965,6 +972,8 @@ TEST(string_strv_hashmap) { TEST(hashmap_dump_sorted) { static void * const expected[] = { UINT_TO_PTR(123U), UINT_TO_PTR(12U), UINT_TO_PTR(345U), }; + static const char *expected_keys[] = { "key 0", "key 1", "key 2", }; + static void * const expected_keys2[] = { UINT_TO_PTR(111U), UINT_TO_PTR(222U), UINT_TO_PTR(333U), }; _cleanup_hashmap_free_ Hashmap *m = NULL; _cleanup_free_ void **vals = NULL; size_t n; @@ -984,6 +993,13 @@ TEST(hashmap_dump_sorted) { assert_se(memcmp(vals, expected, n * sizeof(void*)) == 0); vals = mfree(vals); + + assert_se(hashmap_dump_keys_sorted(m, &vals, &n) >= 0); + assert_se(n == ELEMENTSOF(expected_keys)); + for (size_t i = 0; i < n; i++) + ASSERT_STREQ(vals[i], expected_keys[i]); + + vals = mfree(vals); m = hashmap_free(m); assert_se(m = hashmap_new(NULL)); @@ -999,6 +1015,12 @@ TEST(hashmap_dump_sorted) { assert_se(hashmap_dump_sorted(m, &vals, &n) >= 0); assert_se(n == ELEMENTSOF(expected)); assert_se(memcmp(vals, expected, n * sizeof(void*)) == 0); + + vals = mfree(vals); + + assert_se(hashmap_dump_keys_sorted(m, &vals, &n) >= 0); + assert_se(n == ELEMENTSOF(expected_keys2)); + assert_se(memcmp(vals, expected_keys2, n * sizeof(void*)) == 0); } /* Signal to test-hashmap.c that tests from this compilation unit were run. */ diff --git a/src/test/test-hashmap.c b/src/test/test-hashmap.c index 5daa0e6..74e68a4 100644 --- a/src/test/test-hashmap.c +++ b/src/test/test-hashmap.c @@ -42,7 +42,7 @@ TEST(trivial_compare_func) { } TEST(string_compare_func) { - assert_se(string_compare_func("fred", "wilma") != 0); + ASSERT_NE(string_compare_func("fred", "wilma"), 0); assert_se(string_compare_func("fred", "fred") == 0); } @@ -98,8 +98,8 @@ TEST(iterated_cache) { hashmap_clear(m); compare_cache(m, c); - assert_se(hashmap_free(m) == NULL); - assert_se(iterated_cache_free(c) == NULL); + ASSERT_NULL(hashmap_free(m)); + ASSERT_NULL(iterated_cache_free(c)); } TEST(hashmap_put_strdup) { @@ -116,7 +116,7 @@ TEST(hashmap_put_strdup) { assert_se(hashmap_contains(m, "foo")); s = hashmap_get(m, "foo"); - assert_se(streq(s, "bar")); + ASSERT_STREQ(s, "bar"); assert_se(hashmap_put_strdup(&m, "xxx", "bar") == 1); assert_se(hashmap_put_strdup(&m, "xxx", "bar") == 0); @@ -125,7 +125,7 @@ TEST(hashmap_put_strdup) { assert_se(hashmap_contains(m, "xxx")); s = hashmap_get(m, "xxx"); - assert_se(streq(s, "bar")); + ASSERT_STREQ(s, "bar"); } TEST(hashmap_put_strdup_null) { @@ -139,7 +139,7 @@ TEST(hashmap_put_strdup_null) { assert_se(hashmap_contains(m, "foo")); s = hashmap_get(m, "foo"); - assert_se(streq(s, "bar")); + ASSERT_STREQ(s, "bar"); assert_se(hashmap_put_strdup(&m, "xxx", NULL) == 1); assert_se(hashmap_put_strdup(&m, "xxx", "bar") == -EEXIST); @@ -147,7 +147,7 @@ TEST(hashmap_put_strdup_null) { assert_se(hashmap_contains(m, "xxx")); s = hashmap_get(m, "xxx"); - assert_se(s == NULL); + ASSERT_NULL(s); } /* This file tests in test-hashmap-plain.c, and tests in test-hashmap-ordered.c, which is generated diff --git a/src/test/test-hexdecoct.c b/src/test/test-hexdecoct.c index f884008..5c39fc7 100644 --- a/src/test/test-hexdecoct.c +++ b/src/test/test-hexdecoct.c @@ -80,9 +80,9 @@ static void test_hexmem_one(const char *in, const char *expected) { assert_se(result = hexmem(in, strlen_ptr(in))); log_debug("hexmem(\"%s\") → \"%s\" (expected: \"%s\")", strnull(in), result, expected); - assert_se(streq(result, expected)); + ASSERT_STREQ(result, expected); - assert_se(unhexmem(result, SIZE_MAX, &mem, &len) >= 0); + assert_se(unhexmem(result, &mem, &len) >= 0); assert_se(memcmp_safe(mem, in, len) == 0); } @@ -97,7 +97,7 @@ static void test_unhexmem_one(const char *s, size_t l, int retval) { _cleanup_free_ void *mem = NULL; size_t len; - assert_se(unhexmem(s, l, &mem, &len) == retval); + assert_se(unhexmem_full(s, l, /* secure = */ false, &mem, &len) == retval); if (retval == 0) { char *answer; @@ -106,7 +106,7 @@ static void test_unhexmem_one(const char *s, size_t l, int retval) { assert_se(hex = hexmem(mem, len)); answer = strndupa_safe(strempty(s), l); - assert_se(streq(delete_chars(answer, WHITESPACE), hex)); + ASSERT_STREQ(delete_chars(answer, WHITESPACE), hex); } } @@ -134,72 +134,72 @@ TEST(base32hexmem) { b32 = base32hexmem("", STRLEN(""), true); assert_se(b32); - assert_se(streq(b32, "")); + ASSERT_STREQ(b32, ""); free(b32); b32 = base32hexmem("f", STRLEN("f"), true); assert_se(b32); - assert_se(streq(b32, "CO======")); + ASSERT_STREQ(b32, "CO======"); free(b32); b32 = base32hexmem("fo", STRLEN("fo"), true); assert_se(b32); - assert_se(streq(b32, "CPNG====")); + ASSERT_STREQ(b32, "CPNG===="); free(b32); b32 = base32hexmem("foo", STRLEN("foo"), true); assert_se(b32); - assert_se(streq(b32, "CPNMU===")); + ASSERT_STREQ(b32, "CPNMU==="); free(b32); b32 = base32hexmem("foob", STRLEN("foob"), true); assert_se(b32); - assert_se(streq(b32, "CPNMUOG=")); + ASSERT_STREQ(b32, "CPNMUOG="); free(b32); b32 = base32hexmem("fooba", STRLEN("fooba"), true); assert_se(b32); - assert_se(streq(b32, "CPNMUOJ1")); + ASSERT_STREQ(b32, "CPNMUOJ1"); free(b32); b32 = base32hexmem("foobar", STRLEN("foobar"), true); assert_se(b32); - assert_se(streq(b32, "CPNMUOJ1E8======")); + ASSERT_STREQ(b32, "CPNMUOJ1E8======"); free(b32); b32 = base32hexmem("", STRLEN(""), false); assert_se(b32); - assert_se(streq(b32, "")); + ASSERT_STREQ(b32, ""); free(b32); b32 = base32hexmem("f", STRLEN("f"), false); assert_se(b32); - assert_se(streq(b32, "CO")); + ASSERT_STREQ(b32, "CO"); free(b32); b32 = base32hexmem("fo", STRLEN("fo"), false); assert_se(b32); - assert_se(streq(b32, "CPNG")); + ASSERT_STREQ(b32, "CPNG"); free(b32); b32 = base32hexmem("foo", STRLEN("foo"), false); assert_se(b32); - assert_se(streq(b32, "CPNMU")); + ASSERT_STREQ(b32, "CPNMU"); free(b32); b32 = base32hexmem("foob", STRLEN("foob"), false); assert_se(b32); - assert_se(streq(b32, "CPNMUOG")); + ASSERT_STREQ(b32, "CPNMUOG"); free(b32); b32 = base32hexmem("fooba", STRLEN("fooba"), false); assert_se(b32); - assert_se(streq(b32, "CPNMUOJ1")); + ASSERT_STREQ(b32, "CPNMUOJ1"); free(b32); b32 = base32hexmem("foobar", STRLEN("foobar"), false); assert_se(b32); - assert_se(streq(b32, "CPNMUOJ1E8")); + ASSERT_STREQ(b32, "CPNMUOJ1E8"); free(b32); } @@ -212,7 +212,7 @@ static void test_unbase32hexmem_one(const char *hex, bool padding, int retval, c char *str; str = strndupa_safe(mem, len); - assert_se(streq(str, ans)); + ASSERT_STREQ(str, ans); } } @@ -268,31 +268,31 @@ TEST(base64mem) { char *b64; assert_se(base64mem("", STRLEN(""), &b64) == 0); - assert_se(streq(b64, "")); + ASSERT_STREQ(b64, ""); free(b64); assert_se(base64mem("f", STRLEN("f"), &b64) == 4); - assert_se(streq(b64, "Zg==")); + ASSERT_STREQ(b64, "Zg=="); free(b64); assert_se(base64mem("fo", STRLEN("fo"), &b64) == 4); - assert_se(streq(b64, "Zm8=")); + ASSERT_STREQ(b64, "Zm8="); free(b64); assert_se(base64mem("foo", STRLEN("foo"), &b64) == 4); - assert_se(streq(b64, "Zm9v")); + ASSERT_STREQ(b64, "Zm9v"); free(b64); assert_se(base64mem("foob", STRLEN("foob"), &b64) == 8); - assert_se(streq(b64, "Zm9vYg==")); + ASSERT_STREQ(b64, "Zm9vYg=="); free(b64); assert_se(base64mem("fooba", STRLEN("fooba"), &b64) == 8); - assert_se(streq(b64, "Zm9vYmE=")); + ASSERT_STREQ(b64, "Zm9vYmE="); free(b64); assert_se(base64mem("foobar", STRLEN("foobar"), &b64) == 8); - assert_se(streq(b64, "Zm9vYmFy")); + ASSERT_STREQ(b64, "Zm9vYmFy"); free(b64); } @@ -318,7 +318,7 @@ TEST(base64mem_linebreak) { assert_se(encoded); assert_se((size_t) l == strlen(encoded)); - assert_se(unbase64mem(encoded, SIZE_MAX, &decoded, &decoded_size) >= 0); + assert_se(unbase64mem(encoded, &decoded, &decoded_size) >= 0); assert_se(decoded_size == n); assert_se(memcmp(data, decoded, n) == 0); @@ -341,7 +341,7 @@ static void test_base64_append_one(char **buf, size_t *len, const char *in, cons assert_se(new_len >= 0); log_debug("base64_append_one(\"%s\")\nresult:\n%s\nexpected:\n%s", in, strnull(*buf), strnull(expected)); assert_se((size_t) new_len == strlen_ptr(*buf)); - assert_se(streq_ptr(*buf, expected)); + ASSERT_STREQ(*buf, expected); *len = new_len; } @@ -452,7 +452,7 @@ static void test_unbase64mem_one(const char *input, const char *output, int ret) _cleanup_free_ void *buffer = NULL; size_t size = 0; - assert_se(unbase64mem(input, SIZE_MAX, &buffer, &size) == ret); + assert_se(unbase64mem(input, &buffer, &size) == ret); if (ret >= 0) { assert_se(size == strlen(output)); assert_se(memcmp(buffer, output, size) == 0); @@ -533,12 +533,12 @@ TEST(base64withwithouturl) { size_t size; /* This is regular base64 */ - assert_se(unbase64mem("zKFyIq7aZn4EpuCCmpcF9jPgD8JFE1g/xfT0Mas8X4M0WycyigRsQ4IH4yysufus0AORQsuk3oeGhRC7t1tLyKD0Ih0VcYedv5+p8e6itqrIwzecu98+rNyUVDhWBzS0PMwxEw==", SIZE_MAX, &buffer, &size) >= 0); + assert_se(unbase64mem("zKFyIq7aZn4EpuCCmpcF9jPgD8JFE1g/xfT0Mas8X4M0WycyigRsQ4IH4yysufus0AORQsuk3oeGhRC7t1tLyKD0Ih0VcYedv5+p8e6itqrIwzecu98+rNyUVDhWBzS0PMwxEw==", &buffer, &size) >= 0); assert_se(memcmp_nn(plaintext, sizeof(plaintext), buffer, size) == 0); buffer = mfree(buffer); /* This is the same but in base64url */ - assert_se(unbase64mem("zKFyIq7aZn4EpuCCmpcF9jPgD8JFE1g_xfT0Mas8X4M0WycyigRsQ4IH4yysufus0AORQsuk3oeGhRC7t1tLyKD0Ih0VcYedv5-p8e6itqrIwzecu98-rNyUVDhWBzS0PMwxEw==", SIZE_MAX, &buffer, &size) >= 0); + assert_se(unbase64mem("zKFyIq7aZn4EpuCCmpcF9jPgD8JFE1g_xfT0Mas8X4M0WycyigRsQ4IH4yysufus0AORQsuk3oeGhRC7t1tLyKD0Ih0VcYedv5-p8e6itqrIwzecu98-rNyUVDhWBzS0PMwxEw==", &buffer, &size) >= 0); assert_se(memcmp_nn(plaintext, sizeof(plaintext), buffer, size) == 0); /* Hint: use xxd -i to generate the static C array from some data, and basenc --base64 + basenc diff --git a/src/test/test-hmac.c b/src/test/test-hmac.c index 1b788b1..28f7ab9 100644 --- a/src/test/test-hmac.c +++ b/src/test/test-hmac.c @@ -19,49 +19,49 @@ TEST(hmac) { "", result); hex_result = hexmem(result, sizeof(result)); - assert_se(streq_ptr(hex_result, "cadd5e42114351181f3abff477641d88efb57d2b5641a1e5c6d623363a6d3bad")); + ASSERT_STREQ(hex_result, "cadd5e42114351181f3abff477641d88efb57d2b5641a1e5c6d623363a6d3bad"); hex_result = mfree(hex_result); hmac_sha256_by_string("waldo", "baldohaldo", result); hex_result = hexmem(result, sizeof(result)); - assert_se(streq_ptr(hex_result, "c47ad5031ba21605e52c6ca68090d66a2dd5ccf84efa4bace15361a8cba63cda")); + ASSERT_STREQ(hex_result, "c47ad5031ba21605e52c6ca68090d66a2dd5ccf84efa4bace15361a8cba63cda"); hex_result = mfree(hex_result); hmac_sha256_by_string("waldo", "baldo haldo", result); hex_result = hexmem(result, sizeof(result)); - assert_se(streq_ptr(hex_result, "4e8974ad6c08b98cc2519cd1e27aa7195769fcf86db1dd7ceaab4d44c490ad69")); + ASSERT_STREQ(hex_result, "4e8974ad6c08b98cc2519cd1e27aa7195769fcf86db1dd7ceaab4d44c490ad69"); hex_result = mfree(hex_result); hmac_sha256_by_string("waldo", "baldo 4e8974ad6c08b98cc2519cd1e27aa7195769fcf86db1dd7ceaab4d44c490ad69 haldo", result); hex_result = hexmem(result, sizeof(result)); - assert_se(streq_ptr(hex_result, "039f3df430b19753ffb493e5b90708f75c5210b63c6bcbef3374eb3f0a3f97f7")); + ASSERT_STREQ(hex_result, "039f3df430b19753ffb493e5b90708f75c5210b63c6bcbef3374eb3f0a3f97f7"); hex_result = mfree(hex_result); hmac_sha256_by_string("4e8974ad6c08b98cc2519cd1e27aa7195769fcf86db1dd7ceaab4d44c490ad69", "baldo haldo", result); hex_result = hexmem(result, sizeof(result)); - assert_se(streq_ptr(hex_result, "c4cfaf48077cbb0bbd177a09e59ec4c248f4ca771503410f5b54b98d88d2f47b")); + ASSERT_STREQ(hex_result, "c4cfaf48077cbb0bbd177a09e59ec4c248f4ca771503410f5b54b98d88d2f47b"); hex_result = mfree(hex_result); hmac_sha256_by_string("4e8974ad6c08b98cc2519cd1e27aa7195769fcf86db1dd7ceaab4d44c490ad69", "supercalifragilisticexpialidocious", result); hex_result = hexmem(result, sizeof(result)); - assert_se(streq_ptr(hex_result, "2c059e7a63c4c3b23f47966a65fd2f8a2f5d7161e2e90d78ff68866b5c375cb7")); + ASSERT_STREQ(hex_result, "2c059e7a63c4c3b23f47966a65fd2f8a2f5d7161e2e90d78ff68866b5c375cb7"); hex_result = mfree(hex_result); hmac_sha256_by_string("4e8974ad6c08b98cc2519cd1e27aa7195769fcf86db1dd7ceaab4d44c490ad69c47ad5031ba21605e52c6ca68090d66a2dd5ccf84efa4bace15361a8cba63cda", "supercalifragilisticexpialidocious", result); hex_result = hexmem(result, sizeof(result)); - assert_se(streq_ptr(hex_result, "1dd1d1d45b9d9f9673dc9983c968c46ff3168e03cfeb4156a219eba1af4cff5f")); + ASSERT_STREQ(hex_result, "1dd1d1d45b9d9f9673dc9983c968c46ff3168e03cfeb4156a219eba1af4cff5f"); hex_result = mfree(hex_result); } diff --git a/src/test/test-hostname-setup.c b/src/test/test-hostname-setup.c index 94e5ece..2365a5e 100644 --- a/src/test/test-hostname-setup.c +++ b/src/test/test-hostname-setup.c @@ -22,28 +22,28 @@ TEST(read_etc_hostname) { /* simple hostname */ assert_se(write_string_file(path, "foo", WRITE_STRING_FILE_CREATE) == 0); assert_se(read_etc_hostname(path, &hostname) == 0); - assert_se(streq(hostname, "foo")); + ASSERT_STREQ(hostname, "foo"); hostname = mfree(hostname); /* with comment */ assert_se(write_string_file(path, "# comment\nfoo", WRITE_STRING_FILE_CREATE) == 0); assert_se(read_etc_hostname(path, &hostname) == 0); assert_se(hostname); - assert_se(streq(hostname, "foo")); + ASSERT_STREQ(hostname, "foo"); hostname = mfree(hostname); /* with comment and extra whitespace */ assert_se(write_string_file(path, "# comment\n\n foo ", WRITE_STRING_FILE_CREATE) == 0); assert_se(read_etc_hostname(path, &hostname) == 0); assert_se(hostname); - assert_se(streq(hostname, "foo")); + ASSERT_STREQ(hostname, "foo"); hostname = mfree(hostname); /* cleans up name */ assert_se(write_string_file(path, "!foo/bar.com", WRITE_STRING_FILE_CREATE) == 0); assert_se(read_etc_hostname(path, &hostname) == 0); assert_se(hostname); - assert_se(streq(hostname, "foobar.com")); + ASSERT_STREQ(hostname, "foobar.com"); hostname = mfree(hostname); /* no value set */ diff --git a/src/test/test-hostname-util.c b/src/test/test-hostname-util.c index 77e9a19..a7eccf8 100644 --- a/src/test/test-hostname-util.c +++ b/src/test/test-hostname-util.c @@ -50,27 +50,27 @@ TEST(hostname_cleanup) { char *s; s = strdupa_safe("foobar"); - assert_se(streq(hostname_cleanup(s), "foobar")); + ASSERT_STREQ(hostname_cleanup(s), "foobar"); s = strdupa_safe("foobar.com"); - assert_se(streq(hostname_cleanup(s), "foobar.com")); + ASSERT_STREQ(hostname_cleanup(s), "foobar.com"); s = strdupa_safe("foobar.com."); - assert_se(streq(hostname_cleanup(s), "foobar.com")); + ASSERT_STREQ(hostname_cleanup(s), "foobar.com"); s = strdupa_safe("foo-bar.-com-."); - assert_se(streq(hostname_cleanup(s), "foo-bar.com")); + ASSERT_STREQ(hostname_cleanup(s), "foo-bar.com"); s = strdupa_safe("foo-bar-.-com-."); - assert_se(streq(hostname_cleanup(s), "foo-bar--com")); + ASSERT_STREQ(hostname_cleanup(s), "foo-bar--com"); s = strdupa_safe("--foo-bar.-com"); - assert_se(streq(hostname_cleanup(s), "foo-bar.com")); + ASSERT_STREQ(hostname_cleanup(s), "foo-bar.com"); s = strdupa_safe("fooBAR"); - assert_se(streq(hostname_cleanup(s), "fooBAR")); + ASSERT_STREQ(hostname_cleanup(s), "fooBAR"); s = strdupa_safe("fooBAR.com"); - assert_se(streq(hostname_cleanup(s), "fooBAR.com")); + ASSERT_STREQ(hostname_cleanup(s), "fooBAR.com"); s = strdupa_safe("fooBAR."); - assert_se(streq(hostname_cleanup(s), "fooBAR")); + ASSERT_STREQ(hostname_cleanup(s), "fooBAR"); s = strdupa_safe("fooBAR.com."); - assert_se(streq(hostname_cleanup(s), "fooBAR.com")); + ASSERT_STREQ(hostname_cleanup(s), "fooBAR.com"); s = strdupa_safe("fööbar"); - assert_se(streq(hostname_cleanup(s), "fbar")); + ASSERT_STREQ(hostname_cleanup(s), "fbar"); s = strdupa_safe(""); assert_se(isempty(hostname_cleanup(s))); s = strdupa_safe("."); @@ -78,17 +78,17 @@ TEST(hostname_cleanup) { s = strdupa_safe(".."); assert_se(isempty(hostname_cleanup(s))); s = strdupa_safe("foobar."); - assert_se(streq(hostname_cleanup(s), "foobar")); + ASSERT_STREQ(hostname_cleanup(s), "foobar"); s = strdupa_safe(".foobar"); - assert_se(streq(hostname_cleanup(s), "foobar")); + ASSERT_STREQ(hostname_cleanup(s), "foobar"); s = strdupa_safe("foo..bar"); - assert_se(streq(hostname_cleanup(s), "foo.bar")); + ASSERT_STREQ(hostname_cleanup(s), "foo.bar"); s = strdupa_safe("foo.bar.."); - assert_se(streq(hostname_cleanup(s), "foo.bar")); + ASSERT_STREQ(hostname_cleanup(s), "foo.bar"); s = strdupa_safe("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); - assert_se(streq(hostname_cleanup(s), "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")); + ASSERT_STREQ(hostname_cleanup(s), "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); s = strdupa_safe("xxxx........xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); - assert_se(streq(hostname_cleanup(s), "xxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")); + ASSERT_STREQ(hostname_cleanup(s), "xxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); } TEST(hostname_malloc) { diff --git a/src/test/test-id128.c b/src/test/test-id128.c index ae7df27..48fdbba 100644 --- a/src/test/test-id128.c +++ b/src/test/test-id128.c @@ -50,19 +50,19 @@ TEST(id128) { } printf("waldi: %s\n", sd_id128_to_string(ID128_WALDI, t)); - assert_se(streq(t, STR_WALDI)); + ASSERT_STREQ(t, STR_WALDI); assert_se(asprintf(&b, SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(ID128_WALDI)) == 32); printf("waldi2: %s\n", b); - assert_se(streq(t, b)); + ASSERT_STREQ(t, b); printf("waldi3: %s\n", sd_id128_to_uuid_string(ID128_WALDI, q)); - assert_se(streq(q, UUID_WALDI)); + ASSERT_STREQ(q, UUID_WALDI); b = mfree(b); assert_se(asprintf(&b, SD_ID128_UUID_FORMAT_STR, SD_ID128_FORMAT_VAL(ID128_WALDI)) == 36); printf("waldi4: %s\n", b); - assert_se(streq(q, b)); + ASSERT_STREQ(q, b); assert_se(sd_id128_from_string(STR_WALDI, &id) >= 0); assert_se(sd_id128_equal(id, ID128_WALDI)); @@ -194,12 +194,12 @@ TEST(id128) { } /* Check return values */ - assert_se(sd_id128_get_app_specific(SD_ID128_ALLF, SD_ID128_NULL, &id) == -ENXIO); - assert_se(sd_id128_get_app_specific(SD_ID128_NULL, SD_ID128_ALLF, &id) == 0); + ASSERT_RETURN_EXPECTED_SE(sd_id128_get_app_specific(SD_ID128_ALLF, SD_ID128_NULL, &id) == -ENXIO); + ASSERT_RETURN_EXPECTED_SE(sd_id128_get_app_specific(SD_ID128_NULL, SD_ID128_ALLF, &id) == 0); } TEST(sd_id128_get_invocation) { - sd_id128_t id; + sd_id128_t id = SD_ID128_NULL; int r; /* Query the invocation ID */ @@ -208,6 +208,36 @@ TEST(sd_id128_get_invocation) { log_warning_errno(r, "Failed to get invocation ID, ignoring: %m"); else log_info("Invocation ID: " SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(id)); + + sd_id128_t appid = SD_ID128_NULL; + r = sd_id128_get_invocation_app_specific(SD_ID128_MAKE(59,36,e9,92,fd,11,42,fe,87,c9,e9,b5,6c,9e,4f,04), &appid); + if (r < 0) + log_warning_errno(r, "Failed to get invocation ID, ignoring: %m"); + else { + assert(!sd_id128_equal(id, appid)); + log_info("Per-App Invocation ID: " SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(appid)); + } + + sd_id128_t appid2 = SD_ID128_NULL; + r = sd_id128_get_invocation_app_specific(SD_ID128_MAKE(59,36,e9,92,fd,11,42,fe,87,c9,e9,b5,6c,9e,4f,05), &appid2); /* slightly different appid */ + if (r < 0) + log_warning_errno(r, "Failed to get invocation ID, ignoring: %m"); + else { + assert(!sd_id128_equal(id, appid2)); + assert(!sd_id128_equal(appid, appid2)); + log_info("Per-App Invocation ID 2: " SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(appid2)); + } + + sd_id128_t appid3 = SD_ID128_NULL; + r = sd_id128_get_invocation_app_specific(SD_ID128_MAKE(59,36,e9,92,fd,11,42,fe,87,c9,e9,b5,6c,9e,4f,04), &appid3); /* same appid as before */ + if (r < 0) + log_warning_errno(r, "Failed to get invocation ID, ignoring: %m"); + else { + assert(!sd_id128_equal(id, appid3)); + assert(sd_id128_equal(appid, appid3)); + assert(!sd_id128_equal(appid2, appid3)); + log_info("Per-App Invocation ID 3: " SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(appid3)); + } } TEST(benchmark_sd_id128_get_machine_app_specific) { diff --git a/src/test/test-image-policy.c b/src/test/test-image-policy.c index d9fe556..12fc10a 100644 --- a/src/test/test-image-policy.c +++ b/src/test/test-image-policy.c @@ -79,6 +79,7 @@ TEST_RET(test_image_policy_to_string) { test_policy(&image_policy_sysext, "sysext"); test_policy(&image_policy_sysext_strict, "sysext-strict"); test_policy(&image_policy_confext, "confext"); + test_policy(&image_policy_confext_strict, "confext-strict"); test_policy(&image_policy_container, "container"); test_policy(&image_policy_host, "host"); test_policy(&image_policy_service, "service"); @@ -129,4 +130,36 @@ TEST(extend) { assert_se(partition_policy_flags_extend(PARTITION_POLICY_GROWFS_ON) == (PARTITION_POLICY_GROWFS_ON|_PARTITION_POLICY_USE_MASK|_PARTITION_POLICY_READ_ONLY_MASK)); } +static void test_policy_intersect_one(const char *a, const char *b, const char *c) { + _cleanup_(image_policy_freep) ImagePolicy *x = NULL, *y = NULL, *z = NULL, *t = NULL; + + assert_se(image_policy_from_string(a, &x) >= 0); + assert_se(image_policy_from_string(b, &y) >= 0); + assert_se(image_policy_from_string(c, &z) >= 0); + + assert_se(image_policy_intersect(x, y, &t) >= 0); + + _cleanup_free_ char *s1 = NULL, *s2 = NULL, *s3 = NULL, *s4 = NULL; + assert_se(image_policy_to_string(x, false, &s1) >= 0); + assert_se(image_policy_to_string(y, false, &s2) >= 0); + assert_se(image_policy_to_string(z, false, &s3) >= 0); + assert_se(image_policy_to_string(t, false, &s4) >= 0); + + log_info("%s ^ %s → %s vs. %s", s1, s2, s3, s4); + + assert_se(image_policy_equivalent(z, t) > 0); +} + +TEST(image_policy_intersect) { + test_policy_intersect_one("", "", ""); + test_policy_intersect_one("-", "-", "-"); + test_policy_intersect_one("*", "*", "*"); + test_policy_intersect_one("~", "~", "~"); + test_policy_intersect_one("root=verity+signed", "root=signed+verity", "root=verity+signed"); + test_policy_intersect_one("root=verity+signed", "root=signed", "root=signed"); + test_policy_intersect_one("root=verity+signed", "root=verity", "root=verity"); + test_policy_intersect_one("root=open", "root=verity", "root=verity"); + test_policy_intersect_one("root=open", "=verity+ignore", "root=verity+ignore:=ignore"); +} + DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-import-util.c b/src/test/test-import-util.c index 7930fe5..cc7b139 100644 --- a/src/test/test-import-util.c +++ b/src/test/test-import-util.c @@ -10,7 +10,7 @@ static void test_import_url_last_component_one(const char *input, const char *ou _cleanup_free_ char *s = NULL; assert_se(import_url_last_component(input, &s) == ret); - assert_se(streq_ptr(output, s)); + ASSERT_STREQ(output, s); } TEST(import_url_last_component) { @@ -37,7 +37,7 @@ static void test_import_url_change_suffix_one(const char *input, size_t n, const _cleanup_free_ char *s = NULL; assert_se(import_url_change_suffix(input, n, suffix, &s) == ret); - assert_se(streq_ptr(output, s)); + ASSERT_STREQ(output, s); } TEST(import_url_change_suffix) { diff --git a/src/test/test-in-addr-prefix-util.c b/src/test/test-in-addr-prefix-util.c index 661ca8f..2b44bab 100644 --- a/src/test/test-in-addr-prefix-util.c +++ b/src/test/test-in-addr-prefix-util.c @@ -12,8 +12,8 @@ static void test_in_addr_prefix_to_string_one(int f, const char *addr, unsigned printf("%s: %s/%u == %s\n", __func__, addr, prefixlen, r); assert_se(startswith(r, addr)); - assert_se(streq(r, IN_ADDR_PREFIX_TO_STRING(f, &ua, prefixlen))); - assert_se(streq(IN_ADDR_PREFIX_TO_STRING(f, &ua, prefixlen), r)); + ASSERT_STREQ(r, IN_ADDR_PREFIX_TO_STRING(f, &ua, prefixlen)); + ASSERT_STREQ(IN_ADDR_PREFIX_TO_STRING(f, &ua, prefixlen), r); } TEST(in_addr_to_string_prefix) { @@ -35,8 +35,8 @@ static void test_config_parse_in_addr_prefixes_one(int family, const union in_ad assert_se(config_parse_in_addr_prefixes("unit", "filename", 1, "Service", 1, "IPAddressAllow", 0, str, prefixes, NULL) >= 0); - assert_se(streq(str, IN_ADDR_PREFIX_TO_STRING(family, addr, prefixlen))); - assert_se(streq(IN_ADDR_PREFIX_TO_STRING(family, addr, prefixlen), str)); + ASSERT_STREQ(str, IN_ADDR_PREFIX_TO_STRING(family, addr, prefixlen)); + ASSERT_STREQ(IN_ADDR_PREFIX_TO_STRING(family, addr, prefixlen), str); } static void test_config_parse_in_addr_prefixes(Set **ret) { diff --git a/src/test/test-in-addr-util.c b/src/test/test-in-addr-util.c index 93ab1c5..fcc9a0a 100644 --- a/src/test/test-in-addr-util.c +++ b/src/test/test-in-addr-util.c @@ -81,7 +81,7 @@ static void test_in_addr_prefix_to_string_valid(int family, const char *p) { log_info("%s: %s", __func__, p); assert_se(in_addr_prefix_from_string(p, family, &u, &l) >= 0); - assert_se(streq(p, IN_ADDR_PREFIX_TO_STRING(family, &u, l))); + ASSERT_STREQ(p, IN_ADDR_PREFIX_TO_STRING(family, &u, l)); } static void test_in_addr_prefix_to_string_unoptimized(int family, const char *p) { @@ -97,7 +97,7 @@ static void test_in_addr_prefix_to_string_unoptimized(int family, const char *p) const char *str2 = IN_ADDR_PREFIX_TO_STRING(family, &u2, len2); assert_se(str2); - assert_se(streq(str1, str2)); + ASSERT_STREQ(str1, str2); assert_se(len1 == len2); assert_se(in_addr_equal(family, &u1, &u2) > 0); } @@ -340,9 +340,9 @@ static void test_in_addr_to_string_one(int f, const char *addr) { assert_se(in_addr_from_string(f, addr, &ua) >= 0); assert_se(in_addr_to_string(f, &ua, &r) >= 0); printf("%s: %s == %s\n", __func__, addr, r); - assert_se(streq(addr, r)); + ASSERT_STREQ(addr, r); - assert_se(streq(r, IN_ADDR_TO_STRING(f, &ua))); + ASSERT_STREQ(r, IN_ADDR_TO_STRING(f, &ua)); } TEST(in_addr_to_string) { @@ -391,7 +391,7 @@ TEST(in_addr_prefixlen_to_netmask) { assert_se(in_addr_prefixlen_to_netmask(AF_INET, &addr, prefixlen) >= 0); assert_se(in_addr_to_string(AF_INET, &addr, &result) >= 0); printf("test_in_addr_prefixlen_to_netmask: %s == %s\n", ipv4_netmasks[prefixlen], result); - assert_se(streq(ipv4_netmasks[prefixlen], result)); + ASSERT_STREQ(ipv4_netmasks[prefixlen], result); } for (unsigned char prefixlen = 0; prefixlen <= 128; prefixlen++) { @@ -401,7 +401,58 @@ TEST(in_addr_prefixlen_to_netmask) { assert_se(in_addr_to_string(AF_INET6, &addr, &result) >= 0); printf("test_in_addr_prefixlen_to_netmask: %s\n", result); if (ipv6_netmasks[prefixlen]) - assert_se(streq(ipv6_netmasks[prefixlen], result)); + ASSERT_STREQ(ipv6_netmasks[prefixlen], result); + } +} + +static void in_addr_prefix_covers_full_one(const char *prefix, const char *address, int expected) { + union in_addr_union p, a; + unsigned char plen, alen; + int family, r; + + assert_se(in_addr_prefix_from_string_auto(prefix, &family, &p, &plen) >= 0); + assert_se(in_addr_prefix_from_string(address, family, &a, &alen) >= 0); + r = in_addr_prefix_covers_full(family, &p, plen, &a, alen); + if (r != expected) + log_error("in_addr_prefix_covers_full(%s, %s)=%i (expected=%i)", prefix, address, r, expected); + assert_se(r == expected); +} + +TEST(in_addr_prefix_covers_full) { + /* From issue #32715. */ + in_addr_prefix_covers_full_one("192.168.235.129/32", "192.168.0.128/32", 0); + in_addr_prefix_covers_full_one("192.168.235.130/32", "192.168.0.128/32", 0); + in_addr_prefix_covers_full_one("169.254.0.0/17", "192.168.0.128/32", 0); + in_addr_prefix_covers_full_one("169.254.128.0/17", "192.168.0.128/32", 0); + in_addr_prefix_covers_full_one("0.0.0.0/1", "192.168.0.128/32", 0); + in_addr_prefix_covers_full_one("128.0.0.0/1", "192.168.0.128/32", 1); + in_addr_prefix_covers_full_one("0.0.0.0/0", "192.168.0.128/32", 1); + + for (unsigned i = 0; i <= 32; i++) { + _cleanup_free_ char *prefix = NULL; + + assert_se(asprintf(&prefix, "192.168.0.128/%u", i) >= 0); + + for (unsigned j = 0; j <= 32; j++) { + _cleanup_free_ char *address = NULL; + + assert_se(asprintf(&address, "192.168.0.128/%u", j) >= 0); + in_addr_prefix_covers_full_one(prefix, address, i <= j); + } + } + + for (unsigned i = 0; i <= 32; i++) { + _cleanup_free_ char *prefix = NULL; + + assert_se(asprintf(&prefix, "192.168.235.129/%u", i) >= 0); + in_addr_prefix_covers_full_one(prefix, "192.168.0.128/32", i <= 16); + } + + for (unsigned i = 0; i <= 128; i++) { + _cleanup_free_ char *prefix = NULL; + + assert_se(asprintf(&prefix, "dead:beef::/%u", i) >= 0); + in_addr_prefix_covers_full_one(prefix, "dead:0:beef::1/128", i <= 16); } } diff --git a/src/test/test-install-root.c b/src/test/test-install-root.c index efd75b2..1e7ed27 100644 --- a/src/test/test-install-root.c +++ b/src/test/test-install-root.c @@ -60,9 +60,9 @@ TEST(basic_mask_and_enable) { assert_se(unit_file_mask(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("a.service"), &changes, &n_changes) >= 0); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/dev/null")); + ASSERT_STREQ(changes[0].source, "/dev/null"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/a.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -81,16 +81,16 @@ TEST(basic_mask_and_enable) { assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_UNLINK); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/a.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; assert_se(unit_file_enable(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("a.service"), &changes, &n_changes) == 1); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/a.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/a.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/a.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -109,7 +109,7 @@ TEST(basic_mask_and_enable) { assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_UNLINK); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/a.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -128,9 +128,9 @@ TEST(basic_mask_and_enable) { assert_se(unit_file_enable(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("d.service"), &changes, &n_changes) >= 0); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/a.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/a.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/a.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -145,10 +145,10 @@ TEST(basic_mask_and_enable) { assert_se(n_changes == 2); assert_se(changes[0].type == INSTALL_CHANGE_UNLINK); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/a.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); assert_se(changes[1].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[1].source, "/usr/lib/systemd/system/a.service")); - assert_se(streq(changes[1].path, p)); + ASSERT_STREQ(changes[1].source, "/usr/lib/systemd/system/a.service"); + ASSERT_STREQ(changes[1].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -186,13 +186,13 @@ TEST(basic_mask_and_enable) { assert_se(unit_file_enable(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("f.service"), &changes, &n_changes) == 1); assert_se(n_changes == 2); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/f.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/f.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/x.target.wants/f.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); assert_se(changes[1].type == INSTALL_CHANGE_DESTINATION_NOT_PRESENT); p = strjoina(root, "/usr/lib/systemd/system/f.service"); - assert_se(streq(changes[1].source, p)); - assert_se(streq(changes[1].path, "x.target")); + ASSERT_STREQ(changes[1].source, p); + ASSERT_STREQ(changes[1].path, "x.target"); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -200,7 +200,7 @@ TEST(basic_mask_and_enable) { } TEST(linked_units) { - const char *p, *q; + const char *p, *q, *s; UnitFileState state; InstallChange *changes = NULL; size_t n_changes = 0, i; @@ -224,6 +224,7 @@ TEST(linked_units) { p = strjoina(root, "/opt/linked.service"); assert_se(write_string_file(p, "[Install]\n" + "Alias=linked-alias.service\n" "WantedBy=multi-user.target\n", WRITE_STRING_FILE_CREATE) >= 0); p = strjoina(root, "/opt/linked2.service"); @@ -254,9 +255,9 @@ TEST(linked_units) { assert_se(unit_file_link(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("/opt/linked.service"), &changes, &n_changes) >= 0); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/opt/linked.service")); + ASSERT_STREQ(changes[0].source, "/opt/linked.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/linked.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -267,7 +268,7 @@ TEST(linked_units) { assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_UNLINK); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/linked.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -275,31 +276,41 @@ TEST(linked_units) { /* Now, let's not just link it, but also enable it */ assert_se(unit_file_enable(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("/opt/linked.service"), &changes, &n_changes) >= 0); - assert_se(n_changes == 2); + assert_se(n_changes == 3); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/linked.service"); q = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/linked.service"); + s = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/linked-alias.service"); for (i = 0 ; i < n_changes; i++) { assert_se(changes[i].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[i].source, "/opt/linked.service")); + + if (s && streq(changes[i].path, s)) + /* The alias symlink should point within the search path. */ + ASSERT_STREQ(changes[i].source, SYSTEM_CONFIG_UNIT_DIR"/linked.service"); + else + ASSERT_STREQ(changes[i].source, "/opt/linked.service"); if (p && streq(changes[i].path, p)) p = NULL; else if (q && streq(changes[i].path, q)) q = NULL; + else if (s && streq(changes[i].path, s)) + s = NULL; else assert_not_reached(); } - assert_se(!p && !q); + assert_se(!p && !q && !s); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; assert_se(unit_file_get_state(RUNTIME_SCOPE_SYSTEM, root, "linked.service", &state) >= 0 && state == UNIT_FILE_ENABLED); + assert_se(unit_file_get_state(RUNTIME_SCOPE_SYSTEM, root, "linked-alias.service", &state) >= 0 && state == UNIT_FILE_ALIAS); /* And let's unlink it again */ assert_se(unit_file_disable(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("linked.service"), &changes, &n_changes) >= 0); - assert_se(n_changes == 2); + assert_se(n_changes == 3); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/linked.service"); q = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/linked.service"); + s = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/linked-alias.service"); for (i = 0; i < n_changes; i++) { assert_se(changes[i].type == INSTALL_CHANGE_UNLINK); @@ -307,10 +318,12 @@ TEST(linked_units) { p = NULL; else if (q && streq(changes[i].path, q)) q = NULL; + else if (s && streq(changes[i].path, s)) + s = NULL; else assert_not_reached(); } - assert_se(!p && !q); + assert_se(!p && !q && !s); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -322,7 +335,7 @@ TEST(linked_units) { q = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/linked2.service"); for (i = 0 ; i < n_changes; i++) { assert_se(changes[i].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[i].source, "/opt/linked2.service")); + ASSERT_STREQ(changes[i].source, "/opt/linked2.service"); if (p && streq(changes[i].path, p)) p = NULL; @@ -340,7 +353,7 @@ TEST(linked_units) { assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); assert_se(startswith(changes[0].path, root)); assert_se(endswith(changes[0].path, "linked3.service")); - assert_se(streq(changes[0].source, "/opt/linked3.service")); + ASSERT_STREQ(changes[0].source, "/opt/linked3.service"); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; } @@ -362,7 +375,7 @@ TEST(default) { assert_se(unit_file_set_default(RUNTIME_SCOPE_SYSTEM, 0, root, "idontexist.target", &changes, &n_changes) == -ENOENT); assert_se(n_changes == 1); assert_se(changes[0].type == -ENOENT); - assert_se(streq_ptr(changes[0].path, "idontexist.target")); + ASSERT_STREQ(changes[0].path, "idontexist.target"); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -371,14 +384,14 @@ TEST(default) { assert_se(unit_file_set_default(RUNTIME_SCOPE_SYSTEM, 0, root, "test-default.target", &changes, &n_changes) >= 0); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/test-default-real.target")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/test-default-real.target"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR "/" SPECIAL_DEFAULT_TARGET); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; assert_se(unit_file_get_default(RUNTIME_SCOPE_SYSTEM, root, &def) >= 0); - assert_se(streq_ptr(def, "test-default-real.target")); + ASSERT_STREQ(def, "test-default-real.target"); } TEST(add_dependency) { @@ -401,9 +414,9 @@ TEST(add_dependency) { assert_se(unit_file_add_dependency(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("add-dependency-test-service.service"), "add-dependency-test-target.target", UNIT_WANTS, &changes, &n_changes) >= 0); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/real-add-dependency-test-service.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/real-add-dependency-test-service.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/real-add-dependency-test-target.target.wants/real-add-dependency-test-service.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; } @@ -442,9 +455,9 @@ TEST(template_enable) { assert_se(unit_file_enable(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("template@.service"), &changes, &n_changes) >= 0); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/template@.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/template@.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/template@def.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -458,7 +471,7 @@ TEST(template_enable) { assert_se(unit_file_disable(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("template@.service"), &changes, &n_changes) >= 0); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_UNLINK); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -473,9 +486,9 @@ TEST(template_enable) { assert_se(unit_file_enable(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("template@foo.service"), &changes, &n_changes) >= 0); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/template@.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/template@.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/template@foo.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -489,7 +502,7 @@ TEST(template_enable) { assert_se(unit_file_disable(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("template@foo.service"), &changes, &n_changes) >= 0); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_UNLINK); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -506,9 +519,9 @@ TEST(template_enable) { assert_se(unit_file_enable(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("template-symlink@quux.service"), &changes, &n_changes) >= 0); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/template@.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/template@.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/template@quux.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -552,9 +565,9 @@ TEST(indirect) { assert_se(unit_file_enable(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("indirectc.service"), &changes, &n_changes) >= 0); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/indirectb.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/indirectb.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/indirectb.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -566,7 +579,7 @@ TEST(indirect) { assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_UNLINK); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/indirectb.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; } @@ -614,9 +627,9 @@ TEST(preset_and_list) { assert_se(unit_file_preset(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("preset-yes.service"), UNIT_FILE_PRESET_FULL, &changes, &n_changes) >= 0); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/preset-yes.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/preset-yes.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/preset-yes.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -628,7 +641,7 @@ TEST(preset_and_list) { assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_UNLINK); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/preset-yes.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -654,8 +667,8 @@ TEST(preset_and_list) { for (i = 0; i < n_changes; i++) { if (changes[i].type == INSTALL_CHANGE_SYMLINK) { - assert_se(streq(changes[i].source, "/usr/lib/systemd/system/preset-yes.service")); - assert_se(streq(changes[i].path, p)); + ASSERT_STREQ(changes[i].source, "/usr/lib/systemd/system/preset-yes.service"); + ASSERT_STREQ(changes[i].path, p); } else assert_se(changes[i].type == INSTALL_CHANGE_UNLINK); } @@ -722,7 +735,7 @@ TEST(revert) { assert_se(unit_file_revert(RUNTIME_SCOPE_SYSTEM, root, STRV_MAKE("xx.service"), &changes, &n_changes) >= 0); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_UNLINK); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -733,11 +746,11 @@ TEST(revert) { assert_se(unit_file_revert(RUNTIME_SCOPE_SYSTEM, root, STRV_MAKE("xx.service"), &changes, &n_changes) >= 0); assert_se(n_changes == 2); assert_se(changes[0].type == INSTALL_CHANGE_UNLINK); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/xx.service.d"); assert_se(changes[1].type == INSTALL_CHANGE_UNLINK); - assert_se(streq(changes[1].path, p)); + ASSERT_STREQ(changes[1].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; } @@ -773,9 +786,9 @@ TEST(preset_order) { assert_se(unit_file_preset(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("prefix-1.service"), UNIT_FILE_PRESET_FULL, &changes, &n_changes) >= 0); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/prefix-1.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/prefix-1.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/prefix-1.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -882,12 +895,12 @@ TEST(with_dropin) { assert_se(n_changes == 2); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); assert_se(changes[1].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/with-dropin-1.service")); - assert_se(streq(changes[1].source, "/usr/lib/systemd/system/with-dropin-1.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/with-dropin-1.service"); + ASSERT_STREQ(changes[1].source, "/usr/lib/systemd/system/with-dropin-1.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/with-dropin-1.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/graphical.target.wants/with-dropin-1.service"); - assert_se(streq(changes[1].path, p)); + ASSERT_STREQ(changes[1].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -896,12 +909,12 @@ TEST(with_dropin) { assert_se(n_changes == 2); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); assert_se(changes[1].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, SYSTEM_CONFIG_UNIT_DIR"/with-dropin-2.service")); - assert_se(streq(changes[1].source, SYSTEM_CONFIG_UNIT_DIR"/with-dropin-2.service")); + ASSERT_STREQ(changes[0].source, SYSTEM_CONFIG_UNIT_DIR"/with-dropin-2.service"); + ASSERT_STREQ(changes[1].source, SYSTEM_CONFIG_UNIT_DIR"/with-dropin-2.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/with-dropin-2.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/graphical.target.wants/with-dropin-2.service"); - assert_se(streq(changes[1].path, p)); + ASSERT_STREQ(changes[1].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -910,12 +923,12 @@ TEST(with_dropin) { assert_se(n_changes == 2); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); assert_se(changes[1].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/with-dropin-3.service")); - assert_se(streq(changes[1].source, "/usr/lib/systemd/system/with-dropin-3.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/with-dropin-3.service"); + ASSERT_STREQ(changes[1].source, "/usr/lib/systemd/system/with-dropin-3.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/with-dropin-3.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/graphical.target.wants/with-dropin-3.service"); - assert_se(streq(changes[1].path, p)); + ASSERT_STREQ(changes[1].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -924,12 +937,12 @@ TEST(with_dropin) { assert_se(n_changes == 2); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); assert_se(changes[1].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/with-dropin-4a.service")); - assert_se(streq(changes[1].source, "/usr/lib/systemd/system/with-dropin-4b.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/with-dropin-4a.service"); + ASSERT_STREQ(changes[1].source, "/usr/lib/systemd/system/with-dropin-4b.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/with-dropin-4a.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/with-dropin-4b.service"); - assert_se(streq(changes[1].path, p)); + ASSERT_STREQ(changes[1].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -991,12 +1004,12 @@ TEST(with_dropin_template) { assert_se(n_changes == 2); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); assert_se(changes[1].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/with-dropin-1@.service")); - assert_se(streq(changes[1].source, "/usr/lib/systemd/system/with-dropin-1@.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/with-dropin-1@.service"); + ASSERT_STREQ(changes[1].source, "/usr/lib/systemd/system/with-dropin-1@.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/with-dropin-1@instance-1.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/graphical.target.wants/with-dropin-1@instance-1.service"); - assert_se(streq(changes[1].path, p)); + ASSERT_STREQ(changes[1].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -1004,30 +1017,30 @@ TEST(with_dropin_template) { assert_se(n_changes == 2); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); assert_se(changes[1].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/with-dropin-2@.service")); - assert_se(streq(changes[1].source, "/usr/lib/systemd/system/with-dropin-2@.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/with-dropin-2@.service"); + ASSERT_STREQ(changes[1].source, "/usr/lib/systemd/system/with-dropin-2@.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/with-dropin-2@instance-1.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/graphical.target.wants/with-dropin-2@instance-1.service"); - assert_se(streq(changes[1].path, p)); + ASSERT_STREQ(changes[1].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; assert_se(unit_file_enable(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("with-dropin-2@instance-2.service"), &changes, &n_changes) == 1); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/with-dropin-2@.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/with-dropin-2@.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/with-dropin-2@instance-2.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; assert_se(unit_file_enable(RUNTIME_SCOPE_SYSTEM, 0, root, STRV_MAKE("with-dropin-3@.service"), &changes, &n_changes) == 1); assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); - assert_se(streq(changes[0].source, "/usr/lib/systemd/system/with-dropin-3@.service")); + ASSERT_STREQ(changes[0].source, "/usr/lib/systemd/system/with-dropin-3@.service"); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/with-dropin-3@instance-2.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -1067,7 +1080,7 @@ TEST(preset_multiple_instances) { assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_SYMLINK); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/foo@bar0.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -1075,7 +1088,7 @@ TEST(preset_multiple_instances) { assert_se(n_changes == 1); assert_se(changes[0].type == INSTALL_CHANGE_UNLINK); p = strjoina(root, SYSTEM_CONFIG_UNIT_DIR"/multi-user.target.wants/foo@bar0.service"); - assert_se(streq(changes[0].path, p)); + ASSERT_STREQ(changes[0].path, p); install_changes_free(changes, n_changes); changes = NULL; n_changes = 0; @@ -1118,7 +1131,7 @@ static void verify_one( * RequiredBy= settings, and less so for Alias=. The only case where it should happen is when we have * an Alias=alias@.service an instantiated template template@instance. In that case the instance name * should be propagated into the alias as alias@instance. */ - assert_se(streq_ptr(alias2, updated_name)); + ASSERT_STREQ(alias2, updated_name); } TEST(verify_alias) { diff --git a/src/test/test-iovec-util.c b/src/test/test-iovec-util.c new file mode 100644 index 0000000..e7cc6e4 --- /dev/null +++ b/src/test/test-iovec-util.c @@ -0,0 +1,57 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include "iovec-util.h" +#include "tests.h" + +TEST(iovec_memcmp) { + struct iovec iov1 = CONST_IOVEC_MAKE_STRING("abcdef"), iov2 = IOVEC_MAKE_STRING("bcdefg"), empty = {}; + + struct iovec iov1_truncated = iov1; + iov1_truncated.iov_len /= 2; + + assert_se(iovec_memcmp(NULL, NULL) == 0); + assert_se(iovec_memcmp(&iov1, &iov1) == 0); + assert_se(iovec_memcmp(&iov2, &iov2) == 0); + assert_se(iovec_memcmp(&empty, &empty) == 0); + assert_se(iovec_memcmp(&iov1_truncated, &iov1_truncated) == 0); + assert_se(iovec_memcmp(&empty, NULL) == 0); + assert_se(iovec_memcmp(NULL, &empty) == 0); + assert_se(iovec_memcmp(&iov1, &iov2) < 0); + assert_se(iovec_memcmp(&iov2, &iov1) > 0); + assert_se(iovec_memcmp(&iov1, &empty) > 0); + assert_se(iovec_memcmp(&empty, &iov1) < 0); + assert_se(iovec_memcmp(&iov2, &empty) > 0); + assert_se(iovec_memcmp(&empty, &iov2) < 0); + assert_se(iovec_memcmp(&iov1_truncated, &empty) > 0); + assert_se(iovec_memcmp(&empty, &iov1_truncated) < 0); + assert_se(iovec_memcmp(&iov1, &iov1_truncated) > 0); + assert_se(iovec_memcmp(&iov1_truncated, &iov1) < 0); + assert_se(iovec_memcmp(&iov2, &iov1_truncated) > 0); + assert_se(iovec_memcmp(&iov1_truncated, &iov2) < 0); + + _cleanup_(iovec_done) struct iovec copy = {}; + + assert_se(iovec_memdup(&iov1, ©)); + assert_se(iovec_memcmp(&iov1, ©) == 0); +} + +TEST(iovec_set_and_valid) { + struct iovec empty = {}, + filled = CONST_IOVEC_MAKE_STRING("waldo"), + half = { .iov_base = (char*) "piff", .iov_len = 0 }, + invalid = { .iov_base = NULL, .iov_len = 47 }; + + assert_se(!iovec_is_set(NULL)); + assert_se(!iovec_is_set(&empty)); + assert_se(iovec_is_set(&filled)); + assert_se(!iovec_is_set(&half)); + assert_se(!iovec_is_set(&invalid)); + + assert_se(iovec_is_valid(NULL)); + assert_se(iovec_is_valid(&empty)); + assert_se(iovec_is_valid(&filled)); + assert_se(iovec_is_valid(&half)); + assert_se(!iovec_is_valid(&invalid)); +} + +DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-ip-protocol-list.c b/src/test/test-ip-protocol-list.c index dfff015..9d0403c 100644 --- a/src/test/test-ip-protocol-list.c +++ b/src/test/test-ip-protocol-list.c @@ -27,8 +27,8 @@ static void test_int_fail(int i, int error) { } static void test_str(const char *s) { - assert_se(streq(ip_protocol_to_name(ip_protocol_from_name(s)), s)); - assert_se(streq(ip_protocol_to_name(parse_ip_protocol(s)), s)); + ASSERT_STREQ(ip_protocol_to_name(ip_protocol_from_name(s)), s); + ASSERT_STREQ(ip_protocol_to_name(parse_ip_protocol(s)), s); } static void test_str_fail(const char *s, int error) { diff --git a/src/test/test-json.c b/src/test/test-json.c index c120a70..7d9a785 100644 --- a/src/test/test-json.c +++ b/src/test/test-json.c @@ -6,9 +6,11 @@ #include "escape.h" #include "fd-util.h" #include "fileio.h" +#include "iovec-util.h" #include "json-internal.h" #include "json.h" #include "math-util.h" +#include "string-table.h" #include "string-util.h" #include "strv.h" #include "tests.h" @@ -42,7 +44,7 @@ static void test_tokenizer_one(const char *data, ...) { const char *nn; nn = va_arg(ap, const char *); - assert_se(streq_ptr(nn, str)); + ASSERT_STREQ(nn, str); } else if (t == JSON_TOKEN_REAL) { double d; @@ -105,6 +107,17 @@ static void test_variant_one(const char *data, Test test) { assert_se(json_variant_equal(v, w)); s = mfree(s); + r = json_variant_format(w, JSON_FORMAT_CENSOR_SENSITIVE, &s); + assert_se(s); + ASSERT_STREQ(s, "\"<sensitive data>\""); + + s = mfree(s); + r = json_variant_format(w, JSON_FORMAT_PRETTY, &s); + assert_se(r >= 0); + assert_se(s); + assert_se((size_t) r == strlen(s)); + + s = mfree(s); w = json_variant_unref(w); r = json_variant_format(v, JSON_FORMAT_PRETTY, &s); @@ -154,7 +167,7 @@ static void test_1(JsonVariant *v) { assert_se(p && json_variant_type(p) == JSON_VARIANT_STRING); /* k equals v */ - assert_se(streq(json_variant_string(p), "v")); + ASSERT_STREQ(json_variant_string(p), "v"); /* has foo */ p = json_variant_by_key(v, "foo"); @@ -321,7 +334,7 @@ TEST(build) { assert_se(json_variant_format(b, 0, &t) >= 0); log_info("GOT: %s", t); - assert_se(streq(s, t)); + ASSERT_STREQ(s, t); a = json_variant_unref(a); b = json_variant_unref(b); @@ -349,7 +362,7 @@ TEST(json_parse_file_empty) { assert_se(fopen_unlocked("/dev/null", "re", &f) >= 0); assert_se(json_parse_file(f, "waldo", 0, &v, NULL, NULL) == -ENODATA); - assert_se(v == NULL); + ASSERT_NULL(v); } TEST(json_parse_file_invalid) { @@ -358,7 +371,7 @@ TEST(json_parse_file_invalid) { assert_se(f = fmemopen_unlocked((void*) "kookoo", 6, "r")); assert_se(json_parse_file(f, "waldo", 0, &v, NULL, NULL) == -EINVAL); - assert_se(v == NULL); + ASSERT_NULL(v); } TEST(source) { @@ -449,7 +462,7 @@ TEST(normalize) { assert_se(!json_variant_is_normalized(v)); assert_se(json_variant_format(v, 0, &t) >= 0); - assert_se(streq(t, "{\"b\":\"x\",\"c\":\"y\",\"a\":\"z\"}")); + ASSERT_STREQ(t, "{\"b\":\"x\",\"c\":\"y\",\"a\":\"z\"}"); t = mfree(t); assert_se(json_build(&w, JSON_BUILD_OBJECT( @@ -460,7 +473,7 @@ TEST(normalize) { assert_se(!json_variant_is_normalized(w)); assert_se(json_variant_format(w, 0, &t) >= 0); - assert_se(streq(t, "{\"bar\":\"zzz\",\"foo\":{\"b\":\"x\",\"c\":\"y\",\"a\":\"z\"}}")); + ASSERT_STREQ(t, "{\"bar\":\"zzz\",\"foo\":{\"b\":\"x\",\"c\":\"y\",\"a\":\"z\"}}"); t = mfree(t); assert_se(json_variant_sort(&v) >= 0); @@ -468,7 +481,7 @@ TEST(normalize) { assert_se(json_variant_is_normalized(v)); assert_se(json_variant_format(v, 0, &t) >= 0); - assert_se(streq(t, "{\"a\":\"z\",\"b\":\"x\",\"c\":\"y\"}")); + ASSERT_STREQ(t, "{\"a\":\"z\",\"b\":\"x\",\"c\":\"y\"}"); t = mfree(t); assert_se(json_variant_normalize(&w) >= 0); @@ -476,7 +489,7 @@ TEST(normalize) { assert_se(json_variant_is_normalized(w)); assert_se(json_variant_format(w, 0, &t) >= 0); - assert_se(streq(t, "{\"bar\":\"zzz\",\"foo\":{\"a\":\"z\",\"b\":\"x\",\"c\":\"y\"}}")); + ASSERT_STREQ(t, "{\"bar\":\"zzz\",\"foo\":{\"a\":\"z\",\"b\":\"x\",\"c\":\"y\"}}"); t = mfree(t); } @@ -518,7 +531,7 @@ TEST(bisect) { assert_se(json_variant_is_string(k)); z = (char[5]){ '<', c, c, '>', 0}; - assert_se(streq(json_variant_string(k), z)); + ASSERT_STREQ(json_variant_string(k), z); } } @@ -685,8 +698,8 @@ static void json_array_append_with_source_one(bool source) { assert_se(json_variant_get_source(a, &s1, &line1, &col1) >= 0); assert_se(json_variant_get_source(b, &s2, &line2, &col2) >= 0); - assert_se(streq_ptr(s1, source ? "string 1" : NULL)); - assert_se(streq_ptr(s2, source ? "string 2" : NULL)); + ASSERT_STREQ(s1, source ? "string 1" : NULL); + ASSERT_STREQ(s2, source ? "string 2" : NULL); assert_se(line1 == 1); assert_se(col1 == 2); assert_se(line2 == 3); @@ -710,8 +723,8 @@ static void json_array_append_with_source_one(bool source) { assert_se(elem = json_variant_by_index(a, 1)); assert_se(json_variant_get_source(elem, &s2, &line2, &col2) >= 0); - assert_se(streq_ptr(s1, source ? "string 2" : NULL)); - assert_se(streq_ptr(s2, source ? "string 2" : NULL)); + ASSERT_STREQ(s1, source ? "string 2" : NULL); + ASSERT_STREQ(s2, source ? "string 2" : NULL); assert_se(line1 == 3); assert_se(col1 == 5); assert_se(line2 == 3); @@ -813,4 +826,172 @@ TEST(json_dispatch) { assert_se(foobar.l == INT16_MIN); } +typedef enum mytestenum { + myfoo, mybar, mybaz, _mymax, _myinvalid = -EINVAL, +} mytestenum; + +static const char *mytestenum_table[_mymax] = { + [myfoo] = "myfoo", + [mybar] = "mybar", + [mybaz] = "mybaz", +}; + +DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(mytestenum, mytestenum); + +static JSON_DISPATCH_ENUM_DEFINE(dispatch_mytestenum, mytestenum, mytestenum_from_string); + +TEST(json_dispatch_enum_define) { + + struct data { + mytestenum a, b, c, d; + } data = { + .a = _myinvalid, + .b = _myinvalid, + .c = _myinvalid, + .d = mybar, + }; + + _cleanup_(json_variant_unrefp) JsonVariant *j = NULL; + + assert_se(json_build(&j, JSON_BUILD_OBJECT( + JSON_BUILD_PAIR("a", JSON_BUILD_STRING("mybaz")), + JSON_BUILD_PAIR("b", JSON_BUILD_STRING("mybar")), + JSON_BUILD_PAIR("c", JSON_BUILD_STRING("myfoo")), + JSON_BUILD_PAIR("d", JSON_BUILD_NULL))) >= 0); + + assert_se(json_dispatch(j, + (const JsonDispatch[]) { + { "a", _JSON_VARIANT_TYPE_INVALID, dispatch_mytestenum, offsetof(struct data, a), 0 }, + { "b", _JSON_VARIANT_TYPE_INVALID, dispatch_mytestenum, offsetof(struct data, b), 0 }, + { "c", _JSON_VARIANT_TYPE_INVALID, dispatch_mytestenum, offsetof(struct data, c), 0 }, + { "d", _JSON_VARIANT_TYPE_INVALID, dispatch_mytestenum, offsetof(struct data, d), 0 }, + {}, + }, + /* flags= */ 0, + &data) >= 0); + + assert(data.a == mybaz); + assert(data.b == mybar); + assert(data.c == myfoo); + assert(data.d < 0); +} + +TEST(json_sensitive) { + _cleanup_(json_variant_unrefp) JsonVariant *a = NULL, *b = NULL, *v = NULL; + _cleanup_free_ char *s = NULL; + int r; + + assert_se(json_build(&a, JSON_BUILD_STRV(STRV_MAKE("foo", "bar", "baz", "bar", "baz", "foo", "qux", "baz"))) >= 0); + assert_se(json_build(&b, JSON_BUILD_STRV(STRV_MAKE("foo", "bar", "baz", "qux"))) >= 0); + + json_variant_sensitive(a); + + assert_se(json_variant_format(a, JSON_FORMAT_CENSOR_SENSITIVE, &s) >= 0); + ASSERT_STREQ(s, "\"<sensitive data>\""); + s = mfree(s); + + r = json_variant_format(b, JSON_FORMAT_CENSOR_SENSITIVE, &s); + assert_se(r >= 0); + assert_se(s); + assert_se((size_t) r == strlen(s)); + s = mfree(s); + + assert_se(json_build(&v, JSON_BUILD_OBJECT( + JSON_BUILD_PAIR("c", JSON_BUILD_INTEGER(INT64_MIN)), + JSON_BUILD_PAIR("d", JSON_BUILD_STRING("-9223372036854775808")), + JSON_BUILD_PAIR("e", JSON_BUILD_EMPTY_OBJECT))) >= 0); + json_variant_dump(v, JSON_FORMAT_COLOR|JSON_FORMAT_PRETTY, NULL, NULL); + + r = json_variant_format(v, JSON_FORMAT_CENSOR_SENSITIVE, &s); + assert_se(r >= 0); + assert_se(s); + assert_se((size_t) r == strlen(s)); + s = mfree(s); + v = json_variant_unref(v); + + assert_se(json_build(&v, JSON_BUILD_OBJECT( + JSON_BUILD_PAIR_VARIANT("b", b), + JSON_BUILD_PAIR("c", JSON_BUILD_INTEGER(INT64_MIN)), + JSON_BUILD_PAIR("d", JSON_BUILD_STRING("-9223372036854775808")), + JSON_BUILD_PAIR("e", JSON_BUILD_EMPTY_OBJECT))) >= 0); + json_variant_dump(v, JSON_FORMAT_COLOR|JSON_FORMAT_PRETTY, NULL, NULL); + + r = json_variant_format(v, JSON_FORMAT_CENSOR_SENSITIVE, &s); + assert_se(r >= 0); + assert_se(s); + assert_se((size_t) r == strlen(s)); + s = mfree(s); + v = json_variant_unref(v); + + assert_se(json_build(&v, JSON_BUILD_OBJECT( + JSON_BUILD_PAIR_VARIANT("b", b), + JSON_BUILD_PAIR_VARIANT("a", a), + JSON_BUILD_PAIR("c", JSON_BUILD_INTEGER(INT64_MIN)), + JSON_BUILD_PAIR("d", JSON_BUILD_STRING("-9223372036854775808")), + JSON_BUILD_PAIR("e", JSON_BUILD_EMPTY_OBJECT))) >= 0); + json_variant_dump(v, JSON_FORMAT_COLOR|JSON_FORMAT_PRETTY, NULL, NULL); + + assert_se(json_variant_format(v, JSON_FORMAT_CENSOR_SENSITIVE, &s) >= 0); + ASSERT_STREQ(s, "{\"b\":[\"foo\",\"bar\",\"baz\",\"qux\"],\"a\":\"<sensitive data>\",\"c\":-9223372036854775808,\"d\":\"-9223372036854775808\",\"e\":{}}"); + s = mfree(s); + v = json_variant_unref(v); + + assert_se(json_build(&v, JSON_BUILD_OBJECT( + JSON_BUILD_PAIR_VARIANT("b", b), + JSON_BUILD_PAIR("c", JSON_BUILD_INTEGER(INT64_MIN)), + JSON_BUILD_PAIR_VARIANT("a", a), + JSON_BUILD_PAIR("d", JSON_BUILD_STRING("-9223372036854775808")), + JSON_BUILD_PAIR("e", JSON_BUILD_EMPTY_OBJECT))) >= 0); + json_variant_dump(v, JSON_FORMAT_COLOR|JSON_FORMAT_PRETTY, NULL, NULL); + + assert_se(json_variant_format(v, JSON_FORMAT_CENSOR_SENSITIVE, &s) >= 0); + ASSERT_STREQ(s, "{\"b\":[\"foo\",\"bar\",\"baz\",\"qux\"],\"c\":-9223372036854775808,\"a\":\"<sensitive data>\",\"d\":\"-9223372036854775808\",\"e\":{}}"); + s = mfree(s); + v = json_variant_unref(v); + + assert_se(json_build(&v, JSON_BUILD_OBJECT( + JSON_BUILD_PAIR_VARIANT("b", b), + JSON_BUILD_PAIR("c", JSON_BUILD_INTEGER(INT64_MIN)), + JSON_BUILD_PAIR("d", JSON_BUILD_STRING("-9223372036854775808")), + JSON_BUILD_PAIR_VARIANT("a", a), + JSON_BUILD_PAIR("e", JSON_BUILD_EMPTY_OBJECT))) >= 0); + json_variant_dump(v, JSON_FORMAT_COLOR|JSON_FORMAT_PRETTY, NULL, NULL); + + assert_se(json_variant_format(v, JSON_FORMAT_CENSOR_SENSITIVE, &s) >= 0); + ASSERT_STREQ(s, "{\"b\":[\"foo\",\"bar\",\"baz\",\"qux\"],\"c\":-9223372036854775808,\"d\":\"-9223372036854775808\",\"a\":\"<sensitive data>\",\"e\":{}}"); + s = mfree(s); + v = json_variant_unref(v); + + assert_se(json_build(&v, JSON_BUILD_OBJECT( + JSON_BUILD_PAIR_VARIANT("b", b), + JSON_BUILD_PAIR("c", JSON_BUILD_INTEGER(INT64_MIN)), + JSON_BUILD_PAIR("d", JSON_BUILD_STRING("-9223372036854775808")), + JSON_BUILD_PAIR("e", JSON_BUILD_EMPTY_OBJECT), + JSON_BUILD_PAIR_VARIANT("a", a))) >= 0); + json_variant_dump(v, JSON_FORMAT_COLOR|JSON_FORMAT_PRETTY, NULL, NULL); + + assert_se(json_variant_format(v, JSON_FORMAT_CENSOR_SENSITIVE, &s) >= 0); + ASSERT_STREQ(s, "{\"b\":[\"foo\",\"bar\",\"baz\",\"qux\"],\"c\":-9223372036854775808,\"d\":\"-9223372036854775808\",\"e\":{},\"a\":\"<sensitive data>\"}"); +} + +TEST(json_iovec) { + struct iovec iov1 = CONST_IOVEC_MAKE_STRING("üxknürz"), iov2 = CONST_IOVEC_MAKE_STRING("wuffwuffmiau"); + + _cleanup_(json_variant_unrefp) JsonVariant *j = NULL; + assert_se(json_build(&j, JSON_BUILD_OBJECT( + JSON_BUILD_PAIR("nr1", JSON_BUILD_IOVEC_BASE64(&iov1)), + JSON_BUILD_PAIR("nr2", JSON_BUILD_IOVEC_HEX(&iov2)))) >= 0); + + json_variant_dump(j, JSON_FORMAT_PRETTY_AUTO|JSON_FORMAT_COLOR_AUTO, /* f= */ NULL, /* prefix= */ NULL); + + _cleanup_(iovec_done) struct iovec a = {}, b = {}; + assert_se(json_variant_unbase64_iovec(json_variant_by_key(j, "nr1"), &a) >= 0); + assert_se(json_variant_unhex_iovec(json_variant_by_key(j, "nr2"), &b) >= 0); + + assert_se(iovec_memcmp(&iov1, &a) == 0); + assert_se(iovec_memcmp(&iov2, &b) == 0); + assert_se(iovec_memcmp(&iov2, &a) < 0); + assert_se(iovec_memcmp(&iov1, &b) > 0); +} + DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-label.c b/src/test/test-label.c new file mode 100644 index 0000000..9d7ac18 --- /dev/null +++ b/src/test/test-label.c @@ -0,0 +1,156 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include <errno.h> +#include <stddef.h> +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> + +#include "errno-util.h" +#include "fd-util.h" +#include "fs-util.h" +#include "label.h" +#include "path-util.h" +#include "string-util.h" +#include "tests.h" + +static struct stat buf; +static int check_path(int dir_fd, const char *path) { + assert(path); + assert(dir_fd >= 0 || dir_fd == AT_FDCWD); + + if (isempty(path)) + return -EINVAL; + + /* assume length of pathname is not greater than 40*/ + if (strlen(path) > 40) + return -ENAMETOOLONG; + + /* assume a case where a specific label isn't allowed */ + if (path_equal(path, "/restricted_directory")) + return -EACCES; + return 0; +} + +static int pre_labelling_func(int dir_fd, const char *path, mode_t mode) { + int r; + + assert(mode != MODE_INVALID); + r = check_path(dir_fd, path); + if (r < 0) + return log_error_errno(r, "Error in pathname =>: %m"); + + return 0; +} + +static int post_labelling_func(int dir_fd, const char *path) { + int r; + + /* assume label policies that restrict certain labels */ + r = check_path(dir_fd, path); + if (r < 0) + return log_error_errno(r, "Error in pathname =>: %m"); + + /* Set file data to buf */ + r = RET_NERRNO(fstatat(dir_fd, path, &buf, 0)); + if (r < 0) + return log_error_errno(r, "Error in getting file status =>: %m"); + + return 0; /* on success */ +} + +static int get_dir_fd(const char *dir_path, mode_t mode) { + /* create a new directory and return its descriptor*/ + int dir_fd = -EBADF; + + assert(dir_path); + dir_fd = RET_NERRNO(open_mkdir_at(AT_FDCWD, dir_path, O_CLOEXEC, mode)); + if (dir_fd < 0) + return log_error_errno(dir_fd, "Error occurred while opening directory =>: %m"); + + return dir_fd; +} + +static int labelling_op(int dir_fd, const char *text, const char *path, mode_t mode) { + /* Write some content into the file */ + ssize_t count; + _cleanup_close_ int write_fd = -EBADF; + int r; + + assert(text); + assert(mode != MODE_INVALID); + r = check_path(dir_fd, path); + if (r < 0) + return log_error_errno(r, "Error in pathname =>: %m"); + + /* Open the file within the directory for writing*/ + write_fd = RET_NERRNO(openat(dir_fd, path, O_CLOEXEC|O_WRONLY|O_TRUNC|O_CREAT, 0644)); + if (write_fd < 0) + return log_error_errno(write_fd, "Error in opening directory for writing =>: %m"); + + /* Write data to the file*/ + count = RET_NERRNO(write(write_fd, text, strlen(text))); + if (count < 0) + return log_error_errno(count, "Error occurred while opening file for writing =>: %m"); + return 0; +} + +TEST(label_ops_set) { + static const LabelOps test_label_ops = { + .pre = NULL, + .post = NULL, + }; + + label_ops_reset(); + assert_se(label_ops_set(&test_label_ops) == 0); + /* attempt to reset label_ops when already set */ + assert_se(label_ops_set(&test_label_ops) == -EBUSY); +} + +TEST(label_ops_pre) { + _cleanup_close_ int fd; + static const LabelOps test_label_ops = { + .pre = pre_labelling_func, + .post = NULL, + }; + + label_ops_reset(); + label_ops_set(&test_label_ops); + fd = get_dir_fd("file1.txt", 0755); + assert_se(label_ops_pre(fd, "file1.txt", 0644) == 0); + assert_se(label_ops_pre(fd, "/restricted_directory", 0644) == -EACCES); + assert_se(label_ops_pre(fd, "", 0700) == -EINVAL); + assert_se(label_ops_pre(fd, "/tmp", 0700) == 0); + assert_se(label_ops_pre(fd, "wekrgoierhgoierhqgherhgwklegnlweehgorwfkryrit", 0644) == -ENAMETOOLONG); +} + +TEST(label_ops_post) { + _cleanup_close_ int fd = -EBADF; + const char *text1, *text2; + static const LabelOps test_label_ops = { + .pre = NULL, + .post = post_labelling_func, + }; + + label_ops_reset(); + label_ops_set(&test_label_ops); + + /* Open directory */ + fd = RET_NERRNO(get_dir_fd("label_test_dir", 0755)); + text1 = "Add initial texts to file for testing label operations to file1\n"; + + assert(labelling_op(fd, text1, "file1.txt", 0644) == 0); + assert_se(label_ops_post(fd, "file1.txt") == 0); + assert_se(strlen(text1) == (size_t)buf.st_size); + text2 = "Add text2 data to file2\n"; + + assert(labelling_op(fd, text2, "file2.txt", 0644) == 0); + assert_se(label_ops_post(fd, "file2.txt") == 0); + assert_se(strlen(text2) == (size_t)buf.st_size); + assert_se(label_ops_post(fd, "file3.txt") == -ENOENT); + assert_se(label_ops_post(fd, "/abcd") == -ENOENT); + assert_se(label_ops_post(fd, "/restricted_directory") == -EACCES); + assert_se(label_ops_post(fd, "") == -EINVAL); +} + +DEFINE_TEST_MAIN(LOG_INFO) diff --git a/src/test/test-list.c b/src/test/test-list.c index 87f7c7b..6c64070 100644 --- a/src/test/test-list.c +++ b/src/test/test-list.c @@ -17,8 +17,8 @@ int main(int argc, const char *argv[]) { LIST_HEAD_INIT(head); LIST_HEAD_INIT(head2); - assert_se(head == NULL); - assert_se(head2 == NULL); + ASSERT_NULL(head); + ASSERT_NULL(head2); for (i = 0; i < ELEMENTSOF(items); i++) { LIST_INIT(item_list, &items[i]); @@ -49,7 +49,7 @@ int main(int argc, const char *argv[]) { assert_se(!LIST_JUST_US(item_list, head)); - assert_se(items[0].item_list_next == NULL); + ASSERT_NULL(items[0].item_list_next); assert_se(items[1].item_list_next == &items[0]); assert_se(items[2].item_list_next == &items[1]); assert_se(items[3].item_list_next == &items[2]); @@ -57,7 +57,7 @@ int main(int argc, const char *argv[]) { assert_se(items[0].item_list_prev == &items[1]); assert_se(items[1].item_list_prev == &items[2]); assert_se(items[2].item_list_prev == &items[3]); - assert_se(items[3].item_list_prev == NULL); + ASSERT_NULL(items[3].item_list_prev); list_item *cursor = LIST_FIND_HEAD(item_list, &items[0]); assert_se(cursor == &items[3]); @@ -68,16 +68,16 @@ int main(int argc, const char *argv[]) { assert_se(LIST_REMOVE(item_list, head, &items[1]) == &items[1]); assert_se(LIST_JUST_US(item_list, &items[1])); - assert_se(items[0].item_list_next == NULL); + ASSERT_NULL(items[0].item_list_next); assert_se(items[2].item_list_next == &items[0]); assert_se(items[3].item_list_next == &items[2]); assert_se(items[0].item_list_prev == &items[2]); assert_se(items[2].item_list_prev == &items[3]); - assert_se(items[3].item_list_prev == NULL); + ASSERT_NULL(items[3].item_list_prev); assert_se(LIST_INSERT_AFTER(item_list, head, &items[3], &items[1]) == &items[1]); - assert_se(items[0].item_list_next == NULL); + ASSERT_NULL(items[0].item_list_next); assert_se(items[2].item_list_next == &items[0]); assert_se(items[1].item_list_next == &items[2]); assert_se(items[3].item_list_next == &items[1]); @@ -85,21 +85,21 @@ int main(int argc, const char *argv[]) { assert_se(items[0].item_list_prev == &items[2]); assert_se(items[2].item_list_prev == &items[1]); assert_se(items[1].item_list_prev == &items[3]); - assert_se(items[3].item_list_prev == NULL); + ASSERT_NULL(items[3].item_list_prev); assert_se(LIST_REMOVE(item_list, head, &items[1]) == &items[1]); assert_se(LIST_JUST_US(item_list, &items[1])); - assert_se(items[0].item_list_next == NULL); + ASSERT_NULL(items[0].item_list_next); assert_se(items[2].item_list_next == &items[0]); assert_se(items[3].item_list_next == &items[2]); assert_se(items[0].item_list_prev == &items[2]); assert_se(items[2].item_list_prev == &items[3]); - assert_se(items[3].item_list_prev == NULL); + ASSERT_NULL(items[3].item_list_prev); assert_se(LIST_INSERT_BEFORE(item_list, head, &items[2], &items[1]) == &items[1]); - assert_se(items[0].item_list_next == NULL); + ASSERT_NULL(items[0].item_list_next); assert_se(items[2].item_list_next == &items[0]); assert_se(items[1].item_list_next == &items[2]); assert_se(items[3].item_list_next == &items[1]); @@ -107,21 +107,21 @@ int main(int argc, const char *argv[]) { assert_se(items[0].item_list_prev == &items[2]); assert_se(items[2].item_list_prev == &items[1]); assert_se(items[1].item_list_prev == &items[3]); - assert_se(items[3].item_list_prev == NULL); + ASSERT_NULL(items[3].item_list_prev); assert_se(LIST_REMOVE(item_list, head, &items[0]) == &items[0]); assert_se(LIST_JUST_US(item_list, &items[0])); - assert_se(items[2].item_list_next == NULL); + ASSERT_NULL(items[2].item_list_next); assert_se(items[1].item_list_next == &items[2]); assert_se(items[3].item_list_next == &items[1]); assert_se(items[2].item_list_prev == &items[1]); assert_se(items[1].item_list_prev == &items[3]); - assert_se(items[3].item_list_prev == NULL); + ASSERT_NULL(items[3].item_list_prev); assert_se(LIST_INSERT_BEFORE(item_list, head, &items[3], &items[0]) == &items[0]); - assert_se(items[2].item_list_next == NULL); + ASSERT_NULL(items[2].item_list_next); assert_se(items[1].item_list_next == &items[2]); assert_se(items[3].item_list_next == &items[1]); assert_se(items[0].item_list_next == &items[3]); @@ -129,22 +129,22 @@ int main(int argc, const char *argv[]) { assert_se(items[2].item_list_prev == &items[1]); assert_se(items[1].item_list_prev == &items[3]); assert_se(items[3].item_list_prev == &items[0]); - assert_se(items[0].item_list_prev == NULL); + ASSERT_NULL(items[0].item_list_prev); assert_se(head == &items[0]); assert_se(LIST_REMOVE(item_list, head, &items[0]) == &items[0]); assert_se(LIST_JUST_US(item_list, &items[0])); - assert_se(items[2].item_list_next == NULL); + ASSERT_NULL(items[2].item_list_next); assert_se(items[1].item_list_next == &items[2]); assert_se(items[3].item_list_next == &items[1]); assert_se(items[2].item_list_prev == &items[1]); assert_se(items[1].item_list_prev == &items[3]); - assert_se(items[3].item_list_prev == NULL); + ASSERT_NULL(items[3].item_list_prev); assert_se(LIST_INSERT_BEFORE(item_list, head, NULL, &items[0]) == &items[0]); - assert_se(items[0].item_list_next == NULL); + ASSERT_NULL(items[0].item_list_next); assert_se(items[2].item_list_next == &items[0]); assert_se(items[1].item_list_next == &items[2]); assert_se(items[3].item_list_next == &items[1]); @@ -152,27 +152,27 @@ int main(int argc, const char *argv[]) { assert_se(items[0].item_list_prev == &items[2]); assert_se(items[2].item_list_prev == &items[1]); assert_se(items[1].item_list_prev == &items[3]); - assert_se(items[3].item_list_prev == NULL); + ASSERT_NULL(items[3].item_list_prev); assert_se(LIST_REMOVE(item_list, head, &items[0]) == &items[0]); assert_se(LIST_JUST_US(item_list, &items[0])); - assert_se(items[2].item_list_next == NULL); + ASSERT_NULL(items[2].item_list_next); assert_se(items[1].item_list_next == &items[2]); assert_se(items[3].item_list_next == &items[1]); assert_se(items[2].item_list_prev == &items[1]); assert_se(items[1].item_list_prev == &items[3]); - assert_se(items[3].item_list_prev == NULL); + ASSERT_NULL(items[3].item_list_prev); assert_se(LIST_REMOVE(item_list, head, &items[1]) == &items[1]); assert_se(LIST_JUST_US(item_list, &items[1])); - assert_se(items[2].item_list_next == NULL); + ASSERT_NULL(items[2].item_list_next); assert_se(items[3].item_list_next == &items[2]); assert_se(items[2].item_list_prev == &items[3]); - assert_se(items[3].item_list_prev == NULL); + ASSERT_NULL(items[3].item_list_prev); assert_se(LIST_REMOVE(item_list, head, &items[2]) == &items[2]); assert_se(LIST_JUST_US(item_list, &items[2])); @@ -181,7 +181,7 @@ int main(int argc, const char *argv[]) { assert_se(LIST_REMOVE(item_list, head, &items[3]) == &items[3]); assert_se(LIST_JUST_US(item_list, &items[3])); - assert_se(head == NULL); + ASSERT_NULL(head); for (i = 0; i < ELEMENTSOF(items); i++) { assert_se(LIST_JUST_US(item_list, &items[i])); @@ -193,9 +193,9 @@ int main(int argc, const char *argv[]) { assert_se(items[0].item_list_next == &items[1]); assert_se(items[1].item_list_next == &items[2]); assert_se(items[2].item_list_next == &items[3]); - assert_se(items[3].item_list_next == NULL); + ASSERT_NULL(items[3].item_list_next); - assert_se(items[0].item_list_prev == NULL); + ASSERT_NULL(items[0].item_list_prev); assert_se(items[1].item_list_prev == &items[0]); assert_se(items[2].item_list_prev == &items[1]); assert_se(items[3].item_list_prev == &items[2]); @@ -203,7 +203,7 @@ int main(int argc, const char *argv[]) { for (i = 0; i < ELEMENTSOF(items); i++) assert_se(LIST_REMOVE(item_list, head, &items[i]) == &items[i]); - assert_se(head == NULL); + ASSERT_NULL(head); for (i = 0; i < ELEMENTSOF(items) / 2; i++) { LIST_INIT(item_list, &items[i]); @@ -217,20 +217,20 @@ int main(int argc, const char *argv[]) { assert_se(LIST_PREPEND(item_list, head2, &items[i]) == &items[i]); } - assert_se(items[0].item_list_next == NULL); + ASSERT_NULL(items[0].item_list_next); assert_se(items[1].item_list_next == &items[0]); - assert_se(items[2].item_list_next == NULL); + ASSERT_NULL(items[2].item_list_next); assert_se(items[3].item_list_next == &items[2]); assert_se(items[0].item_list_prev == &items[1]); - assert_se(items[1].item_list_prev == NULL); + ASSERT_NULL(items[1].item_list_prev); assert_se(items[2].item_list_prev == &items[3]); - assert_se(items[3].item_list_prev == NULL); + ASSERT_NULL(items[3].item_list_prev); assert_se(LIST_JOIN(item_list, head2, head) == head2); - assert_se(head == NULL); + ASSERT_NULL(head); - assert_se(items[0].item_list_next == NULL); + ASSERT_NULL(items[0].item_list_next); assert_se(items[1].item_list_next == &items[0]); assert_se(items[2].item_list_next == &items[1]); assert_se(items[3].item_list_next == &items[2]); @@ -238,16 +238,16 @@ int main(int argc, const char *argv[]) { assert_se(items[0].item_list_prev == &items[1]); assert_se(items[1].item_list_prev == &items[2]); assert_se(items[2].item_list_prev == &items[3]); - assert_se(items[3].item_list_prev == NULL); + ASSERT_NULL(items[3].item_list_prev); assert_se(LIST_JOIN(item_list, head, head2) == head); - assert_se(head2 == NULL); + ASSERT_NULL(head2); assert_se(head); for (i = 0; i < ELEMENTSOF(items); i++) assert_se(LIST_REMOVE(item_list, head, &items[i]) == &items[i]); - assert_se(head == NULL); + ASSERT_NULL(head); assert_se(LIST_PREPEND(item_list, head, items + 0) == items + 0); assert_se(LIST_PREPEND(item_list, head, items + 1) == items + 1); @@ -256,7 +256,7 @@ int main(int argc, const char *argv[]) { assert_se(LIST_POP(item_list, head) == items + 2); assert_se(LIST_POP(item_list, head) == items + 1); assert_se(LIST_POP(item_list, head) == items + 0); - assert_se(LIST_POP(item_list, head) == NULL); + ASSERT_NULL(LIST_POP(item_list, head)); /* No-op on an empty list */ @@ -269,7 +269,7 @@ int main(int argc, const char *argv[]) { LIST_CLEAR(item_list, head, free); - assert_se(head == NULL); + ASSERT_NULL(head); /* A list can be cleared partially */ @@ -280,7 +280,7 @@ int main(int argc, const char *argv[]) { LIST_CLEAR(item_list, head->item_list_next, free); assert_se(head == items + 0); - assert_se(head->item_list_next == NULL); + ASSERT_NULL(head->item_list_next); return 0; } diff --git a/src/test/test-load-fragment.c b/src/test/test-load-fragment.c index 8d2cec0..94904e5 100644 --- a/src/test/test-load-fragment.c +++ b/src/test/test-load-fragment.c @@ -79,12 +79,12 @@ static void check_execcommand(ExecCommand *c, n = strv_length(c->argv); log_info("actual: \"%s\" [\"%s\" \"%s\" \"%s\"]", c->path, c->argv[0], n > 0 ? c->argv[1] : "(null)", n > 1 ? c->argv[2] : "(null)"); - assert_se(streq(c->path, path)); - assert_se(streq(c->argv[0], argv0 ?: path)); + ASSERT_STREQ(c->path, path); + ASSERT_STREQ(c->argv[0], argv0 ?: path); if (n > 0) - assert_se(streq_ptr(c->argv[1], argv1)); + ASSERT_STREQ(c->argv[1], argv1); if (n > 1) - assert_se(streq_ptr(c->argv[2], argv2)); + ASSERT_STREQ(c->argv[2], argv2); assert_se(!!(c->flags & EXEC_COMMAND_IGNORE_FAILURE) == ignore); } @@ -139,7 +139,7 @@ TEST(config_parse_exec) { "LValue", 0, "/RValue/ argv0 r1", &c, u); assert_se(r == -ENOEXEC); - assert_se(c1->command_next == NULL); + ASSERT_NULL(c1->command_next); log_info("/* honour_argv0 */"); r = config_parse_exec(NULL, "fake", 3, "section", 1, @@ -154,14 +154,14 @@ TEST(config_parse_exec) { "LValue", 0, "@/RValue", &c, u); assert_se(r == -ENOEXEC); - assert_se(c1->command_next == NULL); + ASSERT_NULL(c1->command_next); log_info("/* no command, whitespace only, reset */"); r = config_parse_exec(NULL, "fake", 3, "section", 1, "LValue", 0, "", &c, u); assert_se(r == 0); - assert_se(c == NULL); + ASSERT_NULL(c); log_info("/* ignore && honour_argv0 */"); r = config_parse_exec(NULL, "fake", 4, "section", 1, @@ -184,14 +184,14 @@ TEST(config_parse_exec) { "LValue", 0, "--/RValue argv0 r1", &c, u); assert_se(r == 0); - assert_se(c1->command_next == NULL); + ASSERT_NULL(c1->command_next); log_info("/* ignore && ignore (2) */"); r = config_parse_exec(NULL, "fake", 4, "section", 1, "LValue", 0, "-@-/RValue argv0 r1", &c, u); assert_se(r == 0); - assert_se(c1->command_next == NULL); + ASSERT_NULL(c1->command_next); log_info("/* semicolon */"); r = config_parse_exec(NULL, "fake", 5, "section", 1, @@ -227,7 +227,7 @@ TEST(config_parse_exec) { c1 = c1->command_next; check_execcommand(c1, "/RValue", "argv0", "r1", NULL, true); - assert_se(c1->command_next == NULL); + ASSERT_NULL(c1->command_next); log_info("/* trailing semicolon, no whitespace */"); r = config_parse_exec(NULL, "fake", 5, "section", 1, @@ -238,7 +238,7 @@ TEST(config_parse_exec) { c1 = c1->command_next; check_execcommand(c1, "/RValue", "argv0", "r1", NULL, true); - assert_se(c1->command_next == NULL); + ASSERT_NULL(c1->command_next); log_info("/* trailing semicolon in single quotes */"); r = config_parse_exec(NULL, "fake", 5, "section", 1, @@ -366,7 +366,7 @@ TEST(config_parse_exec) { "LValue", 0, path, &c, u); assert_se(r == -ENOEXEC); - assert_se(c1->command_next == NULL); + ASSERT_NULL(c1->command_next); } log_info("/* valid character: \\s */"); @@ -392,35 +392,35 @@ TEST(config_parse_exec) { "LValue", 0, "/path\\", &c, u); assert_se(r == -ENOEXEC); - assert_se(c1->command_next == NULL); + ASSERT_NULL(c1->command_next); log_info("/* missing ending ' */"); r = config_parse_exec(NULL, "fake", 4, "section", 1, "LValue", 0, "/path 'foo", &c, u); assert_se(r == -ENOEXEC); - assert_se(c1->command_next == NULL); + ASSERT_NULL(c1->command_next); log_info("/* missing ending ' with trailing backslash */"); r = config_parse_exec(NULL, "fake", 4, "section", 1, "LValue", 0, "/path 'foo\\", &c, u); assert_se(r == -ENOEXEC); - assert_se(c1->command_next == NULL); + ASSERT_NULL(c1->command_next); log_info("/* invalid space between modifiers */"); r = config_parse_exec(NULL, "fake", 4, "section", 1, "LValue", 0, "- /path", &c, u); assert_se(r == 0); - assert_se(c1->command_next == NULL); + ASSERT_NULL(c1->command_next); log_info("/* only modifiers, no path */"); r = config_parse_exec(NULL, "fake", 4, "section", 1, "LValue", 0, "-", &c, u); assert_se(r == 0); - assert_se(c1->command_next == NULL); + ASSERT_NULL(c1->command_next); log_info("/* long arg */"); /* See issue #22957. */ @@ -442,7 +442,7 @@ TEST(config_parse_exec) { "LValue", 0, "", &c, u); assert_se(r == 0); - assert_se(c == NULL); + ASSERT_NULL(c); exec_command_free_list(c); } @@ -544,7 +544,7 @@ TEST(install_printf, .sd_booted = true) { memzero(i.path, strlen(i.path)); \ if (result) { \ printf("%s\n", t); \ - assert_se(streq(t, result)); \ + ASSERT_STREQ(t, result); \ } else \ assert_se(!t); \ strcpy(i.name, d1); \ @@ -794,8 +794,8 @@ TEST(config_parse_pass_environ) { &passenv, NULL); assert_se(r >= 0); assert_se(strv_length(passenv) == 2); - assert_se(streq(passenv[0], "A")); - assert_se(streq(passenv[1], "B")); + ASSERT_STREQ(passenv[0], "A"); + ASSERT_STREQ(passenv[1], "B"); r = config_parse_pass_environ(NULL, "fake", 1, "section", 1, "PassEnvironment", 0, "", @@ -808,7 +808,7 @@ TEST(config_parse_pass_environ) { &passenv, NULL); assert_se(r >= 0); assert_se(strv_length(passenv) == 1); - assert_se(streq(passenv[0], "normal_name")); + ASSERT_STREQ(passenv[0], "normal_name"); } TEST(config_parse_unit_env_file) { @@ -858,8 +858,8 @@ TEST(config_parse_unit_env_file) { &files, u); assert_se(r == 0); assert_se(strv_length(files) == 2); - assert_se(streq(files[0], "/absolute1")); - assert_se(streq(files[1], "/absolute2")); + ASSERT_STREQ(files[0], "/absolute1"); + ASSERT_STREQ(files[1], "/absolute2"); r = config_parse_unit_env_file(u->id, "fake", 1, "section", 1, "EnvironmentFile", 0, "", @@ -872,7 +872,7 @@ TEST(config_parse_unit_env_file) { &files, u); assert_se(r == 0); assert_se(strv_length(files) == 1); - assert_se(streq(files[0], "/path/foobar.service.conf")); + ASSERT_STREQ(files[0], "/path/foobar.service.conf"); } TEST(unit_dump_config_items) { @@ -1073,8 +1073,8 @@ TEST(config_parse_open_file) { &of, u); assert_se(r >= 0); assert_se(of); - assert_se(streq(of->path, "/proc/1/ns/mnt")); - assert_se(streq(of->fdname, "host-mount-namespace")); + ASSERT_STREQ(of->path, "/proc/1/ns/mnt"); + ASSERT_STREQ(of->fdname, "host-mount-namespace"); assert_se(of->flags == OPENFILE_READ_ONLY); of = open_file_free(of); @@ -1083,8 +1083,8 @@ TEST(config_parse_open_file) { &of, u); assert_se(r >= 0); assert_se(of); - assert_se(streq(of->path, "/proc/1/ns/mnt")); - assert_se(streq(of->fdname, "mnt")); + ASSERT_STREQ(of->path, "/proc/1/ns/mnt"); + ASSERT_STREQ(of->fdname, "mnt"); assert_se(of->flags == OPENFILE_READ_ONLY); r = config_parse_open_file(NULL, "fake", 1, "section", 1, diff --git a/src/test/test-local-addresses.c b/src/test/test-local-addresses.c index 5a02465..f418f37 100644 --- a/src/test/test-local-addresses.c +++ b/src/test/test-local-addresses.c @@ -1,20 +1,25 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* Make sure the net/if.h header is included before any linux/ one */ +#include <net/if.h> +#include <linux/if.h> #include <stdio.h> #include "af-list.h" #include "alloc-util.h" +#include "capability-util.h" #include "in-addr-util.h" #include "local-addresses.h" +#include "netlink-util.h" #include "tests.h" -static void print_local_addresses(struct local_address *a, unsigned n) { - for (unsigned i = 0; i < n; i++) { - _cleanup_free_ char *b = NULL; +static bool support_rta_via = false; - assert_se(in_addr_to_string(a[i].family, &a[i].address, &b) >= 0); - log_debug("%s if%i scope=%i metric=%u address=%s", af_to_name(a[i].family), a[i].ifindex, a[i].scope, a[i].metric, b); - } +static void print_local_addresses(const struct local_address *a, size_t n) { + FOREACH_ARRAY(i, a, n) + log_debug("%s ifindex=%i scope=%u priority=%"PRIu32" weight=%"PRIu32" address=%s", + af_to_name(i->family), i->ifindex, i->scope, i->priority, i->weight, + IN_ADDR_TO_STRING(i->family, &i->address)); } TEST(local_addresses) { @@ -24,50 +29,300 @@ TEST(local_addresses) { n = local_addresses(NULL, 0, AF_INET, &a); assert_se(n >= 0); log_debug("/* Local Addresses(ifindex:0, AF_INET) */"); - print_local_addresses(a, (unsigned) n); + print_local_addresses(a, n); a = mfree(a); n = local_addresses(NULL, 0, AF_INET6, &a); assert_se(n >= 0); log_debug("/* Local Addresses(ifindex:0, AF_INET6) */"); - print_local_addresses(a, (unsigned) n); + print_local_addresses(a, n); a = mfree(a); n = local_addresses(NULL, 0, AF_UNSPEC, &a); assert_se(n >= 0); log_debug("/* Local Addresses(ifindex:0, AF_UNSPEC) */"); - print_local_addresses(a, (unsigned) n); + print_local_addresses(a, n); a = mfree(a); n = local_addresses(NULL, 1, AF_INET, &a); assert_se(n >= 0); log_debug("/* Local Addresses(ifindex:1, AF_INET) */"); - print_local_addresses(a, (unsigned) n); + print_local_addresses(a, n); a = mfree(a); n = local_addresses(NULL, 1, AF_INET6, &a); assert_se(n >= 0); log_debug("/* Local Addresses(ifindex:1, AF_INET6) */"); - print_local_addresses(a, (unsigned) n); + print_local_addresses(a, n); a = mfree(a); n = local_addresses(NULL, 1, AF_UNSPEC, &a); assert_se(n >= 0); log_debug("/* Local Addresses(ifindex:1, AF_UNSPEC) */"); - print_local_addresses(a, (unsigned) n); + print_local_addresses(a, n); a = mfree(a); n = local_gateways(NULL, 0, AF_UNSPEC, &a); assert_se(n >= 0); log_debug("/* Local Gateways */"); - print_local_addresses(a, (unsigned) n); + print_local_addresses(a, n); a = mfree(a); n = local_outbounds(NULL, 0, AF_UNSPEC, &a); assert_se(n >= 0); log_debug("/* Local Outbounds */"); - print_local_addresses(a, (unsigned) n); + print_local_addresses(a, n); free(a); } +static void check_local_addresses(sd_netlink *rtnl, int ifindex, int request_ifindex, int family) { + _cleanup_free_ struct local_address *a = NULL; + union in_addr_union u; + int n; + + log_debug("/* Local Addresses (ifindex:%i, %s) */", request_ifindex, family == AF_UNSPEC ? "AF_UNSPEC" : af_to_name(family)); + + n = local_addresses(rtnl, request_ifindex, family, &a); + assert_se(n >= 0); + print_local_addresses(a, n); + + assert_se(in_addr_from_string(AF_INET, "10.123.123.123", &u) >= 0); + assert_se(has_local_address(a, n, + &(struct local_address) { + .ifindex = ifindex, + .scope = RT_SCOPE_UNIVERSE, + .family = AF_INET, + .address = u, + }) == IN_SET(family, AF_UNSPEC, AF_INET)); + + assert_se(in_addr_from_string(AF_INET6, "2001:db8:0:123::123", &u) >= 0); + assert_se(has_local_address(a, n, + &(struct local_address) { + .ifindex = ifindex, + .scope = RT_SCOPE_UNIVERSE, + .family = AF_INET6, + .address = u, + }) == IN_SET(family, AF_UNSPEC, AF_INET6)); + + assert_se(in_addr_from_string(AF_INET6, "2001:db8:1:123::123", &u) >= 0); + assert_se(has_local_address(a, n, + &(struct local_address) { + .ifindex = ifindex, + .scope = RT_SCOPE_UNIVERSE, + .family = AF_INET6, + .address = u, + }) == IN_SET(family, AF_UNSPEC, AF_INET6)); +} + +static void check_local_gateways(sd_netlink *rtnl, int ifindex, int request_ifindex, int family) { + _cleanup_free_ struct local_address *a = NULL; + union in_addr_union u; + int n; + + log_debug("/* Local Gateways (ifindex:%i, %s) */", request_ifindex, family == AF_UNSPEC ? "AF_UNSPEC" : af_to_name(family)); + + n = local_gateways(rtnl, request_ifindex, family, &a); + assert_se(n >= 0); + print_local_addresses(a, n); + + assert_se(in_addr_from_string(AF_INET, "10.123.0.1", &u) >= 0); + assert_se(has_local_address(a, n, + &(struct local_address) { + .ifindex = ifindex, + .priority = 1234, + .family = AF_INET, + .address = u, + }) == IN_SET(family, AF_UNSPEC, AF_INET)); + + assert_se(in_addr_from_string(AF_INET6, "2001:db8:0:123::1", &u) >= 0); + assert_se(has_local_address(a, n, + &(struct local_address) { + .ifindex = ifindex, + .priority = 1234, + .family = AF_INET6, + .address = u, + }) == (family == AF_UNSPEC && support_rta_via)); + + assert_se(in_addr_from_string(AF_INET6, "2001:db8:1:123::1", &u) >= 0); + assert_se(has_local_address(a, n, + &(struct local_address) { + .ifindex = ifindex, + .priority = 1234, + .family = AF_INET6, + .address = u, + }) == IN_SET(family, AF_UNSPEC, AF_INET6)); +} + +static void check_local_outbounds(sd_netlink *rtnl, int ifindex, int request_ifindex, int family) { + _cleanup_free_ struct local_address *a = NULL; + union in_addr_union u; + int n; + + log_debug("/* Local Outbounds (ifindex:%i, %s) */", request_ifindex, family == AF_UNSPEC ? "AF_UNSPEC" : af_to_name(family)); + + n = local_outbounds(rtnl, request_ifindex, family, &a); + assert_se(n >= 0); + print_local_addresses(a, n); + + assert_se(in_addr_from_string(AF_INET, "10.123.123.123", &u) >= 0); + assert_se(has_local_address(a, n, + &(struct local_address) { + .ifindex = ifindex, + .family = AF_INET, + .address = u, + }) == IN_SET(family, AF_UNSPEC, AF_INET)); + + assert_se(in_addr_from_string(AF_INET6, "2001:db8:0:123::123", &u) >= 0); + assert_se(has_local_address(a, n, + &(struct local_address) { + .ifindex = ifindex, + .family = AF_INET6, + .address = u, + }) == (family == AF_UNSPEC && support_rta_via)); + + assert_se(in_addr_from_string(AF_INET6, "2001:db8:1:123::123", &u) >= 0); + assert_se(has_local_address(a, n, + &(struct local_address) { + .ifindex = ifindex, + .family = AF_INET6, + .address = u, + }) == IN_SET(family, AF_UNSPEC, AF_INET6)); +} + +TEST(local_addresses_with_dummy) { + _cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL; + _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *message = NULL, *reply = NULL; + union in_addr_union u; + int r, ifindex; + + assert_se(sd_netlink_open(&rtnl) >= 0); + + /* Create a dummy interface */ + assert_se(sd_rtnl_message_new_link(rtnl, &message, RTM_NEWLINK, 0) >= 0); + assert_se(sd_netlink_message_append_string(message, IFLA_IFNAME, "test-local-addr") >= 0); + assert_se(sd_netlink_message_open_container(message, IFLA_LINKINFO) >= 0); + assert_se(sd_netlink_message_append_string(message, IFLA_INFO_KIND, "dummy") >= 0); + r = sd_netlink_call(rtnl, message, 0, NULL); + if (r == -EPERM) + return (void) log_tests_skipped("missing required capabilities"); + if (r == -EOPNOTSUPP) + return (void) log_tests_skipped("dummy network interface is not supported"); + assert_se(r >= 0); + message = sd_netlink_message_unref(message); + + /* Get ifindex */ + assert_se(sd_rtnl_message_new_link(rtnl, &message, RTM_GETLINK, 0) >= 0); + assert_se(sd_netlink_message_append_string(message, IFLA_IFNAME, "test-local-addr") >= 0); + assert_se(sd_netlink_call(rtnl, message, 0, &reply) >= 0); + assert_se(sd_rtnl_message_link_get_ifindex(reply, &ifindex) >= 0); + assert_se(ifindex > 0); + message = sd_netlink_message_unref(message); + reply = sd_netlink_message_unref(reply); + + /* Bring the interface up */ + assert_se(sd_rtnl_message_new_link(rtnl, &message, RTM_SETLINK, ifindex) >= 0); + assert_se(sd_rtnl_message_link_set_flags(message, IFF_UP, IFF_UP) >= 0); + assert_se(sd_netlink_call(rtnl, message, 0, NULL) >= 0); + message = sd_netlink_message_unref(message); + + /* Add an IPv4 address */ + assert_se(sd_rtnl_message_new_addr_update(rtnl, &message, ifindex, AF_INET) >= 0); + assert_se(sd_rtnl_message_addr_set_scope(message, RT_SCOPE_UNIVERSE) >= 0); + assert_se(sd_rtnl_message_addr_set_prefixlen(message, 16) >= 0); + assert_se(in_addr_from_string(AF_INET, "10.123.123.123", &u) >= 0); + assert_se(sd_netlink_message_append_in_addr(message, IFA_LOCAL, &u.in) >= 0); + assert_se(in_addr_from_string(AF_INET, "10.123.255.255", &u) >= 0); + assert_se(sd_netlink_message_append_in_addr(message, IFA_BROADCAST, &u.in) >= 0); + assert_se(sd_netlink_call(rtnl, message, 0, NULL) >= 0); + message = sd_netlink_message_unref(message); + + /* Add IPv6 addresses */ + assert_se(sd_rtnl_message_new_addr_update(rtnl, &message, ifindex, AF_INET6) >= 0); + assert_se(sd_rtnl_message_addr_set_scope(message, RT_SCOPE_UNIVERSE) >= 0); + assert_se(sd_rtnl_message_addr_set_prefixlen(message, 64) >= 0); + assert_se(in_addr_from_string(AF_INET6, "2001:db8:0:123::123", &u) >= 0); + assert_se(sd_netlink_message_append_in6_addr(message, IFA_LOCAL, &u.in6) >= 0); + assert_se(sd_netlink_message_append_u32(message, IFA_FLAGS, IFA_F_NODAD) >= 0); + assert_se(sd_netlink_call(rtnl, message, 0, NULL) >= 0); + message = sd_netlink_message_unref(message); + + assert_se(sd_rtnl_message_new_addr_update(rtnl, &message, ifindex, AF_INET6) >= 0); + assert_se(sd_rtnl_message_addr_set_scope(message, RT_SCOPE_UNIVERSE) >= 0); + assert_se(sd_rtnl_message_addr_set_prefixlen(message, 64) >= 0); + assert_se(in_addr_from_string(AF_INET6, "2001:db8:1:123::123", &u) >= 0); + assert_se(sd_netlink_message_append_in6_addr(message, IFA_LOCAL, &u.in6) >= 0); + assert_se(sd_netlink_message_append_u32(message, IFA_FLAGS, IFA_F_NODAD) >= 0); + assert_se(sd_netlink_call(rtnl, message, 0, NULL) >= 0); + message = sd_netlink_message_unref(message); + + /* Add an IPv4 default gateway (RTA_GATEWAY) */ + assert_se(sd_rtnl_message_new_route(rtnl, &message, RTM_NEWROUTE, AF_INET, RTPROT_STATIC) >= 0); + assert_se(sd_rtnl_message_route_set_scope(message, RT_SCOPE_UNIVERSE) >= 0); + assert_se(sd_rtnl_message_route_set_type(message, RTN_UNICAST) >= 0); + assert_se(sd_netlink_message_append_u32(message, RTA_PRIORITY, 1234) >= 0); + assert_se(sd_netlink_message_append_u32(message, RTA_TABLE, RT_TABLE_MAIN) >= 0); + assert_se(in_addr_from_string(AF_INET, "10.123.0.1", &u) >= 0); + assert_se(sd_netlink_message_append_in_addr(message, RTA_GATEWAY, &u.in) >= 0); + assert_se(sd_netlink_message_append_u32(message, RTA_OIF, ifindex) >= 0); + assert_se(sd_netlink_call(rtnl, message, 0, NULL) >= 0); + message = sd_netlink_message_unref(message); + + /* Add an IPv4 default gateway (RTA_VIA) */ + assert_se(sd_rtnl_message_new_route(rtnl, &message, RTM_NEWROUTE, AF_INET, RTPROT_STATIC) >= 0); + assert_se(sd_rtnl_message_route_set_scope(message, RT_SCOPE_UNIVERSE) >= 0); + assert_se(sd_rtnl_message_route_set_type(message, RTN_UNICAST) >= 0); + assert_se(sd_netlink_message_append_u32(message, RTA_PRIORITY, 1234) >= 0); + assert_se(sd_netlink_message_append_u32(message, RTA_TABLE, RT_TABLE_MAIN) >= 0); + assert_se(in_addr_from_string(AF_INET6, "2001:db8:0:123::1", &u) >= 0); + assert_se(sd_netlink_message_append_data(message, RTA_VIA, + &(RouteVia) { + .family = AF_INET6, + .address = u, + }, sizeof(RouteVia)) >= 0); + assert_se(sd_netlink_message_append_u32(message, RTA_OIF, ifindex) >= 0); + r = sd_netlink_call(rtnl, message, 0, NULL); + if (r == -EINVAL) + log_debug_errno(r, "RTA_VIA is not supported, ignoring: %m"); + else + assert_se(r >= 0); + support_rta_via = r >= 0; + message = sd_netlink_message_unref(message); + + /* Add an IPv6 default gateway */ + assert_se(sd_rtnl_message_new_route(rtnl, &message, RTM_NEWROUTE, AF_INET6, RTPROT_STATIC) >= 0); + assert_se(sd_rtnl_message_route_set_type(message, RTN_UNICAST) >= 0); + assert_se(sd_netlink_message_append_u32(message, RTA_PRIORITY, 1234) >= 0); + assert_se(sd_netlink_message_append_u32(message, RTA_TABLE, RT_TABLE_MAIN) >= 0); + assert_se(in_addr_from_string(AF_INET6, "2001:db8:1:123::1", &u) >= 0); + assert_se(sd_netlink_message_append_in6_addr(message, RTA_GATEWAY, &u.in6) >= 0); + assert_se(sd_netlink_message_append_u32(message, RTA_OIF, ifindex) >= 0); + assert_se(sd_netlink_call(rtnl, message, 0, NULL) >= 0); + message = sd_netlink_message_unref(message); + + /* Check */ + check_local_addresses(rtnl, ifindex, 0, AF_UNSPEC); + check_local_addresses(rtnl, ifindex, 0, AF_INET); + check_local_addresses(rtnl, ifindex, 0, AF_INET6); + check_local_addresses(rtnl, ifindex, ifindex, AF_UNSPEC); + check_local_addresses(rtnl, ifindex, ifindex, AF_INET); + check_local_addresses(rtnl, ifindex, ifindex, AF_INET6); + check_local_gateways(rtnl, ifindex, 0, AF_UNSPEC); + check_local_gateways(rtnl, ifindex, 0, AF_INET); + check_local_gateways(rtnl, ifindex, 0, AF_INET6); + check_local_gateways(rtnl, ifindex, ifindex, AF_UNSPEC); + check_local_gateways(rtnl, ifindex, ifindex, AF_INET); + check_local_gateways(rtnl, ifindex, ifindex, AF_INET6); + check_local_outbounds(rtnl, ifindex, 0, AF_UNSPEC); + check_local_outbounds(rtnl, ifindex, 0, AF_INET); + check_local_outbounds(rtnl, ifindex, 0, AF_INET6); + check_local_outbounds(rtnl, ifindex, ifindex, AF_UNSPEC); + check_local_outbounds(rtnl, ifindex, ifindex, AF_INET); + check_local_outbounds(rtnl, ifindex, ifindex, AF_INET6); + + /* Cleanup */ + assert_se(sd_rtnl_message_new_link(rtnl, &message, RTM_DELLINK, ifindex) >= 0); + assert_se(sd_netlink_call(rtnl, message, 0, NULL) >= 0); + message = sd_netlink_message_unref(message); +} + DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-locale-util.c b/src/test/test-locale-util.c index 39f71c6..ab2d1f5 100644 --- a/src/test/test-locale-util.c +++ b/src/test/test-locale-util.c @@ -82,7 +82,7 @@ TEST(keymaps) { #define dump_glyph(x) log_info(STRINGIFY(x) ": %s", special_glyph(x)) TEST(dump_special_glyphs) { - assert_cc(SPECIAL_GLYPH_WORLD + 1 == _SPECIAL_GLYPH_MAX); + assert_cc(SPECIAL_GLYPH_GREEN_CIRCLE + 1 == _SPECIAL_GLYPH_MAX); log_info("is_locale_utf8: %s", yes_no(is_locale_utf8())); @@ -92,6 +92,8 @@ TEST(dump_special_glyphs) { dump_glyph(SPECIAL_GLYPH_TREE_SPACE); dump_glyph(SPECIAL_GLYPH_TREE_TOP); dump_glyph(SPECIAL_GLYPH_VERTICAL_DOTTED); + dump_glyph(SPECIAL_GLYPH_HORIZONTAL_DOTTED); + dump_glyph(SPECIAL_GLYPH_HORIZONTAL_FAT); dump_glyph(SPECIAL_GLYPH_TRIANGULAR_BULLET); dump_glyph(SPECIAL_GLYPH_BLACK_CIRCLE); dump_glyph(SPECIAL_GLYPH_WHITE_CIRCLE); @@ -127,6 +129,10 @@ TEST(dump_special_glyphs) { dump_glyph(SPECIAL_GLYPH_WARNING_SIGN); dump_glyph(SPECIAL_GLYPH_COMPUTER_DISK); dump_glyph(SPECIAL_GLYPH_WORLD); + dump_glyph(SPECIAL_GLYPH_RED_CIRCLE); + dump_glyph(SPECIAL_GLYPH_YELLOW_CIRCLE); + dump_glyph(SPECIAL_GLYPH_BLUE_CIRCLE); + dump_glyph(SPECIAL_GLYPH_GREEN_CIRCLE); } DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-log.c b/src/test/test-log.c index b5ba67b..97eb5e0 100644 --- a/src/test/test-log.c +++ b/src/test/test-log.c @@ -22,6 +22,26 @@ assert_cc(!IS_SYNTHETIC_ERRNO(0)); #define X100(x) X10(X10(x)) #define X1000(x) X100(X10(x)) +static int fail_with_EINVAL(void) { + assert_return(false, -EINVAL); + return 0; +} + +static void test_assert_return_is_critical(void) { + SAVE_ASSERT_RETURN_IS_CRITICAL; + + log_set_assert_return_is_critical(false); + assert_se(fail_with_EINVAL() == -EINVAL); + + log_set_assert_return_is_critical(true); + ASSERT_RETURN_IS_CRITICAL(false, assert_se(fail_with_EINVAL() == -EINVAL)); + assert_se(log_get_assert_return_is_critical() == true); + ASSERT_RETURN_EXPECTED(assert_se(fail_with_EINVAL() == -EINVAL)); + assert_se(log_get_assert_return_is_critical() == true); + ASSERT_RETURN_EXPECTED_SE(fail_with_EINVAL() == -EINVAL); + assert_se(log_get_assert_return_is_critical() == true); +} + static void test_file(void) { log_info("__FILE__: %s", __FILE__); log_info("RELATIVE_SOURCE_PATH: %s", RELATIVE_SOURCE_PATH); @@ -207,6 +227,7 @@ static void test_log_prefix(void) { int main(int argc, char* argv[]) { test_setup_logging(LOG_DEBUG); + test_assert_return_is_critical(); test_file(); assert_se(log_info_errno(SYNTHETIC_ERRNO(EUCLEAN), "foo") == -EUCLEAN); diff --git a/src/test/test-login-util.c b/src/test/test-login-util.c new file mode 100644 index 0000000..2d20e23 --- /dev/null +++ b/src/test/test-login-util.c @@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include "login-util.h" +#include "string-util.h" +#include "tests.h" + +TEST(session_id_valid) { + /* Invalid Session ID */ + assert_se(!session_id_valid("")); + assert_se(!session_id_valid(NULL)); + assert_se(!session_id_valid("abc-123")); + assert_se(!session_id_valid("abc_123")); + assert_se(!session_id_valid("abc123*")); + + /* Valid Session ID */ + assert_se(session_id_valid("abc123")); + assert_se(session_id_valid("AbCdEfG123456")); + assert_se(session_id_valid("1234567890")); + assert_se(session_id_valid("ABCDEFGHI")); +} + +DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-loop-block.c b/src/test/test-loop-block.c index 1bd00d1..15c6357 100644 --- a/src/test/test-loop-block.c +++ b/src/test/test-loop-block.c @@ -49,10 +49,10 @@ static void verify_dissected_image(DissectedImage *dissected) { static void verify_dissected_image_harder(DissectedImage *dissected) { verify_dissected_image(dissected); - assert_se(streq(dissected->partitions[PARTITION_ESP].fstype, "vfat")); - assert_se(streq(dissected->partitions[PARTITION_XBOOTLDR].fstype, "vfat")); - assert_se(streq(dissected->partitions[PARTITION_ROOT].fstype, "ext4")); - assert_se(streq(dissected->partitions[PARTITION_HOME].fstype, "ext4")); + ASSERT_STREQ(dissected->partitions[PARTITION_ESP].fstype, "vfat"); + ASSERT_STREQ(dissected->partitions[PARTITION_XBOOTLDR].fstype, "vfat"); + ASSERT_STREQ(dissected->partitions[PARTITION_ROOT].fstype, "ext4"); + ASSERT_STREQ(dissected->partitions[PARTITION_HOME].fstype, "ext4"); } static void* thread_func(void *ptr) { @@ -328,7 +328,7 @@ static int run(int argc, char *argv[]) { log_notice("All threads started now."); if (arg_n_threads == 1) - assert_se(thread_func(FD_TO_PTR(fd)) == NULL); + ASSERT_NULL(thread_func(FD_TO_PTR(fd))); else for (unsigned i = 0; i < arg_n_threads; i++) { log_notice("Joining thread #%u.", i); diff --git a/src/test/test-loopback.c b/src/test/test-loopback.c index 48869ae..db6ee0f 100644 --- a/src/test/test-loopback.c +++ b/src/test/test-loopback.c @@ -19,6 +19,8 @@ TEST_RET(loopback_setup) { } r = loopback_setup(); + if (ERRNO_IS_NEG_PRIVILEGE(r)) + return log_tests_skipped("lacking privileges"); if (r < 0) return log_error_errno(r, "loopback: %m"); diff --git a/src/test/test-macro.c b/src/test/test-macro.c index b91a1f9..9e2875d 100644 --- a/src/test/test-macro.c +++ b/src/test/test-macro.c @@ -1,7 +1,9 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stddef.h> +#include <sys/stat.h> +#include "errno-util.h" #include "log.h" #include "macro.h" #include "tests.h" @@ -159,6 +161,153 @@ TEST(container_of) { #pragma GCC diagnostic pop +#define TEST_OVERFLOW_MATH_BY_TYPE(type, min, max, lit) \ + ({ \ + type x; \ + \ + assert_se(ADD_SAFE(&x, lit(5), lit(10))); \ + assert_se(x == lit(15)); \ + if (IS_SIGNED_INTEGER_TYPE(type)) { \ + assert_se(ADD_SAFE(&x, lit(5), lit(-10))); \ + assert_se(x == lit(-5)); \ + } \ + assert_se(ADD_SAFE(&x, min, lit(0))); \ + assert_se(x == min); \ + assert_se(ADD_SAFE(&x, max, lit(0))); \ + assert_se(x == max); \ + if (IS_SIGNED_INTEGER_TYPE(type)) \ + assert_se(!ADD_SAFE(&x, min, lit(-1))); \ + assert_se(!ADD_SAFE(&x, max, lit(1))); \ + \ + x = lit(5); \ + assert_se(INC_SAFE(&x, lit(10))); \ + assert_se(x == lit(15)); \ + if (IS_SIGNED_INTEGER_TYPE(type)) { \ + assert_se(INC_SAFE(&x, lit(-20))); \ + assert_se(x == lit(-5)); \ + } \ + x = min; \ + assert_se(INC_SAFE(&x, lit(0))); \ + assert_se(x == min); \ + if (IS_SIGNED_INTEGER_TYPE(type)) \ + assert_se(!INC_SAFE(&x, lit(-1))); \ + x = max; \ + assert_se(INC_SAFE(&x, lit(0))); \ + assert_se(x == max); \ + assert_se(!INC_SAFE(&x, lit(1))); \ + \ + assert_se(SUB_SAFE(&x, lit(10), lit(5))); \ + assert_se(x == lit(5)); \ + if (IS_SIGNED_INTEGER_TYPE(type)) { \ + assert_se(SUB_SAFE(&x, lit(5), lit(10))); \ + assert_se(x == lit(-5)); \ + \ + assert_se(SUB_SAFE(&x, lit(5), lit(-10))); \ + assert_se(x == lit(15)); \ + } else \ + assert_se(!SUB_SAFE(&x, lit(5), lit(10))); \ + assert_se(SUB_SAFE(&x, min, lit(0))); \ + assert_se(x == min); \ + assert_se(SUB_SAFE(&x, max, lit(0))); \ + assert_se(x == max); \ + assert_se(!SUB_SAFE(&x, min, lit(1))); \ + if (IS_SIGNED_INTEGER_TYPE(type)) \ + assert_se(!SUB_SAFE(&x, max, lit(-1))); \ + \ + x = lit(10); \ + assert_se(DEC_SAFE(&x, lit(5))); \ + assert_se(x == lit(5)); \ + if (IS_SIGNED_INTEGER_TYPE(type)) { \ + assert_se(DEC_SAFE(&x, lit(10))); \ + assert_se(x == lit(-5)); \ + \ + x = lit(5); \ + assert_se(DEC_SAFE(&x, lit(-10))); \ + assert_se(x == lit(15)); \ + } else \ + assert_se(!DEC_SAFE(&x, lit(10))); \ + x = min; \ + assert_se(DEC_SAFE(&x, lit(0))); \ + assert_se(x == min); \ + assert_se(!DEC_SAFE(&x, lit(1))); \ + x = max; \ + assert_se(DEC_SAFE(&x, lit(0))); \ + if (IS_SIGNED_INTEGER_TYPE(type)) \ + assert_se(!DEC_SAFE(&x, lit(-1))); \ + \ + assert_se(MUL_SAFE(&x, lit(2), lit(4))); \ + assert_se(x == lit(8)); \ + if (IS_SIGNED_INTEGER_TYPE(type)) { \ + assert_se(MUL_SAFE(&x, lit(2), lit(-4))); \ + assert_se(x == lit(-8)); \ + } \ + assert_se(MUL_SAFE(&x, lit(5), lit(0))); \ + assert_se(x == lit(0)); \ + assert_se(MUL_SAFE(&x, min, lit(1))); \ + assert_se(x == min); \ + if (IS_SIGNED_INTEGER_TYPE(type)) \ + assert_se(!MUL_SAFE(&x, min, lit(2))); \ + assert_se(MUL_SAFE(&x, max, lit(1))); \ + assert_se(x == max); \ + assert_se(!MUL_SAFE(&x, max, lit(2))); \ + \ + x = lit(2); \ + assert_se(MUL_ASSIGN_SAFE(&x, lit(4))); \ + assert_se(x == lit(8)); \ + if (IS_SIGNED_INTEGER_TYPE(type)) { \ + assert_se(MUL_ASSIGN_SAFE(&x, lit(-1))); \ + assert_se(x == lit(-8)); \ + } \ + assert_se(MUL_ASSIGN_SAFE(&x, lit(0))); \ + assert_se(x == lit(0)); \ + x = min; \ + assert_se(MUL_ASSIGN_SAFE(&x, lit(1))); \ + assert_se(x == min); \ + if IS_SIGNED_INTEGER_TYPE(type) \ + assert_se(!MUL_ASSIGN_SAFE(&x, lit(2))); \ + x = max; \ + assert_se(MUL_ASSIGN_SAFE(&x, lit(1))); \ + assert_se(x == max); \ + assert_se(!MUL_ASSIGN_SAFE(&x, lit(2))); \ + }) + +TEST(overflow_safe_math) { + int64_t i; + uint64_t u, *p; + + /* basic tests */ + TEST_OVERFLOW_MATH_BY_TYPE(int8_t, INT8_MIN, INT8_MAX, INT8_C); + TEST_OVERFLOW_MATH_BY_TYPE(int16_t, INT16_MIN, INT16_MAX, INT16_C); + TEST_OVERFLOW_MATH_BY_TYPE(int32_t, INT32_MIN, INT32_MAX, INT32_C); + TEST_OVERFLOW_MATH_BY_TYPE(int64_t, INT64_MIN, INT64_MAX, INT64_C); + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wtype-limits" /* Otherwise the compiler complains about comparisons to negative numbers always being false */ + TEST_OVERFLOW_MATH_BY_TYPE(uint8_t, UINT8_C(0), UINT8_MAX, UINT8_C); + TEST_OVERFLOW_MATH_BY_TYPE(uint16_t, UINT16_C(0), UINT16_MAX, UINT16_C); + TEST_OVERFLOW_MATH_BY_TYPE(uint32_t, UINT32_C(0), UINT32_MAX, UINT32_C); + TEST_OVERFLOW_MATH_BY_TYPE(uint64_t, UINT64_C(0), UINT64_MAX, UINT64_C); +#pragma GCC diagnostic pop + + /* make sure we handle pointers correctly */ + p = &u; + assert_se(ADD_SAFE(p, 35, 15) && (u == 50)); + assert_se(SUB_SAFE(p, 35, 15) && (u == 20)); + assert_se(MUL_SAFE(p, 5, 10) && (u == 50)); + assert_se(INC_SAFE(p, 10) && (u == 60)); + assert_se(DEC_SAFE(p, 10) && (u == 50)); + assert_se(MUL_ASSIGN_SAFE(p, 3) && (u == 150)); + assert_se(!ADD_SAFE(p, UINT64_MAX, 1)); + assert_se(!SUB_SAFE(p, 0, 1)); + + /* cross-type sanity checks */ + assert_se(ADD_SAFE(&i, INT32_MAX, 1)); + assert_se(SUB_SAFE(&i, INT32_MIN, 1)); + assert_se(!ADD_SAFE(&i, UINT64_MAX, 0)); + assert_se(ADD_SAFE(&u, INT32_MAX, 1)); + assert_se(MUL_SAFE(&u, INT32_MAX, 2)); +} + TEST(DIV_ROUND_UP) { int div; @@ -221,92 +370,13 @@ TEST(IN_SET) { assert_se(!IN_SET(t.x, 2, 3, 4)); } -TEST(FOREACH_POINTER) { - int a, b, c, *i; - size_t k = 0; - - FOREACH_POINTER(i, &a, &b, &c) { - switch (k) { - - case 0: - assert_se(i == &a); - break; - - case 1: - assert_se(i == &b); - break; - - case 2: - assert_se(i == &c); - break; - - default: - assert_not_reached(); - break; - } - - k++; - } - - assert_se(k == 3); - - FOREACH_POINTER(i, &b) { - assert_se(k == 3); - assert_se(i == &b); - k = 4; - } - - assert_se(k == 4); - - FOREACH_POINTER(i, NULL, &c, NULL, &b, NULL, &a, NULL) { - switch (k) { - - case 4: - assert_se(i == NULL); - break; - - case 5: - assert_se(i == &c); - break; - - case 6: - assert_se(i == NULL); - break; - - case 7: - assert_se(i == &b); - break; - - case 8: - assert_se(i == NULL); - break; - - case 9: - assert_se(i == &a); - break; - - case 10: - assert_se(i == NULL); - break; - - default: - assert_not_reached(); - break; - } - - k++; - } - - assert_se(k == 11); -} - -TEST(FOREACH_VA_ARGS) { +TEST(FOREACH_ARGUMENT) { size_t i; i = 0; uint8_t u8, u8_1 = 1, u8_2 = 2, u8_3 = 3; - VA_ARGS_FOREACH(u8, u8_2, 8, 0xff, u8_1, u8_3, 0, 1) { - switch(i++) { + FOREACH_ARGUMENT(u8, u8_2, 8, 0xff, u8_1, u8_3, 0, 1) { + switch (i++) { case 0: assert_se(u8 == u8_2); break; case 1: assert_se(u8 == 8); break; case 2: assert_se(u8 == 0xff); break; @@ -319,24 +389,24 @@ TEST(FOREACH_VA_ARGS) { } assert_se(i == 7); i = 0; - VA_ARGS_FOREACH(u8, 0) { + FOREACH_ARGUMENT(u8, 0) { assert_se(u8 == 0); assert_se(i++ == 0); } assert_se(i == 1); i = 0; - VA_ARGS_FOREACH(u8, 0xff) { + FOREACH_ARGUMENT(u8, 0xff) { assert_se(u8 == 0xff); assert_se(i++ == 0); } assert_se(i == 1); - VA_ARGS_FOREACH(u8) + FOREACH_ARGUMENT(u8) assert_se(false); i = 0; uint32_t u32, u32_1 = 0xffff0000, u32_2 = 10, u32_3 = 0xffff; - VA_ARGS_FOREACH(u32, 1, 100, u32_2, 1000, u32_3, u32_1, 1, 0) { - switch(i++) { + FOREACH_ARGUMENT(u32, 1, 100, u32_2, 1000, u32_3, u32_1, 1, 0) { + switch (i++) { case 0: assert_se(u32 == 1); break; case 1: assert_se(u32 == 100); break; case 2: assert_se(u32 == u32_2); break; @@ -350,24 +420,24 @@ TEST(FOREACH_VA_ARGS) { } assert_se(i == 8); i = 0; - VA_ARGS_FOREACH(u32, 0) { + FOREACH_ARGUMENT(u32, 0) { assert_se(u32 == 0); assert_se(i++ == 0); } assert_se(i == 1); i = 0; - VA_ARGS_FOREACH(u32, 1000) { + FOREACH_ARGUMENT(u32, 1000) { assert_se(u32 == 1000); assert_se(i++ == 0); } assert_se(i == 1); - VA_ARGS_FOREACH(u32) + FOREACH_ARGUMENT(u32) assert_se(false); i = 0; uint64_t u64, u64_1 = 0xffffffffffffffff, u64_2 = 50, u64_3 = 0xffff; - VA_ARGS_FOREACH(u64, 44, 0, u64_3, 100, u64_2, u64_1, 50000) { - switch(i++) { + FOREACH_ARGUMENT(u64, 44, 0, u64_3, 100, u64_2, u64_1, 50000) { + switch (i++) { case 0: assert_se(u64 == 44); break; case 1: assert_se(u64 == 0); break; case 2: assert_se(u64 == u64_3); break; @@ -380,18 +450,18 @@ TEST(FOREACH_VA_ARGS) { } assert_se(i == 7); i = 0; - VA_ARGS_FOREACH(u64, 0) { + FOREACH_ARGUMENT(u64, 0) { assert_se(u64 == 0); assert_se(i++ == 0); } assert_se(i == 1); i = 0; - VA_ARGS_FOREACH(u64, 0xff00ff00000000) { + FOREACH_ARGUMENT(u64, 0xff00ff00000000) { assert_se(u64 == 0xff00ff00000000); assert_se(i++ == 0); } assert_se(i == 1); - VA_ARGS_FOREACH(u64) + FOREACH_ARGUMENT(u64) assert_se(false); struct test { @@ -405,8 +475,8 @@ TEST(FOREACH_VA_ARGS) { s_2 = { .a = 100000, .b = 'z', }, s_3 = { .a = 0xff, .b = 'q', }, s_4 = { .a = 1, .b = 'x', }; - VA_ARGS_FOREACH(s, s_1, (struct test){ .a = 10, .b = 'd', }, s_2, (struct test){}, s_3, s_4) { - switch(i++) { + FOREACH_ARGUMENT(s, s_1, (struct test){ .a = 10, .b = 'd', }, s_2, (struct test){}, s_3, s_4) { + switch (i++) { case 0: assert_se(s.a == 0 ); assert_se(s.b == 'c'); break; case 1: assert_se(s.a == 10 ); assert_se(s.b == 'd'); break; case 2: assert_se(s.a == 100000); assert_se(s.b == 'z'); break; @@ -418,69 +488,69 @@ TEST(FOREACH_VA_ARGS) { } assert_se(i == 6); i = 0; - VA_ARGS_FOREACH(s, (struct test){ .a = 1, .b = 'A', }) { + FOREACH_ARGUMENT(s, (struct test){ .a = 1, .b = 'A', }) { assert_se(s.a == 1); assert_se(s.b == 'A'); assert_se(i++ == 0); } assert_se(i == 1); - VA_ARGS_FOREACH(s) + FOREACH_ARGUMENT(s) assert_se(false); i = 0; struct test *p, *p_1 = &s_1, *p_2 = &s_2, *p_3 = &s_3, *p_4 = &s_4; - VA_ARGS_FOREACH(p, p_1, NULL, p_2, p_3, NULL, p_4, NULL) { - switch(i++) { + FOREACH_ARGUMENT(p, p_1, NULL, p_2, p_3, NULL, p_4, NULL) { + switch (i++) { case 0: assert_se(p == p_1); break; - case 1: assert_se(p == NULL); break; + case 1: ASSERT_NULL(p); break; case 2: assert_se(p == p_2); break; case 3: assert_se(p == p_3); break; - case 4: assert_se(p == NULL); break; + case 4: ASSERT_NULL(p); break; case 5: assert_se(p == p_4); break; - case 6: assert_se(p == NULL); break; + case 6: ASSERT_NULL(p); break; default: assert_se(false); } } assert_se(i == 7); i = 0; - VA_ARGS_FOREACH(p, p_3) { + FOREACH_ARGUMENT(p, p_3) { assert_se(p == p_3); assert_se(i++ == 0); } assert_se(i == 1); - VA_ARGS_FOREACH(p) + FOREACH_ARGUMENT(p) assert_se(false); i = 0; void *v, *v_1 = p_1, *v_2 = p_2, *v_3 = p_3; uint32_t *u32p = &u32; - VA_ARGS_FOREACH(v, v_1, NULL, u32p, v_3, p_2, p_4, v_2, NULL) { - switch(i++) { + FOREACH_ARGUMENT(v, v_1, NULL, u32p, v_3, p_2, p_4, v_2, NULL) { + switch (i++) { case 0: assert_se(v == v_1); break; - case 1: assert_se(v == NULL); break; + case 1: ASSERT_NULL(v); break; case 2: assert_se(v == u32p); break; case 3: assert_se(v == v_3); break; case 4: assert_se(v == p_2); break; case 5: assert_se(v == p_4); break; case 6: assert_se(v == v_2); break; - case 7: assert_se(v == NULL); break; + case 7: ASSERT_NULL(v); break; default: assert_se(false); } } assert_se(i == 8); i = 0; - VA_ARGS_FOREACH(v, NULL) { - assert_se(v == NULL); + FOREACH_ARGUMENT(v, NULL) { + ASSERT_NULL(v); assert_se(i++ == 0); } assert_se(i == 1); i = 0; - VA_ARGS_FOREACH(v, v_1) { + FOREACH_ARGUMENT(v, v_1) { assert_se(v == v_1); assert_se(i++ == 0); } assert_se(i == 1); - VA_ARGS_FOREACH(v) + FOREACH_ARGUMENT(v) assert_se(false); } @@ -1037,4 +1107,80 @@ TEST(u64_multiply_safe) { assert_se(u64_multiply_safe(UINT64_MAX, UINT64_MAX) == 0); } +TEST(ASSERT) { + char *null = NULL; + + ASSERT_OK(0); + ASSERT_OK(255); + ASSERT_OK(printf("Hello world\n")); + ASSERT_SIGNAL(ASSERT_OK(-1), SIGABRT); + ASSERT_SIGNAL(ASSERT_OK(-ENOANO), SIGABRT); + + ASSERT_OK_ERRNO(0 >= 0); + ASSERT_OK_ERRNO(255 >= 0); + ASSERT_OK_ERRNO(printf("Hello world\n")); + ASSERT_SIGNAL(ASSERT_OK_ERRNO(-1), SIGABRT); + ASSERT_SIGNAL(ASSERT_OK_ERRNO(-ENOANO), SIGABRT); + + ASSERT_ERROR(-ENOENT, ENOENT); + ASSERT_ERROR(RET_NERRNO(mkdir("/i/will/fail/with/enoent", 666)), ENOENT); + ASSERT_SIGNAL(ASSERT_ERROR(0, ENOENT), SIGABRT); + ASSERT_SIGNAL(ASSERT_ERROR(RET_NERRNO(mkdir("/i/will/fail/with/enoent", 666)), ENOANO), SIGABRT); + + errno = ENOENT; + ASSERT_ERROR_ERRNO(-1, ENOENT); + errno = 0; + ASSERT_ERROR_ERRNO(mkdir("/i/will/fail/with/enoent", 666), ENOENT); + ASSERT_SIGNAL(ASSERT_ERROR_ERRNO(0, ENOENT), SIGABRT); + errno = 0; + ASSERT_SIGNAL(ASSERT_ERROR_ERRNO(mkdir("/i/will/fail/with/enoent", 666), ENOANO), SIGABRT); + + ASSERT_TRUE(true); + ASSERT_TRUE(255); + ASSERT_TRUE(getpid()); + ASSERT_SIGNAL(ASSERT_TRUE(1 == 0), SIGABRT); + + ASSERT_FALSE(false); + ASSERT_FALSE(1 == 0); + ASSERT_SIGNAL(ASSERT_FALSE(1 > 0), SIGABRT); + + ASSERT_NULL(NULL); + ASSERT_SIGNAL(ASSERT_NULL(signal_to_string(SIGINT)), SIGABRT); + + ASSERT_NOT_NULL(signal_to_string(SIGTERM)); + ASSERT_SIGNAL(ASSERT_NOT_NULL(NULL), SIGABRT); + + ASSERT_STREQ(NULL, null); + ASSERT_STREQ("foo", "foo"); + ASSERT_SIGNAL(ASSERT_STREQ(null, "bar"), SIGABRT); + ASSERT_SIGNAL(ASSERT_STREQ("foo", "bar"), SIGABRT); + + ASSERT_EQ(0, 0); + ASSERT_EQ(-1, -1); + ASSERT_SIGNAL(ASSERT_EQ(255, -1), SIGABRT); + + ASSERT_GE(0, 0); + ASSERT_GE(1, -1); + ASSERT_SIGNAL(ASSERT_GE(-1, 1), SIGABRT); + + ASSERT_LE(0, 0); + ASSERT_LE(-1, 1); + ASSERT_SIGNAL(ASSERT_LE(1, -1), SIGABRT); + + ASSERT_NE(0, (int64_t) UINT_MAX); + ASSERT_NE(-1, 1); + ASSERT_SIGNAL(ASSERT_NE(0, 0), SIGABRT); + ASSERT_SIGNAL(ASSERT_NE(-1, -1), SIGABRT); + + ASSERT_GT(1, 0); + ASSERT_GT(1, -1); + ASSERT_SIGNAL(ASSERT_GT(0, 0), SIGABRT); + ASSERT_SIGNAL(ASSERT_GT(-1, 1), SIGABRT); + + ASSERT_LT(0, 1); + ASSERT_LT(-1, 1); + ASSERT_SIGNAL(ASSERT_LT(0, 0), SIGABRT); + ASSERT_SIGNAL(ASSERT_LT(1, -1), SIGABRT); +} + DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-manager.c b/src/test/test-manager.c deleted file mode 100644 index 76e094b..0000000 --- a/src/test/test-manager.c +++ /dev/null @@ -1,19 +0,0 @@ -/* SPDX-License-Identifier: LGPL-2.1-or-later */ - -#include "manager.h" -#include "tests.h" - -TEST(manager_taint_string) { - Manager m = {}; - - _cleanup_free_ char *a = manager_taint_string(&m); - assert_se(a); - log_debug("taint string: '%s'", a); - - if (cg_all_unified() == 0) - assert_se(strstr(a, "cgroupsv1")); - else - assert_se(!strstr(a, "cgroupsv1")); -} - -DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-mempool.c b/src/test/test-mempool.c index d3bc173..1f071db 100644 --- a/src/test/test-mempool.c +++ b/src/test/test-mempool.c @@ -35,7 +35,7 @@ TEST(mempool_trim) { assert_se(!a[x] || a[x]->value == x); if (a[x]) - n_freed ++; + n_freed++; a[x] = mempool_free_tile(&test_mempool, a[x]); } @@ -46,7 +46,7 @@ TEST(mempool_trim) { for (size_t i = 2; i < NN; i += 3) { assert_se(!a[i] || a[i]->value == i); if (a[i]) - n_freed ++; + n_freed++; a[i] = mempool_free_tile(&test_mempool, a[i]); } @@ -66,7 +66,7 @@ TEST(mempool_trim) { for (size_t i = 0; i < NN; i += 1) { assert_se(!a[i] || a[i]->value == i); if (a[i]) - n_freed ++; + n_freed++; a[i] = mempool_free_tile(&test_mempool, a[i]); } @@ -77,7 +77,7 @@ TEST(mempool_trim) { for (size_t i = 0; i < NN; i += 1) { assert_se(!b[i] || b[i]->value == ~(uint64_t) i); if (b[i]) - n_freed ++; + n_freed++; b[i] = mempool_free_tile(&test_mempool, b[i]); } diff --git a/src/test/test-mempress.c b/src/test/test-mempress.c index 26ce4ce..44f1f4c 100644 --- a/src/test/test-mempress.c +++ b/src/test/test-mempress.c @@ -40,7 +40,7 @@ static void *fake_pressure_thread(void *p) { assert_se(cfd >= 0); char buf[STRLEN("hello")+1] = {}; assert_se(read(cfd, buf, sizeof(buf)-1) == sizeof(buf)-1); - assert_se(streq(buf, "hello")); + ASSERT_STREQ(buf, "hello"); assert_se(write(cfd, &(const char) { 'z' }, 1) == 1); return 0; @@ -220,7 +220,7 @@ TEST(real_pressure) { assert_se(sd_bus_message_read(reply, "o", &object) >= 0); - assert_se(bus_wait_for_jobs_one(w, object, /* quiet= */ false, /* extra_args= */ NULL) >= 0); + assert_se(bus_wait_for_jobs_one(w, object, /* flags= */ BUS_WAIT_JOBS_LOG_ERROR, /* extra_args= */ NULL) >= 0); assert_se(sd_event_default(&e) >= 0); @@ -233,7 +233,7 @@ TEST(real_pressure) { _exit(EXIT_SUCCESS); } - assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD, -1) >= 0); + assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD) >= 0); assert_se(sd_event_add_child(e, &cs, pid, WEXITED, real_pressure_child_callback, NULL) >= 0); assert_se(sd_event_source_set_child_process_own(cs, true) >= 0); diff --git a/src/test/test-memstream-util.c b/src/test/test-memstream-util.c index 254bdca..b8cc856 100644 --- a/src/test/test-memstream-util.c +++ b/src/test/test-memstream-util.c @@ -17,7 +17,7 @@ TEST(memstream_empty) { assert_se(memstream_init(&m)); assert_se(memstream_finalize(&m, &buf, &sz) >= 0); - assert_se(streq(buf, "")); + ASSERT_STREQ(buf, ""); assert_se(sz == 0); } @@ -32,7 +32,7 @@ TEST(memstream) { fputs("おはよう!", f); fputs(u8"😀😀😀", f); assert_se(memstream_finalize(&m, &buf, &sz) >= 0); - assert_se(streq(buf, u8"hogeおはよう!😀😀😀")); + ASSERT_STREQ(buf, u8"hogeおはよう!😀😀😀"); assert_se(sz == strlen(u8"hogeおはよう!😀😀😀")); buf = mfree(buf); @@ -40,7 +40,7 @@ TEST(memstream) { assert_se(f = memstream_init(&m)); fputs("second", f); assert_se(memstream_finalize(&m, &buf, &sz) >= 0); - assert_se(streq(buf, "second")); + ASSERT_STREQ(buf, "second"); assert_se(sz == strlen("second")); } diff --git a/src/test/test-mkdir.c b/src/test/test-mkdir.c index 4820b32..ef00729 100644 --- a/src/test/test-mkdir.c +++ b/src/test/test-mkdir.c @@ -96,7 +96,7 @@ TEST(mkdir_p_root) { assert_se(mkdtemp_malloc("/tmp/test-mkdir-XXXXXX", &tmp) >= 0); assert_se(p = path_join(tmp, "run/aaa/bbb")); - assert_se(mkdir_p_root(tmp, "/run/aaa/bbb", UID_INVALID, GID_INVALID, 0755, NULL) >= 0); + assert_se(mkdir_p_root(tmp, "/run/aaa/bbb", UID_INVALID, GID_INVALID, 0755) >= 0); assert_se(is_dir(p, false) > 0); assert_se(is_dir(p, true) > 0); @@ -109,18 +109,18 @@ TEST(mkdir_p_root) { p = mfree(p); assert_se(p = path_join(tmp, "var/run/hoge/foo/baz")); - assert_se(mkdir_p_root(tmp, "/var/run/hoge/foo/baz", UID_INVALID, GID_INVALID, 0755, NULL) >= 0); + assert_se(mkdir_p_root(tmp, "/var/run/hoge/foo/baz", UID_INVALID, GID_INVALID, 0755) >= 0); assert_se(is_dir(p, false) > 0); assert_se(is_dir(p, true) > 0); p = mfree(p); assert_se(p = path_join(tmp, "not-exists")); - assert_se(mkdir_p_root(p, "/aaa", UID_INVALID, GID_INVALID, 0755, NULL) == -ENOENT); + assert_se(mkdir_p_root(p, "/aaa", UID_INVALID, GID_INVALID, 0755) == -ENOENT); p = mfree(p); assert_se(p = path_join(tmp, "regular-file")); assert_se(touch(p) >= 0); - assert_se(mkdir_p_root(p, "/aaa", UID_INVALID, GID_INVALID, 0755, NULL) == -ENOTDIR); + assert_se(mkdir_p_root(p, "/aaa", UID_INVALID, GID_INVALID, 0755) == -ENOTDIR); /* FIXME: The tests below do not work. p = mfree(p); @@ -138,4 +138,31 @@ TEST(mkdir_p_root) { */ } +TEST(mkdir_p_root_full) { + _cleanup_(rm_rf_physical_and_freep) char *tmp = NULL; + _cleanup_free_ char *p = NULL; + struct stat st; + + ASSERT_OK(mkdtemp_malloc("/tmp/test-mkdir-XXXXXX", &tmp)); + + ASSERT_NOT_NULL(p = path_join(tmp, "foo")); + ASSERT_OK(mkdir_p_root_full(tmp, "/foo", UID_INVALID, GID_INVALID, 0755, 2 * USEC_PER_SEC, NULL)); + ASSERT_GT(is_dir(p, false), 0); + ASSERT_GT(is_dir(p, true), 0); + ASSERT_OK_ERRNO(stat(p, &st)); + ASSERT_EQ(st.st_mtim.tv_sec, 2); + ASSERT_EQ(st.st_atim.tv_sec, 2); + + p = mfree(p); + ASSERT_NOT_NULL(p = path_join(tmp, "dir-not-exists/foo")); + ASSERT_OK(mkdir_p_root_full(NULL, p, UID_INVALID, GID_INVALID, 0755, 90 * USEC_PER_HOUR, NULL)); + ASSERT_GT(is_dir(p, false), 0); + ASSERT_GT(is_dir(p, true), 0); + p = mfree(p); + ASSERT_NOT_NULL(p = path_join(tmp, "dir-not-exists")); + ASSERT_OK_ERRNO(stat(p, &st)); + ASSERT_EQ(st.st_mtim.tv_sec, 90 * 60 * 60); + ASSERT_EQ(st.st_atim.tv_sec, 90 * 60 * 60); +} + DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-mount-util.c b/src/test/test-mount-util.c index c3d0acb..4f6da39 100644 --- a/src/test/test-mount-util.c +++ b/src/test/test-mount-util.c @@ -31,56 +31,56 @@ TEST(mount_option_mangle) { assert_se(mount_option_mangle(NULL, MS_RDONLY|MS_NOSUID, &f, &opts) == 0); assert_se(f == (MS_RDONLY|MS_NOSUID)); - assert_se(opts == NULL); + ASSERT_NULL(opts); assert_se(mount_option_mangle("", MS_RDONLY|MS_NOSUID, &f, &opts) == 0); assert_se(f == (MS_RDONLY|MS_NOSUID)); - assert_se(opts == NULL); + ASSERT_NULL(opts); assert_se(mount_option_mangle("ro,nosuid,nodev,noexec", 0, &f, &opts) == 0); assert_se(f == (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC)); - assert_se(opts == NULL); + ASSERT_NULL(opts); assert_se(mount_option_mangle("ro,nosuid,nodev,noexec,mode=0755", 0, &f, &opts) == 0); assert_se(f == (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC)); - assert_se(streq(opts, "mode=0755")); + ASSERT_STREQ(opts, "mode=0755"); opts = mfree(opts); assert_se(mount_option_mangle("rw,nosuid,foo,hogehoge,nodev,mode=0755", 0, &f, &opts) == 0); assert_se(f == (MS_NOSUID|MS_NODEV)); - assert_se(streq(opts, "foo,hogehoge,mode=0755")); + ASSERT_STREQ(opts, "foo,hogehoge,mode=0755"); opts = mfree(opts); assert_se(mount_option_mangle("rw,nosuid,nodev,noexec,relatime,net_cls,net_prio", MS_RDONLY, &f, &opts) == 0); assert_se(f == (MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_RELATIME)); - assert_se(streq(opts, "net_cls,net_prio")); + ASSERT_STREQ(opts, "net_cls,net_prio"); opts = mfree(opts); assert_se(mount_option_mangle("rw,nosuid,nodev,relatime,size=1630748k,mode=0700,uid=1000,gid=1000", MS_RDONLY, &f, &opts) == 0); assert_se(f == (MS_NOSUID|MS_NODEV|MS_RELATIME)); - assert_se(streq(opts, "size=1630748k,mode=0700,uid=1000,gid=1000")); + ASSERT_STREQ(opts, "size=1630748k,mode=0700,uid=1000,gid=1000"); opts = mfree(opts); assert_se(mount_option_mangle("size=1630748k,rw,gid=1000,,,nodev,relatime,,mode=0700,nosuid,uid=1000", MS_RDONLY, &f, &opts) == 0); assert_se(f == (MS_NOSUID|MS_NODEV|MS_RELATIME)); - assert_se(streq(opts, "size=1630748k,gid=1000,mode=0700,uid=1000")); + ASSERT_STREQ(opts, "size=1630748k,gid=1000,mode=0700,uid=1000"); opts = mfree(opts); assert_se(mount_option_mangle("rw,exec,size=8143984k,nr_inodes=2035996,mode=0755", MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV, &f, &opts) == 0); assert_se(f == (MS_NOSUID|MS_NODEV)); - assert_se(streq(opts, "size=8143984k,nr_inodes=2035996,mode=0755")); + ASSERT_STREQ(opts, "size=8143984k,nr_inodes=2035996,mode=0755"); opts = mfree(opts); assert_se(mount_option_mangle("rw,relatime,fmask=0022,,,dmask=0022", MS_RDONLY, &f, &opts) == 0); assert_se(f == MS_RELATIME); - assert_se(streq(opts, "fmask=0022,dmask=0022")); + ASSERT_STREQ(opts, "fmask=0022,dmask=0022"); opts = mfree(opts); assert_se(mount_option_mangle("rw,relatime,fmask=0022,dmask=0022,\"hogehoge", MS_RDONLY, &f, &opts) < 0); assert_se(mount_option_mangle("mode=01777,size=10%,nr_inodes=400k,uid=496107520,gid=496107520,context=\"system_u:object_r:svirt_sandbox_file_t:s0:c0,c1\"", 0, &f, &opts) == 0); assert_se(f == 0); - assert_se(streq(opts, "mode=01777,size=10%,nr_inodes=400k,uid=496107520,gid=496107520,context=\"system_u:object_r:svirt_sandbox_file_t:s0:c0,c1\"")); + ASSERT_STREQ(opts, "mode=01777,size=10%,nr_inodes=400k,uid=496107520,gid=496107520,context=\"system_u:object_r:svirt_sandbox_file_t:s0:c0,c1\""); opts = mfree(opts); } @@ -91,7 +91,7 @@ static void test_mount_flags_to_string_one(unsigned long flags, const char *expe r = mount_flags_to_string(flags, &x); log_info("flags: %#lX → %d/\"%s\"", flags, r, strnull(x)); assert_se(r >= 0); - assert_se(streq(x, expected)); + ASSERT_STREQ(x, expected); } TEST(mount_flags_to_string) { @@ -213,6 +213,25 @@ TEST(bind_remount_one) { _exit(EXIT_SUCCESS); } + assert_se(wait_for_terminate_and_check("test-remount-one-with-mountinfo", pid, WAIT_LOG) == EXIT_SUCCESS); + + pid = fork(); + assert_se(pid >= 0); + + if (pid == 0) { + /* child */ + + assert_se(detach_mount_namespace() >= 0); + + assert_se(bind_remount_one("/run", MS_RDONLY, MS_RDONLY) >= 0); + assert_se(bind_remount_one("/run", MS_NOEXEC, MS_RDONLY|MS_NOEXEC) >= 0); + assert_se(bind_remount_one("/proc/idontexist", MS_RDONLY, MS_RDONLY) == -ENOENT); + assert_se(bind_remount_one("/proc/self", MS_RDONLY, MS_RDONLY) == -EINVAL); + assert_se(bind_remount_one("/", MS_RDONLY, MS_RDONLY) >= 0); + + _exit(EXIT_SUCCESS); + } + assert_se(wait_for_terminate_and_check("test-remount-one", pid, WAIT_LOG) == EXIT_SUCCESS); } @@ -276,7 +295,17 @@ TEST(make_mount_switch_root) { assert_se(s); assert_se(touch(s) >= 0); - for (int force_ms_move = 0; force_ms_move < 2; force_ms_move++) { + struct { + const char *path; + bool force_ms_move; + } table[] = { + { t, false }, + { t, true }, + { "/", false }, + { "/", true }, + }; + + FOREACH_ELEMENT(i, table) { r = safe_fork("(switch-root)", FORK_RESET_SIGNALS | FORK_CLOSE_ALL_FDS | @@ -290,12 +319,14 @@ TEST(make_mount_switch_root) { assert_se(r >= 0); if (r == 0) { - assert_se(make_mount_point(t) >= 0); - assert_se(mount_switch_root_full(t, /* mount_propagation_flag= */ 0, force_ms_move) >= 0); + assert_se(make_mount_point(i->path) >= 0); + assert_se(mount_switch_root_full(i->path, /* mount_propagation_flag= */ 0, i->force_ms_move) >= 0); - assert_se(access(ASSERT_PTR(strrchr(s, '/')), F_OK) >= 0); /* absolute */ - assert_se(access(ASSERT_PTR(strrchr(s, '/')) + 1, F_OK) >= 0); /* relative */ - assert_se(access(s, F_OK) < 0 && errno == ENOENT); /* doesn't exist in our new environment */ + if (!path_equal(i->path, "/")) { + assert_se(access(ASSERT_PTR(strrchr(s, '/')), F_OK) >= 0); /* absolute */ + assert_se(access(ASSERT_PTR(strrchr(s, '/')) + 1, F_OK) >= 0); /* relative */ + assert_se(access(s, F_OK) < 0 && errno == ENOENT); /* doesn't exist in our new environment */ + } _exit(EXIT_SUCCESS); } @@ -327,7 +358,7 @@ TEST(umount_recursive) { int r; - FOREACH_ARRAY(t, test_table, ELEMENTSOF(test_table)) { + FOREACH_ELEMENT(t, test_table) { r = safe_fork("(umount-rec)", FORK_RESET_SIGNALS | @@ -496,11 +527,11 @@ TEST(bind_mount_submounts) { free(x); assert_se(x = path_join(b, "x")); - assert_se(path_is_mount_point(x, NULL, 0) > 0); + assert_se(path_is_mount_point(x) > 0); free(x); assert_se(x = path_join(b, "y")); - assert_se(path_is_mount_point(x, NULL, 0) > 0); + assert_se(path_is_mount_point(x) > 0); assert_se(umount_recursive(a, 0) >= 0); assert_se(umount_recursive(b, 0) >= 0); diff --git a/src/test/test-mountpoint-util.c b/src/test/test-mountpoint-util.c index ff447c6..85c0859 100644 --- a/src/test/test-mountpoint-util.c +++ b/src/test/test-mountpoint-util.c @@ -33,7 +33,7 @@ static void test_mount_propagation_flag_one(const char *name, int ret, unsigned if (isempty(name)) assert_se(isempty(c)); else - assert_se(streq(c, name)); + ASSERT_STREQ(c, name); } } @@ -69,7 +69,7 @@ TEST(mnt_id) { assert_se(sscanf(line, "%i %*s %*s %*s %ms", &mnt_id, &path) == 2); #if HAS_FEATURE_MEMORY_SANITIZER /* We don't know the length of the string, so we need to unpoison it one char at a time */ - for (const char *c = path; ;c++) { + for (const char *c = path; ; c++) { msan_unpoison(c, 1); if (!*c) break; @@ -101,7 +101,7 @@ TEST(mnt_id) { * See #11505. */ assert_se(q = hashmap_get(h, INT_TO_PTR(mnt_id2))); - assert_se((r = path_is_mount_point(p, NULL, 0)) >= 0); + assert_se((r = path_is_mount_point_full(p, NULL, 0)) >= 0); if (r == 0) { /* If the path is not a mount point anymore, then it must be a sub directory of * the path corresponds to mnt_id2. */ @@ -123,25 +123,20 @@ TEST(path_is_mount_point) { _cleanup_free_ char *dir1 = NULL, *dir1file = NULL, *dirlink1 = NULL, *dirlink1file = NULL; _cleanup_free_ char *dir2 = NULL, *dir2file = NULL; - assert_se(path_is_mount_point("/", NULL, AT_SYMLINK_FOLLOW) > 0); - assert_se(path_is_mount_point("/", NULL, 0) > 0); - assert_se(path_is_mount_point("//", NULL, AT_SYMLINK_FOLLOW) > 0); - assert_se(path_is_mount_point("//", NULL, 0) > 0); + assert_se(path_is_mount_point_full("/", NULL, AT_SYMLINK_FOLLOW) > 0); + assert_se(path_is_mount_point_full("/", NULL, 0) > 0); + assert_se(path_is_mount_point_full("//", NULL, AT_SYMLINK_FOLLOW) > 0); + assert_se(path_is_mount_point_full("//", NULL, 0) > 0); - assert_se(path_is_mount_point("/proc", NULL, AT_SYMLINK_FOLLOW) > 0); - assert_se(path_is_mount_point("/proc", NULL, 0) > 0); - assert_se(path_is_mount_point("/proc/", NULL, AT_SYMLINK_FOLLOW) > 0); - assert_se(path_is_mount_point("/proc/", NULL, 0) > 0); + assert_se(path_is_mount_point_full("/proc", NULL, AT_SYMLINK_FOLLOW) > 0); + assert_se(path_is_mount_point_full("/proc", NULL, 0) > 0); + assert_se(path_is_mount_point_full("/proc/", NULL, AT_SYMLINK_FOLLOW) > 0); + assert_se(path_is_mount_point_full("/proc/", NULL, 0) > 0); - assert_se(path_is_mount_point("/proc/1", NULL, AT_SYMLINK_FOLLOW) == 0); - assert_se(path_is_mount_point("/proc/1", NULL, 0) == 0); - assert_se(path_is_mount_point("/proc/1/", NULL, AT_SYMLINK_FOLLOW) == 0); - assert_se(path_is_mount_point("/proc/1/", NULL, 0) == 0); - - assert_se(path_is_mount_point("/sys", NULL, AT_SYMLINK_FOLLOW) > 0); - assert_se(path_is_mount_point("/sys", NULL, 0) > 0); - assert_se(path_is_mount_point("/sys/", NULL, AT_SYMLINK_FOLLOW) > 0); - assert_se(path_is_mount_point("/sys/", NULL, 0) > 0); + assert_se(path_is_mount_point_full("/proc/1", NULL, AT_SYMLINK_FOLLOW) == 0); + assert_se(path_is_mount_point_full("/proc/1", NULL, 0) == 0); + assert_se(path_is_mount_point_full("/proc/1/", NULL, AT_SYMLINK_FOLLOW) == 0); + assert_se(path_is_mount_point_full("/proc/1/", NULL, 0) == 0); /* we'll create a hierarchy of different kinds of dir/file/link * layouts: @@ -157,7 +152,7 @@ TEST(path_is_mount_point) { */ /* file mountpoints */ - assert_se(mkdtemp(tmp_dir) != NULL); + ASSERT_NOT_NULL(mkdtemp(tmp_dir)); file1 = path_join(tmp_dir, "file1"); assert_se(file1); file2 = path_join(tmp_dir, "file2"); @@ -175,10 +170,10 @@ TEST(path_is_mount_point) { assert_se(link1); assert_se(symlink("file2", link2) == 0); - assert_se(path_is_mount_point(file1, NULL, AT_SYMLINK_FOLLOW) == 0); - assert_se(path_is_mount_point(file1, NULL, 0) == 0); - assert_se(path_is_mount_point(link1, NULL, AT_SYMLINK_FOLLOW) == 0); - assert_se(path_is_mount_point(link1, NULL, 0) == 0); + assert_se(path_is_mount_point_full(file1, NULL, AT_SYMLINK_FOLLOW) == 0); + assert_se(path_is_mount_point_full(file1, NULL, 0) == 0); + assert_se(path_is_mount_point_full(link1, NULL, AT_SYMLINK_FOLLOW) == 0); + assert_se(path_is_mount_point_full(link1, NULL, 0) == 0); /* directory mountpoints */ dir1 = path_join(tmp_dir, "dir1"); @@ -194,10 +189,10 @@ TEST(path_is_mount_point) { assert_se(dir2); assert_se(mkdir(dir2, 0755) == 0); - assert_se(path_is_mount_point(dir1, NULL, AT_SYMLINK_FOLLOW) == 0); - assert_se(path_is_mount_point(dir1, NULL, 0) == 0); - assert_se(path_is_mount_point(dirlink1, NULL, AT_SYMLINK_FOLLOW) == 0); - assert_se(path_is_mount_point(dirlink1, NULL, 0) == 0); + assert_se(path_is_mount_point_full(dir1, NULL, AT_SYMLINK_FOLLOW) == 0); + assert_se(path_is_mount_point_full(dir1, NULL, 0) == 0); + assert_se(path_is_mount_point_full(dirlink1, NULL, AT_SYMLINK_FOLLOW) == 0); + assert_se(path_is_mount_point_full(dirlink1, NULL, 0) == 0); /* file in subdirectory mountpoints */ dir1file = path_join(dir1, "file"); @@ -206,10 +201,10 @@ TEST(path_is_mount_point) { assert_se(fd > 0); close(fd); - assert_se(path_is_mount_point(dir1file, NULL, AT_SYMLINK_FOLLOW) == 0); - assert_se(path_is_mount_point(dir1file, NULL, 0) == 0); - assert_se(path_is_mount_point(dirlink1file, NULL, AT_SYMLINK_FOLLOW) == 0); - assert_se(path_is_mount_point(dirlink1file, NULL, 0) == 0); + assert_se(path_is_mount_point_full(dir1file, NULL, AT_SYMLINK_FOLLOW) == 0); + assert_se(path_is_mount_point_full(dir1file, NULL, 0) == 0); + assert_se(path_is_mount_point_full(dirlink1file, NULL, AT_SYMLINK_FOLLOW) == 0); + assert_se(path_is_mount_point_full(dirlink1file, NULL, 0) == 0); /* these tests will only work as root */ if (mount(file1, file2, NULL, MS_BIND, NULL) >= 0) { @@ -219,17 +214,17 @@ TEST(path_is_mount_point) { /* files */ /* capture results in vars, to avoid dangling mounts on failure */ log_info("%s: %s", __func__, file2); - rf = path_is_mount_point(file2, NULL, 0); - rt = path_is_mount_point(file2, NULL, AT_SYMLINK_FOLLOW); + rf = path_is_mount_point_full(file2, NULL, 0); + rt = path_is_mount_point_full(file2, NULL, AT_SYMLINK_FOLLOW); file2d = strjoina(file2, "/"); log_info("%s: %s", __func__, file2d); - rdf = path_is_mount_point(file2d, NULL, 0); - rdt = path_is_mount_point(file2d, NULL, AT_SYMLINK_FOLLOW); + rdf = path_is_mount_point_full(file2d, NULL, 0); + rdt = path_is_mount_point_full(file2d, NULL, AT_SYMLINK_FOLLOW); log_info("%s: %s", __func__, link2); - rlf = path_is_mount_point(link2, NULL, 0); - rlt = path_is_mount_point(link2, NULL, AT_SYMLINK_FOLLOW); + rlf = path_is_mount_point_full(link2, NULL, 0); + rlt = path_is_mount_point_full(link2, NULL, AT_SYMLINK_FOLLOW); assert_se(umount(file2) == 0); @@ -250,15 +245,15 @@ TEST(path_is_mount_point) { assert_se(mount(dir2, dir1, NULL, MS_BIND, NULL) >= 0); log_info("%s: %s", __func__, dir1); - rf = path_is_mount_point(dir1, NULL, 0); - rt = path_is_mount_point(dir1, NULL, AT_SYMLINK_FOLLOW); + rf = path_is_mount_point_full(dir1, NULL, 0); + rt = path_is_mount_point_full(dir1, NULL, AT_SYMLINK_FOLLOW); log_info("%s: %s", __func__, dirlink1); - rlf = path_is_mount_point(dirlink1, NULL, 0); - rlt = path_is_mount_point(dirlink1, NULL, AT_SYMLINK_FOLLOW); + rlf = path_is_mount_point_full(dirlink1, NULL, 0); + rlt = path_is_mount_point_full(dirlink1, NULL, AT_SYMLINK_FOLLOW); log_info("%s: %s", __func__, dirlink1file); /* its parent is a mount point, but not /file itself */ - rl1f = path_is_mount_point(dirlink1file, NULL, 0); - rl1t = path_is_mount_point(dirlink1file, NULL, AT_SYMLINK_FOLLOW); + rl1f = path_is_mount_point_full(dirlink1file, NULL, 0); + rl1t = path_is_mount_point_full(dirlink1file, NULL, AT_SYMLINK_FOLLOW); assert_se(umount(dir1) == 0); @@ -333,23 +328,23 @@ TEST(mount_option_supported) { r = mount_option_supported("tmpfs", "size", "64M"); log_info("tmpfs supports size=64M: %s (%i)", r < 0 ? "don't know" : yes_no(r), r); - assert_se(r > 0 || r == -EAGAIN || (r < 0 && ERRNO_IS_PRIVILEGE(r))); + assert_se(r > 0 || r == -EAGAIN || ERRNO_IS_NEG_PRIVILEGE(r)); r = mount_option_supported("ext4", "discard", NULL); log_info("ext4 supports discard: %s (%i)", r < 0 ? "don't know" : yes_no(r), r); - assert_se(r > 0 || r == -EAGAIN || (r < 0 && ERRNO_IS_PRIVILEGE(r))); + assert_se(r > 0 || r == -EAGAIN || ERRNO_IS_NEG_PRIVILEGE(r)); r = mount_option_supported("tmpfs", "idontexist", "64M"); log_info("tmpfs supports idontexist: %s (%i)", r < 0 ? "don't know" : yes_no(r), r); - assert_se(r == 0 || r == -EAGAIN || (r < 0 && ERRNO_IS_PRIVILEGE(r))); + assert_se(IN_SET(r, 0, -EAGAIN) || ERRNO_IS_NEG_PRIVILEGE(r)); r = mount_option_supported("tmpfs", "ialsodontexist", NULL); log_info("tmpfs supports ialsodontexist: %s (%i)", r < 0 ? "don't know" : yes_no(r), r); - assert_se(r == 0 || r == -EAGAIN || (r < 0 && ERRNO_IS_PRIVILEGE(r))); + assert_se(IN_SET(r, 0, -EAGAIN) || ERRNO_IS_NEG_PRIVILEGE(r)); r = mount_option_supported("proc", "hidepid", "1"); log_info("proc supports hidepid=1: %s (%i)", r < 0 ? "don't know" : yes_no(r), r); - assert_se(r >= 0 || r == -EAGAIN || (r < 0 && ERRNO_IS_PRIVILEGE(r))); + assert_se(r >= 0 || r == -EAGAIN || ERRNO_IS_NEG_PRIVILEGE(r)); } TEST(fstype_can_discard) { @@ -359,9 +354,9 @@ TEST(fstype_can_discard) { } TEST(fstype_can_norecovery) { - assert_se(fstype_can_norecovery("ext4")); - assert_se(!fstype_can_norecovery("vfat")); - assert_se(!fstype_can_norecovery("tmpfs")); + ASSERT_STREQ(fstype_norecovery_option("ext4"), "norecovery"); + ASSERT_NULL(fstype_norecovery_option("vfat")); + ASSERT_NULL(fstype_norecovery_option("tmpfs")); } TEST(fstype_can_umask) { diff --git a/src/test/test-namespace.c b/src/test/test-namespace.c index 65d0825..2a684ce 100644 --- a/src/test/test-namespace.c +++ b/src/test/test-namespace.c @@ -1,6 +1,7 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> +#include <sysexits.h> #include <sys/socket.h> #include <sys/stat.h> @@ -84,6 +85,7 @@ TEST(tmpdir) { static void test_shareable_ns(unsigned long nsflag) { _cleanup_close_pair_ int s[2] = EBADF_PAIR; + bool permission_denied = false; pid_t pid1, pid2, pid3; int r, n = 0; siginfo_t si; @@ -100,8 +102,8 @@ static void test_shareable_ns(unsigned long nsflag) { if (pid1 == 0) { r = setup_shareable_ns(s, nsflag); - assert_se(r >= 0); - _exit(r); + assert_se(r >= 0 || ERRNO_IS_NEG_PRIVILEGE(r)); + _exit(r >= 0 ? r : EX_NOPERM); } pid2 = fork(); @@ -109,8 +111,8 @@ static void test_shareable_ns(unsigned long nsflag) { if (pid2 == 0) { r = setup_shareable_ns(s, nsflag); - assert_se(r >= 0); - exit(r); + assert_se(r >= 0 || ERRNO_IS_NEG_PRIVILEGE(r)); + _exit(r >= 0 ? r : EX_NOPERM); } pid3 = fork(); @@ -118,24 +120,38 @@ static void test_shareable_ns(unsigned long nsflag) { if (pid3 == 0) { r = setup_shareable_ns(s, nsflag); - assert_se(r >= 0); - exit(r); + assert_se(r >= 0 || ERRNO_IS_NEG_PRIVILEGE(r)); + _exit(r >= 0 ? r : EX_NOPERM); } r = wait_for_terminate(pid1, &si); assert_se(r >= 0); assert_se(si.si_code == CLD_EXITED); - n += si.si_status; + if (si.si_status == EX_NOPERM) + permission_denied = true; + else + n += si.si_status; r = wait_for_terminate(pid2, &si); assert_se(r >= 0); assert_se(si.si_code == CLD_EXITED); - n += si.si_status; + if (si.si_status == EX_NOPERM) + permission_denied = true; + else + n += si.si_status; r = wait_for_terminate(pid3, &si); assert_se(r >= 0); assert_se(si.si_code == CLD_EXITED); - n += si.si_status; + if (si.si_status == EX_NOPERM) + permission_denied = true; + else + n += si.si_status; + + /* LSMs can cause setup_shareable_ns() to fail with permission denied, do not fail the test in that + * case (e.g.: LXC with AppArmor on kernel < v6.2). */ + if (permission_denied) + return (void) log_tests_skipped("insufficient privileges"); assert_se(n == 1); } diff --git a/src/test/test-net-naming-scheme.c b/src/test/test-net-naming-scheme.c index f7ec5a6..a339020 100644 --- a/src/test/test-net-naming-scheme.c +++ b/src/test/test-net-naming-scheme.c @@ -25,7 +25,7 @@ TEST(naming_scheme_conversions) { log_info("latest → %s", n->name); assert_se(n = naming_scheme_from_name("v238")); - assert_se(streq(n->name, "v238")); + ASSERT_STREQ(n->name, "v238"); } DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-netlink-manual.c b/src/test/test-netlink-manual.c index 6543c61..8c1b0d4 100644 --- a/src/test/test-netlink-manual.c +++ b/src/test/test-netlink-manual.c @@ -1,5 +1,7 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* Make sure the net/if.h header is included before any linux/ one */ +#include <net/if.h> #include <arpa/inet.h> #include <linux/if_tunnel.h> #include <linux/ip.h> @@ -13,25 +15,29 @@ #include "tests.h" static int load_module(const char *mod_name) { - _cleanup_(kmod_unrefp) struct kmod_ctx *ctx = NULL; - _cleanup_(kmod_module_unref_listp) struct kmod_list *list = NULL; + _cleanup_(sym_kmod_unrefp) struct kmod_ctx *ctx = NULL; + _cleanup_(sym_kmod_module_unref_listp) struct kmod_list *list = NULL; struct kmod_list *l; int r; - ctx = kmod_new(NULL, NULL); + r = dlopen_libkmod(); + if (r < 0) + return log_error_errno(r, "Failed to load libkmod: %m"); + + ctx = sym_kmod_new(NULL, NULL); if (!ctx) return log_oom(); - r = kmod_module_new_from_lookup(ctx, mod_name, &list); + r = sym_kmod_module_new_from_lookup(ctx, mod_name, &list); if (r < 0) return r; - kmod_list_foreach(l, list) { - _cleanup_(kmod_module_unrefp) struct kmod_module *mod = NULL; + sym_kmod_list_foreach(l, list) { + _cleanup_(sym_kmod_module_unrefp) struct kmod_module *mod = NULL; - mod = kmod_module_get_module(l); + mod = sym_kmod_module_get_module(l); - r = kmod_module_probe_insert_module(mod, 0, NULL, NULL, NULL, NULL); + r = sym_kmod_module_probe_insert_module(mod, 0, NULL, NULL, NULL, NULL); if (r > 0) r = -EINVAL; } @@ -78,7 +84,7 @@ static int test_tunnel_configure(sd_netlink *rtnl) { assert_se(sd_netlink_call(rtnl, m, -1, 0) == 1); - assert_se((m = sd_netlink_message_unref(m)) == NULL); + ASSERT_NULL((m = sd_netlink_message_unref(m))); /* sit */ assert_se(sd_rtnl_message_new_link(rtnl, &n, RTM_NEWLINK, 0) >= 0); @@ -104,7 +110,7 @@ static int test_tunnel_configure(sd_netlink *rtnl) { assert_se(sd_netlink_call(rtnl, n, -1, 0) == 1); - assert_se((n = sd_netlink_message_unref(n)) == NULL); + ASSERT_NULL((n = sd_netlink_message_unref(n))); return EXIT_SUCCESS; } @@ -120,7 +126,7 @@ int main(int argc, char *argv[]) { r = test_tunnel_configure(rtnl); - assert_se((rtnl = sd_netlink_unref(rtnl)) == NULL); + ASSERT_NULL((rtnl = sd_netlink_unref(rtnl))); return r; } diff --git a/src/test/test-nss-hosts.c b/src/test/test-nss-hosts.c index 72a9c64..2f1810d 100644 --- a/src/test/test-nss-hosts.c +++ b/src/test/test-nss-hosts.c @@ -140,7 +140,7 @@ static void test_gethostbyname4_r(void *handle, const char *module, const char * assert_se(status == NSS_STATUS_SUCCESS); assert_se(n == socket_ipv6_is_enabled() + 1); - } else if (streq(module, "resolve") && getenv_bool_secure("SYSTEMD_NSS_RESOLVE_SYNTHESIZE") != 0) { + } else if (streq(module, "resolve") && secure_getenv_bool("SYSTEMD_NSS_RESOLVE_SYNTHESIZE") != 0) { assert_se(status == NSS_STATUS_SUCCESS); if (socket_ipv6_is_enabled()) assert_se(n == 2); diff --git a/src/test/test-nulstr-util.c b/src/test/test-nulstr-util.c index 95c25f1..9b13d3c 100644 --- a/src/test/test-nulstr-util.c +++ b/src/test/test-nulstr-util.c @@ -13,10 +13,10 @@ TEST(strv_split_nulstr) { l = strv_split_nulstr(nulstr); assert_se(l); - assert_se(streq(l[0], "str0")); - assert_se(streq(l[1], "str1")); - assert_se(streq(l[2], "str2")); - assert_se(streq(l[3], "str3")); + ASSERT_STREQ(l[0], "str0"); + ASSERT_STREQ(l[1], "str1"); + ASSERT_STREQ(l[2], "str2"); + ASSERT_STREQ(l[3], "str3"); } #define strv_parse_nulstr_full_one(s, n, e0, e1) \ @@ -97,7 +97,7 @@ static void test_strv_make_nulstr_one(char **l) { assert_se(memcmp_nn(b, n, c, m) == 0); NULSTR_FOREACH(s, b) - assert_se(streq(s, l[i++])); + ASSERT_STREQ(s, l[i++]); assert_se(i == strv_length(l)); } diff --git a/src/test/test-open-file.c b/src/test/test-open-file.c index 4314d0d..22f58af 100644 --- a/src/test/test-open-file.c +++ b/src/test/test-open-file.c @@ -11,32 +11,32 @@ TEST(open_file_parse) { r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:read-only", &of); assert_se(r >= 0); - assert_se(streq(of->path, "/proc/1/ns/mnt")); - assert_se(streq(of->fdname, "host-mount-namespace")); + ASSERT_STREQ(of->path, "/proc/1/ns/mnt"); + ASSERT_STREQ(of->fdname, "host-mount-namespace"); assert_se(of->flags == OPENFILE_READ_ONLY); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt", &of); assert_se(r >= 0); - assert_se(streq(of->path, "/proc/1/ns/mnt")); - assert_se(streq(of->fdname, "mnt")); + ASSERT_STREQ(of->path, "/proc/1/ns/mnt"); + ASSERT_STREQ(of->fdname, "mnt"); assert_se(of->flags == 0); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace", &of); assert_se(r >= 0); - assert_se(streq(of->path, "/proc/1/ns/mnt")); - assert_se(streq(of->fdname, "host-mount-namespace")); + ASSERT_STREQ(of->path, "/proc/1/ns/mnt"); + ASSERT_STREQ(of->fdname, "host-mount-namespace"); assert_se(of->flags == 0); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt::read-only", &of); assert_se(r >= 0); - assert_se(streq(of->path, "/proc/1/ns/mnt")); - assert_se(streq(of->fdname, "mnt")); + ASSERT_STREQ(of->path, "/proc/1/ns/mnt"); + ASSERT_STREQ(of->fdname, "mnt"); assert_se(of->flags == OPENFILE_READ_ONLY); of = open_file_free(of); @@ -53,16 +53,16 @@ TEST(open_file_parse) { r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:append", &of); assert_se(r >= 0); - assert_se(streq(of->path, "/proc/1/ns/mnt")); - assert_se(streq(of->fdname, "host-mount-namespace")); + ASSERT_STREQ(of->path, "/proc/1/ns/mnt"); + ASSERT_STREQ(of->fdname, "host-mount-namespace"); assert_se(of->flags == OPENFILE_APPEND); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:truncate", &of); assert_se(r >= 0); - assert_se(streq(of->path, "/proc/1/ns/mnt")); - assert_se(streq(of->fdname, "host-mount-namespace")); + ASSERT_STREQ(of->path, "/proc/1/ns/mnt"); + ASSERT_STREQ(of->fdname, "host-mount-namespace"); assert_se(of->flags == OPENFILE_TRUNCATE); of = open_file_free(of); @@ -89,16 +89,16 @@ TEST(open_file_parse) { r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:graceful", &of); assert_se(r >= 0); - assert_se(streq(of->path, "/proc/1/ns/mnt")); - assert_se(streq(of->fdname, "host-mount-namespace")); + ASSERT_STREQ(of->path, "/proc/1/ns/mnt"); + ASSERT_STREQ(of->fdname, "host-mount-namespace"); assert_se(of->flags == OPENFILE_GRACEFUL); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:read-only,graceful", &of); assert_se(r >= 0); - assert_se(streq(of->path, "/proc/1/ns/mnt")); - assert_se(streq(of->fdname, "host-mount-namespace")); + ASSERT_STREQ(of->path, "/proc/1/ns/mnt"); + ASSERT_STREQ(of->fdname, "host-mount-namespace"); assert_se(of->flags == (OPENFILE_READ_ONLY | OPENFILE_GRACEFUL)); of = open_file_free(of); @@ -120,7 +120,7 @@ TEST(open_file_to_string) { r = open_file_to_string(of, &s); assert_se(r >= 0); - assert_se(streq(s, "/proc/1/ns/mnt:host-mount-namespace:read-only")); + ASSERT_STREQ(s, "/proc/1/ns/mnt:host-mount-namespace:read-only"); s = mfree(s); of->flags = OPENFILE_APPEND; @@ -128,7 +128,7 @@ TEST(open_file_to_string) { r = open_file_to_string(of, &s); assert_se(r >= 0); - assert_se(streq(s, "/proc/1/ns/mnt:host-mount-namespace:append")); + ASSERT_STREQ(s, "/proc/1/ns/mnt:host-mount-namespace:append"); s = mfree(s); of->flags = OPENFILE_TRUNCATE; @@ -136,7 +136,7 @@ TEST(open_file_to_string) { r = open_file_to_string(of, &s); assert_se(r >= 0); - assert_se(streq(s, "/proc/1/ns/mnt:host-mount-namespace:truncate")); + ASSERT_STREQ(s, "/proc/1/ns/mnt:host-mount-namespace:truncate"); s = mfree(s); of->flags = OPENFILE_GRACEFUL; @@ -144,7 +144,7 @@ TEST(open_file_to_string) { r = open_file_to_string(of, &s); assert_se(r >= 0); - assert_se(streq(s, "/proc/1/ns/mnt:host-mount-namespace:graceful")); + ASSERT_STREQ(s, "/proc/1/ns/mnt:host-mount-namespace:graceful"); s = mfree(s); of->flags = OPENFILE_READ_ONLY | OPENFILE_GRACEFUL; @@ -152,7 +152,7 @@ TEST(open_file_to_string) { r = open_file_to_string(of, &s); assert_se(r >= 0); - assert_se(streq(s, "/proc/1/ns/mnt:host-mount-namespace:read-only,graceful")); + ASSERT_STREQ(s, "/proc/1/ns/mnt:host-mount-namespace:read-only,graceful"); s = mfree(s); of->flags = 0; @@ -160,7 +160,7 @@ TEST(open_file_to_string) { r = open_file_to_string(of, &s); assert_se(r >= 0); - assert_se(streq(s, "/proc/1/ns/mnt:host-mount-namespace")); + ASSERT_STREQ(s, "/proc/1/ns/mnt:host-mount-namespace"); s = mfree(s); assert_se(free_and_strdup(&of->fdname, "mnt")); @@ -169,15 +169,15 @@ TEST(open_file_to_string) { r = open_file_to_string(of, &s); assert_se(r >= 0); - assert_se(streq(s, "/proc/1/ns/mnt::read-only")); + ASSERT_STREQ(s, "/proc/1/ns/mnt::read-only"); s = mfree(s); - assert_se(free_and_strdup(&of->path, "/path:with:colon") >= 0); - assert_se(free_and_strdup(&of->fdname, "path:with:colon") >= 0); + ASSERT_OK(free_and_strdup(&of->path, "/path:with:colon")); + ASSERT_OK(free_and_strdup(&of->fdname, "path:with:colon")); of->flags = 0; - assert_se(open_file_to_string(of, &s) >= 0); - assert_se(streq(s, "/path\\x3awith\\x3acolon")); + ASSERT_OK(open_file_to_string(of, &s)); + ASSERT_STREQ(s, "/path\\x3awith\\x3acolon"); } DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-openssl.c b/src/test/test-openssl.c index dfdd1ab..d0ea0f0 100644 --- a/src/test/test-openssl.c +++ b/src/test/test-openssl.c @@ -95,7 +95,7 @@ TEST(invalid) { DEFINE_HEX_PTR(key, "2d2d2d2d2d424547494e205055424c4943204b45592d2d2d2d2d0a4d466b7b"); assert_se(openssl_pkey_from_pem(key, key_len, &pkey) == -EIO); - assert_se(pkey == NULL); + ASSERT_NULL(pkey); } static const struct { @@ -136,7 +136,7 @@ static const struct { TEST(digest_size) { size_t size; - FOREACH_ARRAY(t, digest_size_table, ELEMENTSOF(digest_size_table)) { + FOREACH_ELEMENT(t, digest_size_table) { assert(openssl_digest_size(t->alg, &size) >= 0); assert_se(size == t->size); diff --git a/src/test/test-ordered-set.c b/src/test/test-ordered-set.c index c055411..bb1eefb 100644 --- a/src/test/test-ordered-set.c +++ b/src/test/test-ordered-set.c @@ -81,9 +81,9 @@ TEST(set_put) { * non-trivial hash ops. */ assert_se(t = ordered_set_get_strv(m)); - assert_se(streq(t[0], "1")); - assert_se(streq(t[1], "22")); - assert_se(streq(t[2], "333")); + ASSERT_STREQ(t[0], "1"); + ASSERT_STREQ(t[1], "22"); + ASSERT_STREQ(t[2], "333"); assert_se(!t[3]); ordered_set_print(stdout, "FOO=", m); diff --git a/src/test/test-os-util.c b/src/test/test-os-util.c index 84e55e1..55475a5 100644 --- a/src/test/test-os-util.c +++ b/src/test/test-os-util.c @@ -14,47 +14,49 @@ #include "tmpfile-util.h" TEST(path_is_os_tree) { - assert_se(path_is_os_tree("/") > 0); - assert_se(path_is_os_tree("/etc") == 0); + ASSERT_GT(path_is_os_tree("/"), 0); + ASSERT_EQ(path_is_os_tree("/etc"), 0); assert_se(path_is_os_tree("/idontexist") == -ENOENT); } TEST(parse_os_release) { - /* Let's assume that we're running in a valid system, so os-release is available */ _cleanup_free_ char *id = NULL, *id2 = NULL, *name = NULL, *foobar = NULL; - assert_se(parse_os_release(NULL, "ID", &id) == 0); - log_info("ID: %s", id); - assert_se(setenv("SYSTEMD_OS_RELEASE", "/dev/null", 1) == 0); - assert_se(parse_os_release(NULL, "ID", &id2) == 0); + if (access("/etc/os-release", F_OK) >= 0 || access("/usr/lib/os-release", F_OK) >= 0) { + ASSERT_EQ(parse_os_release(NULL, "ID", &id), 0); + log_info("ID: %s", id); + } + + ASSERT_EQ(setenv("SYSTEMD_OS_RELEASE", "/dev/null", 1), 0); + ASSERT_EQ(parse_os_release(NULL, "ID", &id2), 0); log_info("ID: %s", strnull(id2)); _cleanup_(unlink_tempfilep) char tmpfile[] = "/tmp/test-os-util.XXXXXX"; - assert_se(write_tmpfile(tmpfile, + ASSERT_EQ(write_tmpfile(tmpfile, "ID=the-id \n" - "NAME=the-name") == 0); + "NAME=the-name"), 0); - assert_se(setenv("SYSTEMD_OS_RELEASE", tmpfile, 1) == 0); - assert_se(parse_os_release(NULL, "ID", &id, "NAME", &name) == 0); + ASSERT_EQ(setenv("SYSTEMD_OS_RELEASE", tmpfile, 1), 0); + ASSERT_EQ(parse_os_release(NULL, "ID", &id, "NAME", &name), 0); log_info("ID: %s NAME: %s", id, name); - assert_se(streq(id, "the-id")); - assert_se(streq(name, "the-name")); + ASSERT_STREQ(id, "the-id"); + ASSERT_STREQ(name, "the-name"); _cleanup_(unlink_tempfilep) char tmpfile2[] = "/tmp/test-os-util.XXXXXX"; - assert_se(write_tmpfile(tmpfile2, + ASSERT_EQ(write_tmpfile(tmpfile2, "ID=\"ignored\" \n" "ID=\"the-id\" \n" - "NAME='the-name'") == 0); + "NAME='the-name'"), 0); - assert_se(setenv("SYSTEMD_OS_RELEASE", tmpfile2, 1) == 0); - assert_se(parse_os_release(NULL, "ID", &id, "NAME", &name) == 0); + ASSERT_EQ(setenv("SYSTEMD_OS_RELEASE", tmpfile2, 1), 0); + ASSERT_EQ(parse_os_release(NULL, "ID", &id, "NAME", &name), 0); log_info("ID: %s NAME: %s", id, name); - assert_se(streq(id, "the-id")); - assert_se(streq(name, "the-name")); + ASSERT_STREQ(id, "the-id"); + ASSERT_STREQ(name, "the-name"); - assert_se(parse_os_release(NULL, "FOOBAR", &foobar) == 0); + ASSERT_EQ(parse_os_release(NULL, "FOOBAR", &foobar), 0); log_info("FOOBAR: %s", strnull(foobar)); - assert_se(foobar == NULL); + ASSERT_NULL(foobar); assert_se(unsetenv("SYSTEMD_OS_RELEASE") == 0); } @@ -70,6 +72,7 @@ TEST(parse_extension_release) { assert_se(a = path_join(tempdir, "/usr/lib/extension-release.d/extension-release.test")); assert_se(mkdir_parents(a, 0777) >= 0); + ASSERT_GE(mkdir_parents(a, 0777), 0); r = write_string_file(a, "ID=the-id \n VERSION_ID=the-version-id", WRITE_STRING_FILE_CREATE); if (r < 0) @@ -77,8 +80,8 @@ TEST(parse_extension_release) { assert_se(parse_extension_release(tempdir, IMAGE_SYSEXT, "test", false, "ID", &id, "VERSION_ID", &version_id) == 0); log_info("ID: %s VERSION_ID: %s", id, version_id); - assert_se(streq(id, "the-id")); - assert_se(streq(version_id, "the-version-id")); + ASSERT_STREQ(id, "the-id"); + ASSERT_STREQ(version_id, "the-version-id"); assert_se(b = path_join(tempdir, "/etc/extension-release.d/extension-release.tester")); assert_se(mkdir_parents(b, 0777) >= 0); @@ -87,42 +90,42 @@ TEST(parse_extension_release) { if (r < 0) log_error_errno(r, "Failed to write file: %m"); - assert_se(parse_extension_release(tempdir, IMAGE_CONFEXT, "tester", false, "ID", &id, "VERSION_ID", &version_id) == 0); + ASSERT_EQ(parse_extension_release(tempdir, IMAGE_CONFEXT, "tester", false, "ID", &id, "VERSION_ID", &version_id), 0); log_info("ID: %s VERSION_ID: %s", id, version_id); - assert_se(streq(id, "the-id")); - assert_se(streq(version_id, "the-version-id")); + ASSERT_STREQ(id, "the-id"); + ASSERT_STREQ(version_id, "the-version-id"); assert_se(parse_extension_release(tempdir, IMAGE_CONFEXT, "tester", false, "FOOBAR", &foobar) == 0); log_info("FOOBAR: %s", strnull(foobar)); - assert_se(foobar == NULL); + ASSERT_NULL(foobar); assert_se(parse_extension_release(tempdir, IMAGE_SYSEXT, "test", false, "FOOBAR", &foobar) == 0); log_info("FOOBAR: %s", strnull(foobar)); - assert_se(foobar == NULL); + ASSERT_NULL(foobar); } TEST(load_os_release_pairs) { _cleanup_(unlink_tempfilep) char tmpfile[] = "/tmp/test-os-util.XXXXXX"; - assert_se(write_tmpfile(tmpfile, + ASSERT_EQ(write_tmpfile(tmpfile, "ID=\"ignored\" \n" "ID=\"the-id\" \n" - "NAME='the-name'") == 0); + "NAME='the-name'"), 0); - assert_se(setenv("SYSTEMD_OS_RELEASE", tmpfile, 1) == 0); + ASSERT_EQ(setenv("SYSTEMD_OS_RELEASE", tmpfile, 1), 0); _cleanup_strv_free_ char **pairs = NULL; - assert_se(load_os_release_pairs(NULL, &pairs) == 0); + ASSERT_EQ(load_os_release_pairs(NULL, &pairs), 0); assert_se(strv_equal(pairs, STRV_MAKE("ID", "the-id", "NAME", "the-name"))); - assert_se(unsetenv("SYSTEMD_OS_RELEASE") == 0); + ASSERT_EQ(unsetenv("SYSTEMD_OS_RELEASE"), 0); } TEST(os_release_support_ended) { int r; - assert_se(os_release_support_ended("1999-01-01", false, NULL) == true); - assert_se(os_release_support_ended("2037-12-31", false, NULL) == false); + ASSERT_TRUE(os_release_support_ended("1999-01-01", false, NULL)); + ASSERT_FALSE(os_release_support_ended("2037-12-31", false, NULL)); assert_se(os_release_support_ended("-1-1-1", true, NULL) == -EINVAL); r = os_release_support_ended(NULL, false, NULL); diff --git a/src/test/test-parse-argument.c b/src/test/test-parse-argument.c index cf3d542..c07b2d9 100644 --- a/src/test/test-parse-argument.c +++ b/src/test/test-parse-argument.c @@ -20,13 +20,13 @@ TEST(parse_path_argument) { _cleanup_free_ char *path = NULL; assert_se(parse_path_argument("help", false, &path) == 0); - assert_se(streq(basename(path), "help")); + ASSERT_STREQ(basename(path), "help"); assert_se(parse_path_argument("/", false, &path) == 0); - assert_se(streq(path, "/")); + ASSERT_STREQ(path, "/"); assert_se(parse_path_argument("/", true, &path) == 0); - assert_se(path == NULL); + ASSERT_NULL(path); } TEST(parse_signal_argument) { diff --git a/src/test/test-parse-helpers.c b/src/test/test-parse-helpers.c index 052e251..20d4c2f 100644 --- a/src/test/test-parse-helpers.c +++ b/src/test/test-parse-helpers.c @@ -37,6 +37,7 @@ static void test_invalid_item(const char *str) { TEST(valid_items) { test_valid_item("any", AF_UNSPEC, 0, 0, 0); + test_valid_item("0-65535", AF_UNSPEC, 0, 0, 0); test_valid_item("ipv4", AF_INET, 0, 0, 0); test_valid_item("ipv6", AF_INET6, 0, 0, 0); test_valid_item("ipv4:any", AF_INET, 0, 0, 0); @@ -45,6 +46,7 @@ TEST(valid_items) { test_valid_item("udp", AF_UNSPEC, IPPROTO_UDP, 0, 0); test_valid_item("tcp:any", AF_UNSPEC, IPPROTO_TCP, 0, 0); test_valid_item("udp:any", AF_UNSPEC, IPPROTO_UDP, 0, 0); + test_valid_item("0", AF_UNSPEC, 0, 1, 0); test_valid_item("6666", AF_UNSPEC, 0, 1, 6666); test_valid_item("6666-6667", AF_UNSPEC, 0, 2, 6666); test_valid_item("65535", AF_UNSPEC, 0, 1, 65535); @@ -61,6 +63,7 @@ TEST(valid_items) { test_valid_item("ipv6:tcp:6666", AF_INET6, IPPROTO_TCP, 1, 6666); test_valid_item("ipv6:udp:6666-6667", AF_INET6, IPPROTO_UDP, 2, 6666); test_valid_item("ipv6:tcp:any", AF_INET6, IPPROTO_TCP, 0, 0); + test_valid_item("ipv6:tcp:0", AF_INET6, IPPROTO_TCP, 1, 0); } TEST(invalid_items) { @@ -77,9 +80,7 @@ TEST(invalid_items) { test_invalid_item("ipv6::"); test_invalid_item("ipv6:ipv6"); test_invalid_item("ipv6:icmp"); - test_invalid_item("ipv6:tcp:0"); test_invalid_item("65536"); - test_invalid_item("0-65535"); test_invalid_item("ipv6:tcp:6666-6665"); test_invalid_item("ipv6:tcp:6666-100000"); test_invalid_item("ipv6::6666"); @@ -92,4 +93,39 @@ TEST(invalid_items) { test_invalid_item("ipv6:tcp:6666\n zupa"); } +static int test_path_simplify_and_warn_one(const char *p, const char *q, PathSimplifyWarnFlags f) { + _cleanup_free_ char *s = ASSERT_PTR(strdup(p)); + int a, b; + + a = path_simplify_and_warn(s, f, /* unit= */ NULL, /* filename= */ NULL, /* line= */ 0, "Foobar="); + assert(streq_ptr(s, q)); + + free(s); + s = ASSERT_PTR(strdup(p)); + + b = path_simplify_and_warn(s, f|PATH_CHECK_FATAL, /* unit= */ NULL, /* filename= */ NULL, /* line= */ 0, "Foobar="); + assert(streq_ptr(s, q)); + + assert(a == b); + + return a; +} + +TEST(path_simplify_and_warn) { + + assert_se(test_path_simplify_and_warn_one("", "", 0) == -EINVAL); + assert_se(test_path_simplify_and_warn_one("/", "/", 0) == 0); + assert_se(test_path_simplify_and_warn_one("/foo/../bar", "/foo/../bar", 0) == -EINVAL); + assert_se(test_path_simplify_and_warn_one("/foo/./bar", "/foo/bar", 0) == 0); + assert_se(test_path_simplify_and_warn_one("/proc/self///fd", "/proc/self/fd", 0) == 0); + assert_se(test_path_simplify_and_warn_one("/proc/self///fd", "/proc/self/fd", PATH_CHECK_NON_API_VFS) == -EINVAL); + assert_se(test_path_simplify_and_warn_one("aaaa", "aaaa", 0) == 0); + assert_se(test_path_simplify_and_warn_one("aaaa", "aaaa", PATH_CHECK_ABSOLUTE) == -EINVAL); + assert_se(test_path_simplify_and_warn_one("aaaa", "aaaa", PATH_CHECK_RELATIVE) == 0); + assert_se(test_path_simplify_and_warn_one("/aaaa", "/aaaa", 0) == 0); + assert_se(test_path_simplify_and_warn_one("/aaaa", "/aaaa", PATH_CHECK_ABSOLUTE) == 0); + assert_se(test_path_simplify_and_warn_one("/aaaa", "/aaaa", PATH_CHECK_RELATIVE) == -EINVAL); + +} + DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-path-lookup.c b/src/test/test-path-lookup.c index 431a859..cff2774 100644 --- a/src/test/test-path-lookup.c +++ b/src/test/test-path-lookup.c @@ -13,8 +13,8 @@ static void test_paths_one(RuntimeScope scope) { _cleanup_(rm_rf_physical_and_freep) char *tmp = NULL; - _cleanup_(lookup_paths_free) LookupPaths lp_without_env = {}; - _cleanup_(lookup_paths_free) LookupPaths lp_with_env = {}; + _cleanup_(lookup_paths_done) LookupPaths lp_without_env = {}; + _cleanup_(lookup_paths_done) LookupPaths lp_with_env = {}; char *systemd_unit_path; assert_se(mkdtemp_malloc("/tmp/test-path-lookup.XXXXXXX", &tmp) >= 0); @@ -28,7 +28,7 @@ static void test_paths_one(RuntimeScope scope) { assert_se(setenv("SYSTEMD_UNIT_PATH", systemd_unit_path, 1) == 0); assert_se(lookup_paths_init(&lp_with_env, scope, 0, NULL) == 0); assert_se(strv_length(lp_with_env.search_path) == 1); - assert_se(streq(lp_with_env.search_path[0], systemd_unit_path)); + ASSERT_STREQ(lp_with_env.search_path[0], systemd_unit_path); lookup_paths_log(&lp_with_env); assert_se(strv_equal(lp_with_env.search_path, STRV_MAKE(systemd_unit_path))); } @@ -40,7 +40,7 @@ TEST(paths) { } TEST(user_and_global_paths) { - _cleanup_(lookup_paths_free) LookupPaths lp_global = {}, lp_user = {}; + _cleanup_(lookup_paths_done) LookupPaths lp_global = {}, lp_user = {}; char **u, **g; unsigned k = 0; diff --git a/src/test/test-path-util.c b/src/test/test-path-util.c index f5a4256..e02bd8c 100644 --- a/src/test/test-path-util.c +++ b/src/test/test-path-util.c @@ -18,30 +18,32 @@ #include "tmpfile-util.h" TEST(print_paths) { - log_info("DEFAULT_PATH=%s", DEFAULT_PATH); - log_info("DEFAULT_USER_PATH=%s", DEFAULT_USER_PATH); + log_info("default system PATH: %s", default_PATH()); + log_info("default user PATH: %s", default_user_PATH()); } TEST(path) { - assert_se(path_is_absolute("/")); + assert_se( path_is_absolute("/")); assert_se(!path_is_absolute("./")); - assert_se(streq(basename("./aa/bb/../file.da."), "file.da.")); - assert_se(streq(basename("/aa///.file"), ".file")); - assert_se(streq(basename("/aa///file..."), "file...")); - assert_se(streq(basename("file.../"), "")); + ASSERT_STREQ(basename("./aa/bb/../file.da."), "file.da."); + ASSERT_STREQ(basename("/aa///.file"), ".file"); + ASSERT_STREQ(basename("/aa///file..."), "file..."); + ASSERT_STREQ(basename("file.../"), ""); - assert_se(PATH_IN_SET("/bin", "/", "/bin", "/foo")); - assert_se(PATH_IN_SET("/bin", "/bin")); - assert_se(PATH_IN_SET("/bin", "/foo/bar", "/bin")); - assert_se(PATH_IN_SET("/", "/", "/", "/foo/bar")); + assert_se( PATH_IN_SET("/bin", "/", "/bin", "/foo")); + assert_se( PATH_IN_SET("/bin", "/bin")); + assert_se( PATH_IN_SET("/bin", "/foo/bar", "/bin")); + assert_se( PATH_IN_SET("/", "/", "/", "/foo/bar")); assert_se(!PATH_IN_SET("/", "/abc", "/def")); - assert_se(path_equal_ptr(NULL, NULL)); - assert_se(path_equal_ptr("/a", "/a")); - assert_se(!path_equal_ptr("/a", "/b")); - assert_se(!path_equal_ptr("/a", NULL)); - assert_se(!path_equal_ptr(NULL, "/a")); + assert_se( path_equal(NULL, NULL)); + assert_se( path_equal("/a", "/a")); + assert_se(!path_equal("/a", "/b")); + assert_se(!path_equal("/a", NULL)); + assert_se(!path_equal(NULL, "/a")); + assert_se(!path_equal("a", NULL)); + assert_se(!path_equal(NULL, "a")); } TEST(is_path) { @@ -144,7 +146,7 @@ static void test_path_simplify_one(const char *in, const char *out, PathSimplify p = strdupa_safe(in); path_simplify_full(p, flags); log_debug("/* test_path_simplify(%s) → %s (expected: %s) */", in, p, out); - assert_se(streq(p, out)); + ASSERT_STREQ(p, out); } TEST(path_simplify) { @@ -377,12 +379,12 @@ TEST(find_executable_full) { assert_se(find_executable_full("sh", NULL, NULL, true, &p, NULL) == 0); puts(p); - assert_se(streq(basename(p), "sh")); + ASSERT_STREQ(basename(p), "sh"); free(p); assert_se(find_executable_full("sh", NULL, NULL, false, &p, NULL) == 0); puts(p); - assert_se(streq(basename(p), "sh")); + ASSERT_STREQ(basename(p), "sh"); free(p); _cleanup_free_ char *oldpath = NULL; @@ -394,12 +396,12 @@ TEST(find_executable_full) { assert_se(find_executable_full("sh", NULL, NULL, true, &p, NULL) == 0); puts(p); - assert_se(streq(basename(p), "sh")); + ASSERT_STREQ(basename(p), "sh"); free(p); assert_se(find_executable_full("sh", NULL, NULL, false, &p, NULL) == 0); puts(p); - assert_se(streq(basename(p), "sh")); + ASSERT_STREQ(basename(p), "sh"); free(p); if (oldpath) @@ -412,7 +414,7 @@ TEST(find_executable_full) { assert_se(find_executable_full(test_file_name, NULL, STRV_MAKE("/doesnotexist", "/tmp", "/bin"), false, &p, NULL) == 0); puts(p); - assert_se(streq(p, fn)); + ASSERT_STREQ(p, fn); free(p); (void) unlink(fn); @@ -440,12 +442,12 @@ TEST(find_executable) { free(p); assert_se(find_executable("/bin/touch", &p) == 0); - assert_se(streq(p, "/bin/touch")); + ASSERT_STREQ(p, "/bin/touch"); free(p); assert_se(find_executable("touch", &p) == 0); assert_se(path_is_absolute(p)); - assert_se(streq(basename(p), "touch")); + ASSERT_STREQ(basename(p), "touch"); free(p); assert_se(find_executable("xxxx-xxxx", &p) == -ENOENT); @@ -466,7 +468,7 @@ static void test_find_executable_exec_one(const char *path) { assert_se(fd > STDERR_FILENO); assert_se(path_is_absolute(t)); if (path_is_absolute(path)) - assert_se(streq(t, path)); + ASSERT_STREQ(t, path); pid = fork(); assert_se(pid >= 0); @@ -504,26 +506,26 @@ TEST(prefixes) { i = 0; PATH_FOREACH_PREFIX_MORE(s, "/a/b/c/d") { log_error("---%s---", s); - assert_se(streq(s, values[i++])); + ASSERT_STREQ(s, values[i++]); } - assert_se(values[i] == NULL); + ASSERT_NULL(values[i]); i = 1; PATH_FOREACH_PREFIX(s, "/a/b/c/d") { log_error("---%s---", s); - assert_se(streq(s, values[i++])); + ASSERT_STREQ(s, values[i++]); } - assert_se(values[i] == NULL); + ASSERT_NULL(values[i]); i = 0; PATH_FOREACH_PREFIX_MORE(s, "////a////b////c///d///////") - assert_se(streq(s, values[i++])); - assert_se(values[i] == NULL); + ASSERT_STREQ(s, values[i++]); + ASSERT_NULL(values[i]); i = 1; PATH_FOREACH_PREFIX(s, "////a////b////c///d///////") - assert_se(streq(s, values[i++])); - assert_se(values[i] == NULL); + ASSERT_STREQ(s, values[i++]); + ASSERT_NULL(values[i]); PATH_FOREACH_PREFIX(s, "////") assert_not_reached(); @@ -531,7 +533,7 @@ TEST(prefixes) { b = false; PATH_FOREACH_PREFIX_MORE(s, "////") { assert_se(!b); - assert_se(streq(s, "")); + ASSERT_STREQ(s, ""); b = true; } assert_se(b); @@ -542,7 +544,7 @@ TEST(prefixes) { b = false; PATH_FOREACH_PREFIX_MORE(s, "") { assert_se(!b); - assert_se(streq(s, "")); + ASSERT_STREQ(s, ""); b = true; } } @@ -552,7 +554,7 @@ TEST(path_join) { _cleanup_free_ char *z = NULL; \ z = path_join(__VA_ARGS__); \ log_debug("got \"%s\", expected \"%s\"", z, expected); \ - assert_se(streq(z, expected)); \ + ASSERT_STREQ(z, expected); \ } test_join("/root/a/b/c", "/root", "/a/b", "/c"); @@ -595,25 +597,25 @@ TEST(path_extend) { _cleanup_free_ char *p = NULL; assert_se(path_extend(&p, "foo", "bar", "baz") == p); - assert_se(streq(p, "foo/bar/baz")); + ASSERT_STREQ(p, "foo/bar/baz"); assert_se(path_extend(&p, "foo", "bar", "baz") == p); - assert_se(streq(p, "foo/bar/baz/foo/bar/baz")); + ASSERT_STREQ(p, "foo/bar/baz/foo/bar/baz"); p = mfree(p); assert_se(path_extend(&p, "foo") == p); - assert_se(streq(p, "foo")); + ASSERT_STREQ(p, "foo"); assert_se(path_extend(&p, "/foo") == p); - assert_se(streq(p, "foo/foo")); + ASSERT_STREQ(p, "foo/foo"); assert_se(path_extend(&p, "/waaaah/wahhh//") == p); - assert_se(streq(p, "foo/foo/waaaah/wahhh//")); /* path_extend() does not drop redundant slashes */ + ASSERT_STREQ(p, "foo/foo/waaaah/wahhh//"); /* path_extend() does not drop redundant slashes */ assert_se(path_extend(&p, "/aaa/bbb/") == p); - assert_se(streq(p, "foo/foo/waaaah/wahhh///aaa/bbb/")); /* but not add an extra slash */ + ASSERT_STREQ(p, "foo/foo/waaaah/wahhh///aaa/bbb/"); /* but not add an extra slash */ assert_se(free_and_strdup(&p, "/") >= 0); assert_se(path_extend(&p, "foo") == p); - assert_se(streq(p, "/foo")); + ASSERT_STREQ(p, "/foo"); } TEST(fsck_exists) { @@ -635,7 +637,7 @@ static void test_path_make_relative_one(const char *from, const char *to, const r = path_make_relative(from, to, &z); assert_se((r >= 0) == !!expected); - assert_se(streq_ptr(z, expected)); + ASSERT_STREQ(z, expected); } TEST(path_make_relative) { @@ -661,7 +663,7 @@ static void test_path_make_relative_parent_one(const char *from, const char *to, r = path_make_relative_parent(from, to, &z); assert_se((r >= 0) == !!expected); - assert_se(streq_ptr(z, expected)); + ASSERT_STREQ(z, expected); } TEST(path_make_relative_parent) { @@ -685,7 +687,7 @@ TEST(path_strv_resolve) { _cleanup_strv_free_ char **search_dirs = NULL; _cleanup_strv_free_ char **absolute_dirs = NULL; - assert_se(mkdtemp(tmp_dir) != NULL); + ASSERT_NOT_NULL(mkdtemp(tmp_dir)); search_dirs = strv_new("/dir1", "/dir2", "/dir3"); assert_se(search_dirs); @@ -700,9 +702,9 @@ TEST(path_strv_resolve) { assert_se(symlink("dir2", absolute_dirs[2]) == 0); path_strv_resolve(search_dirs, tmp_dir); - assert_se(streq(search_dirs[0], "/dir1")); - assert_se(streq(search_dirs[1], "/dir2")); - assert_se(streq(search_dirs[2], "/dir2")); + ASSERT_STREQ(search_dirs[0], "/dir1"); + ASSERT_STREQ(search_dirs[1], "/dir2"); + ASSERT_STREQ(search_dirs[2], "/dir2"); assert_se(rm_rf(tmp_dir, REMOVE_ROOT|REMOVE_PHYSICAL) == 0); } @@ -713,10 +715,10 @@ static void test_path_startswith_one(const char *path, const char *prefix, const log_debug("/* %s(%s, %s) */", __func__, path, prefix); p = path_startswith(path, prefix); - assert_se(streq_ptr(p, expected)); + ASSERT_STREQ(p, expected); if (p) { q = strjoina(skipped, p); - assert_se(streq(q, path)); + ASSERT_STREQ(q, path); assert_se(p == path + strlen(skipped)); } } @@ -759,11 +761,11 @@ static void test_prefix_root_one(const char *r, const char *p, const char *expec const char *t; assert_se(s = path_join(r, p)); - assert_se(path_equal_ptr(s, expected)); + assert_se(path_equal(s, expected)); t = prefix_roota(r, p); assert_se(t); - assert_se(path_equal_ptr(t, expected)); + assert_se(path_equal(t, expected)); } TEST(prefix_root) { @@ -791,17 +793,17 @@ TEST(file_in_same_dir) { assert_se(file_in_same_dir("/", "a", &t) == -EADDRNOTAVAIL); assert_se(file_in_same_dir("/", "/a", &t) >= 0); - assert_se(streq(t, "/a")); + ASSERT_STREQ(t, "/a"); free(t); assert_se(file_in_same_dir("", "a", &t) == -EINVAL); assert_se(file_in_same_dir("a/", "x", &t) >= 0); - assert_se(streq(t, "x")); + ASSERT_STREQ(t, "x"); free(t); assert_se(file_in_same_dir("bar/foo", "bar", &t) >= 0); - assert_se(streq(t, "bar/bar")); + ASSERT_STREQ(t, "bar/bar"); free(t); } @@ -984,23 +986,23 @@ TEST(path_find_last_component) { } TEST(last_path_component) { - assert_se(last_path_component(NULL) == NULL); - assert_se(streq(last_path_component("a/b/c"), "c")); - assert_se(streq(last_path_component("a/b/c/"), "c/")); - assert_se(streq(last_path_component("/"), "/")); - assert_se(streq(last_path_component("//"), "/")); - assert_se(streq(last_path_component("///"), "/")); - assert_se(streq(last_path_component("."), ".")); - assert_se(streq(last_path_component("./."), ".")); - assert_se(streq(last_path_component("././"), "./")); - assert_se(streq(last_path_component("././/"), ".//")); - assert_se(streq(last_path_component("/foo/a"), "a")); - assert_se(streq(last_path_component("/foo/a/"), "a/")); - assert_se(streq(last_path_component(""), "")); - assert_se(streq(last_path_component("a"), "a")); - assert_se(streq(last_path_component("a/"), "a/")); - assert_se(streq(last_path_component("/a"), "a")); - assert_se(streq(last_path_component("/a/"), "a/")); + ASSERT_NULL(last_path_component(NULL)); + ASSERT_STREQ(last_path_component("a/b/c"), "c"); + ASSERT_STREQ(last_path_component("a/b/c/"), "c/"); + ASSERT_STREQ(last_path_component("/"), "/"); + ASSERT_STREQ(last_path_component("//"), "/"); + ASSERT_STREQ(last_path_component("///"), "/"); + ASSERT_STREQ(last_path_component("."), "."); + ASSERT_STREQ(last_path_component("./."), "."); + ASSERT_STREQ(last_path_component("././"), "./"); + ASSERT_STREQ(last_path_component("././/"), ".//"); + ASSERT_STREQ(last_path_component("/foo/a"), "a"); + ASSERT_STREQ(last_path_component("/foo/a/"), "a/"); + ASSERT_STREQ(last_path_component(""), ""); + ASSERT_STREQ(last_path_component("a"), "a"); + ASSERT_STREQ(last_path_component("a/"), "a/"); + ASSERT_STREQ(last_path_component("/a"), "a"); + ASSERT_STREQ(last_path_component("/a/"), "a/"); } static void test_path_extract_filename_one(const char *input, const char *output, int ret) { @@ -1012,7 +1014,7 @@ static void test_path_extract_filename_one(const char *input, const char *output strnull(input), strnull(k), r < 0 ? STRERROR(r) : "-", strnull(output), ret < 0 ? STRERROR(ret) : "-"); - assert_se(streq_ptr(k, output)); + ASSERT_STREQ(k, output); assert_se(r == ret); } @@ -1056,7 +1058,7 @@ static void test_path_extract_directory_one(const char *input, const char *outpu strnull(input), strnull(k), r < 0 ? STRERROR(r) : "-", strnull(output), STRERROR(ret)); - assert_se(streq_ptr(k, output)); + ASSERT_STREQ(k, output); assert_se(r == ret); /* Extra safety check: let's make sure that if we split out the filename too (and it works) the @@ -1190,17 +1192,17 @@ TEST(hidden_or_backup_file) { } TEST(skip_dev_prefix) { - assert_se(streq(skip_dev_prefix("/"), "/")); - assert_se(streq(skip_dev_prefix("/dev"), "")); - assert_se(streq(skip_dev_prefix("/dev/"), "")); - assert_se(streq(skip_dev_prefix("/dev/foo"), "foo")); - assert_se(streq(skip_dev_prefix("/dev/foo/bar"), "foo/bar")); - assert_se(streq(skip_dev_prefix("//dev"), "")); - assert_se(streq(skip_dev_prefix("//dev//"), "")); - assert_se(streq(skip_dev_prefix("/dev///foo"), "foo")); - assert_se(streq(skip_dev_prefix("///dev///foo///bar"), "foo///bar")); - assert_se(streq(skip_dev_prefix("//foo"), "//foo")); - assert_se(streq(skip_dev_prefix("foo"), "foo")); + ASSERT_STREQ(skip_dev_prefix("/"), "/"); + ASSERT_STREQ(skip_dev_prefix("/dev"), ""); + ASSERT_STREQ(skip_dev_prefix("/dev/"), ""); + ASSERT_STREQ(skip_dev_prefix("/dev/foo"), "foo"); + ASSERT_STREQ(skip_dev_prefix("/dev/foo/bar"), "foo/bar"); + ASSERT_STREQ(skip_dev_prefix("//dev"), ""); + ASSERT_STREQ(skip_dev_prefix("//dev//"), ""); + ASSERT_STREQ(skip_dev_prefix("/dev///foo"), "foo"); + ASSERT_STREQ(skip_dev_prefix("///dev///foo///bar"), "foo///bar"); + ASSERT_STREQ(skip_dev_prefix("//foo"), "//foo"); + ASSERT_STREQ(skip_dev_prefix("foo"), "foo"); } TEST(empty_or_root) { @@ -1217,43 +1219,43 @@ TEST(empty_or_root) { } TEST(path_startswith_set) { - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo/bar", "/foo/quux", "/foo/bar", "/zzz"), "")); - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo/bar", "/foo/quux", "/foo/", "/zzz"), "bar")); - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo/bar", "/foo/quux", "/foo", "/zzz"), "bar")); - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo/bar", "/foo/quux", "/", "/zzz"), "foo/bar")); - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo/bar", "/foo/quux", "", "/zzz"), NULL)); - - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo/bar2", "/foo/quux", "/foo/bar", "/zzz"), NULL)); - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo/bar2", "/foo/quux", "/foo/", "/zzz"), "bar2")); - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo/bar2", "/foo/quux", "/foo", "/zzz"), "bar2")); - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo/bar2", "/foo/quux", "/", "/zzz"), "foo/bar2")); - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo/bar2", "/foo/quux", "", "/zzz"), NULL)); - - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo2/bar", "/foo/quux", "/foo/bar", "/zzz"), NULL)); - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo2/bar", "/foo/quux", "/foo/", "/zzz"), NULL)); - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo2/bar", "/foo/quux", "/foo", "/zzz"), NULL)); - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo2/bar", "/foo/quux", "/", "/zzz"), "foo2/bar")); - assert_se(streq_ptr(PATH_STARTSWITH_SET("/foo2/bar", "/foo/quux", "", "/zzz"), NULL)); + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo/bar", "/foo/quux", "/foo/bar", "/zzz"), ""); + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo/bar", "/foo/quux", "/foo/", "/zzz"), "bar"); + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo/bar", "/foo/quux", "/foo", "/zzz"), "bar"); + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo/bar", "/foo/quux", "/", "/zzz"), "foo/bar"); + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo/bar", "/foo/quux", "", "/zzz"), NULL); + + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo/bar2", "/foo/quux", "/foo/bar", "/zzz"), NULL); + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo/bar2", "/foo/quux", "/foo/", "/zzz"), "bar2"); + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo/bar2", "/foo/quux", "/foo", "/zzz"), "bar2"); + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo/bar2", "/foo/quux", "/", "/zzz"), "foo/bar2"); + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo/bar2", "/foo/quux", "", "/zzz"), NULL); + + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo2/bar", "/foo/quux", "/foo/bar", "/zzz"), NULL); + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo2/bar", "/foo/quux", "/foo/", "/zzz"), NULL); + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo2/bar", "/foo/quux", "/foo", "/zzz"), NULL); + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo2/bar", "/foo/quux", "/", "/zzz"), "foo2/bar"); + ASSERT_STREQ(PATH_STARTSWITH_SET("/foo2/bar", "/foo/quux", "", "/zzz"), NULL); } TEST(path_startswith_strv) { - assert_se(streq_ptr(path_startswith_strv("/foo/bar", STRV_MAKE("/foo/quux", "/foo/bar", "/zzz")), "")); - assert_se(streq_ptr(path_startswith_strv("/foo/bar", STRV_MAKE("/foo/quux", "/foo/", "/zzz")), "bar")); - assert_se(streq_ptr(path_startswith_strv("/foo/bar", STRV_MAKE("/foo/quux", "/foo", "/zzz")), "bar")); - assert_se(streq_ptr(path_startswith_strv("/foo/bar", STRV_MAKE("/foo/quux", "/", "/zzz")), "foo/bar")); - assert_se(streq_ptr(path_startswith_strv("/foo/bar", STRV_MAKE("/foo/quux", "", "/zzz")), NULL)); - - assert_se(streq_ptr(path_startswith_strv("/foo/bar2", STRV_MAKE("/foo/quux", "/foo/bar", "/zzz")), NULL)); - assert_se(streq_ptr(path_startswith_strv("/foo/bar2", STRV_MAKE("/foo/quux", "/foo/", "/zzz")), "bar2")); - assert_se(streq_ptr(path_startswith_strv("/foo/bar2", STRV_MAKE("/foo/quux", "/foo", "/zzz")), "bar2")); - assert_se(streq_ptr(path_startswith_strv("/foo/bar2", STRV_MAKE("/foo/quux", "/", "/zzz")), "foo/bar2")); - assert_se(streq_ptr(path_startswith_strv("/foo/bar2", STRV_MAKE("/foo/quux", "", "/zzz")), NULL)); - - assert_se(streq_ptr(path_startswith_strv("/foo2/bar", STRV_MAKE("/foo/quux", "/foo/bar", "/zzz")), NULL)); - assert_se(streq_ptr(path_startswith_strv("/foo2/bar", STRV_MAKE("/foo/quux", "/foo/", "/zzz")), NULL)); - assert_se(streq_ptr(path_startswith_strv("/foo2/bar", STRV_MAKE("/foo/quux", "/foo", "/zzz")), NULL)); - assert_se(streq_ptr(path_startswith_strv("/foo2/bar", STRV_MAKE("/foo/quux", "/", "/zzz")), "foo2/bar")); - assert_se(streq_ptr(path_startswith_strv("/foo2/bar", STRV_MAKE("/foo/quux", "", "/zzz")), NULL)); + ASSERT_STREQ(path_startswith_strv("/foo/bar", STRV_MAKE("/foo/quux", "/foo/bar", "/zzz")), ""); + ASSERT_STREQ(path_startswith_strv("/foo/bar", STRV_MAKE("/foo/quux", "/foo/", "/zzz")), "bar"); + ASSERT_STREQ(path_startswith_strv("/foo/bar", STRV_MAKE("/foo/quux", "/foo", "/zzz")), "bar"); + ASSERT_STREQ(path_startswith_strv("/foo/bar", STRV_MAKE("/foo/quux", "/", "/zzz")), "foo/bar"); + ASSERT_STREQ(path_startswith_strv("/foo/bar", STRV_MAKE("/foo/quux", "", "/zzz")), NULL); + + ASSERT_STREQ(path_startswith_strv("/foo/bar2", STRV_MAKE("/foo/quux", "/foo/bar", "/zzz")), NULL); + ASSERT_STREQ(path_startswith_strv("/foo/bar2", STRV_MAKE("/foo/quux", "/foo/", "/zzz")), "bar2"); + ASSERT_STREQ(path_startswith_strv("/foo/bar2", STRV_MAKE("/foo/quux", "/foo", "/zzz")), "bar2"); + ASSERT_STREQ(path_startswith_strv("/foo/bar2", STRV_MAKE("/foo/quux", "/", "/zzz")), "foo/bar2"); + ASSERT_STREQ(path_startswith_strv("/foo/bar2", STRV_MAKE("/foo/quux", "", "/zzz")), NULL); + + ASSERT_STREQ(path_startswith_strv("/foo2/bar", STRV_MAKE("/foo/quux", "/foo/bar", "/zzz")), NULL); + ASSERT_STREQ(path_startswith_strv("/foo2/bar", STRV_MAKE("/foo/quux", "/foo/", "/zzz")), NULL); + ASSERT_STREQ(path_startswith_strv("/foo2/bar", STRV_MAKE("/foo/quux", "/foo", "/zzz")), NULL); + ASSERT_STREQ(path_startswith_strv("/foo2/bar", STRV_MAKE("/foo/quux", "/", "/zzz")), "foo2/bar"); + ASSERT_STREQ(path_startswith_strv("/foo2/bar", STRV_MAKE("/foo/quux", "", "/zzz")), NULL); } static void test_path_glob_can_match_one(const char *pattern, const char *prefix, const char *expected) { @@ -1262,7 +1264,7 @@ static void test_path_glob_can_match_one(const char *pattern, const char *prefix log_debug("%s(%s, %s, %s)", __func__, pattern, prefix, strnull(expected)); assert_se(path_glob_can_match(pattern, prefix, &result) == !!expected); - assert_se(streq_ptr(result, expected)); + ASSERT_STREQ(result, expected); } TEST(path_glob_can_match) { @@ -1305,4 +1307,28 @@ TEST(print_MAX) { assert_cc(FILENAME_MAX == PATH_MAX); } +TEST(path_implies_directory) { + assert_se(!path_implies_directory(NULL)); + assert_se(!path_implies_directory("")); + assert_se(path_implies_directory("/")); + assert_se(path_implies_directory("////")); + assert_se(path_implies_directory("////.///")); + assert_se(path_implies_directory("////./")); + assert_se(path_implies_directory("////.")); + assert_se(path_implies_directory(".")); + assert_se(path_implies_directory("./")); + assert_se(path_implies_directory("/.")); + assert_se(path_implies_directory("..")); + assert_se(path_implies_directory("../")); + assert_se(path_implies_directory("/..")); + assert_se(!path_implies_directory("a")); + assert_se(!path_implies_directory("ab")); + assert_se(path_implies_directory("ab/")); + assert_se(!path_implies_directory("ab/a")); + assert_se(path_implies_directory("ab/a/")); + assert_se(path_implies_directory("ab/a/..")); + assert_se(path_implies_directory("ab/a/.")); + assert_se(path_implies_directory("ab/a//")); +} + DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-path.c b/src/test/test-path.c index 22ed88f..e49653a 100644 --- a/src/test/test-path.c +++ b/src/test/test-path.c @@ -100,7 +100,8 @@ static int _check_states(unsigned line, service_state_to_string(service->state), service_result_to_string(service->result)); - if (service->state == SERVICE_FAILED && service->main_exec_status.status == EXIT_CGROUP) { + if (service->state == SERVICE_FAILED && + (service->main_exec_status.status == EXIT_CGROUP || service->result == SERVICE_FAILURE_RESOURCES)) { const char *ci = ci_environment(); /* On a general purpose system we may fail to start the service for reasons which are diff --git a/src/test/test-pidref.c b/src/test/test-pidref.c new file mode 100644 index 0000000..2c4d894 --- /dev/null +++ b/src/test/test-pidref.c @@ -0,0 +1,225 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include "fd-util.h" +#include "pidref.h" +#include "process-util.h" +#include "signal-util.h" +#include "stdio-util.h" +#include "tests.h" + +TEST(pidref_is_set) { + assert_se(!pidref_is_set(NULL)); + assert_se(!pidref_is_set(&PIDREF_NULL)); + assert_se(pidref_is_set(&PIDREF_MAKE_FROM_PID(1))); +} + +TEST(pidref_equal) { + assert_se(pidref_equal(NULL, NULL)); + assert_se(pidref_equal(NULL, &PIDREF_NULL)); + assert_se(pidref_equal(&PIDREF_NULL, NULL)); + assert_se(pidref_equal(&PIDREF_NULL, &PIDREF_NULL)); + + assert_se(!pidref_equal(NULL, &PIDREF_MAKE_FROM_PID(1))); + assert_se(!pidref_equal(&PIDREF_MAKE_FROM_PID(1), NULL)); + assert_se(!pidref_equal(&PIDREF_NULL, &PIDREF_MAKE_FROM_PID(1))); + assert_se(!pidref_equal(&PIDREF_MAKE_FROM_PID(1), &PIDREF_NULL)); + assert_se(pidref_equal(&PIDREF_MAKE_FROM_PID(1), &PIDREF_MAKE_FROM_PID(1))); + assert_se(!pidref_equal(&PIDREF_MAKE_FROM_PID(1), &PIDREF_MAKE_FROM_PID(2))); +} + +TEST(pidref_set_pid) { + _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL; + int r; + + r = pidref_set_pid(&pidref, 1); + if (r == -ESRCH) + return (void) log_tests_skipped_errno(r, "PID1 does not exist"); + assert_se(r >= 0); + + assert_se(pidref_equal(&pidref, &PIDREF_MAKE_FROM_PID(1))); + assert_se(!pidref_equal(&pidref, &PIDREF_MAKE_FROM_PID(2))); +} + +TEST(pidref_set_self) { + _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL; + + assert_se(pidref_set_self(&pidref) >= 0); + assert_se(pidref_equal(&pidref, &PIDREF_MAKE_FROM_PID(getpid_cached()))); + assert_se(!pidref_equal(&pidref, &PIDREF_MAKE_FROM_PID(getpid_cached()+1))); +} + +TEST(pidref_set_pidstr) { + _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL; + char buf[DECIMAL_STR_MAX(pid_t)]; + + xsprintf(buf, PID_FMT, getpid_cached()); + assert_se(pidref_set_pidstr(&pidref, buf) >= 0); + assert_se(pidref_equal(&pidref, &PIDREF_MAKE_FROM_PID(getpid_cached()))); + assert_se(!pidref_equal(&pidref, &PIDREF_MAKE_FROM_PID(getpid_cached()+1))); +} + +TEST(pidref_set_pidfd) { + _cleanup_(pidref_done) PidRef a = PIDREF_NULL, b = PIDREF_NULL, c = PIDREF_NULL, d = PIDREF_NULL; + + assert_se(pidref_set_self(&a) >= 0); + if (a.fd < 0) + return (void) log_tests_skipped("PIDFD not supported"); + + assert_se(pidref_set_pidfd(&b, a.fd) >= 0); + assert_se(pidref_equal(&a, &b)); + assert_se(pidref_set_pidfd_take(&c, b.fd) >= 0); + b.fd = -EBADF; + assert_se(pidref_equal(&a, &c)); + assert_se(pidref_set_pidfd_consume(&d, TAKE_FD(c.fd)) >= 0); + assert_se(pidref_equal(&a, &d)); +} + +TEST(pidref_is_self) { + _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL; + + assert_se(pidref_set_self(&pidref) >= 0); + assert_se(pidref_is_self(&pidref)); + + assert_se(!pidref_is_self(NULL)); + assert_se(!pidref_is_self(&PIDREF_NULL)); + assert_se(pidref_is_self(&PIDREF_MAKE_FROM_PID(getpid_cached()))); + assert_se(!pidref_is_self(&PIDREF_MAKE_FROM_PID(getpid_cached()+1))); +} + +TEST(pidref_copy) { + _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL; + int r; + + assert_se(pidref_copy(NULL, &pidref) >= 0); + assert_se(!pidref_is_set(&pidref)); + + assert_se(pidref_copy(&PIDREF_NULL, &pidref) >= 0); + assert_se(!pidref_is_set(&pidref)); + + assert_se(pidref_copy(&PIDREF_MAKE_FROM_PID(getpid_cached()), &pidref) >= 0); + assert_se(pidref_is_self(&pidref)); + pidref_done(&pidref); + + r = pidref_copy(&PIDREF_MAKE_FROM_PID(1), &pidref); + if (r == -ESRCH) + return (void) log_tests_skipped_errno(r, "PID1 does not exist"); + assert_se(r >= 0); + assert_se(pidref_equal(&pidref, &PIDREF_MAKE_FROM_PID(1))); +} + +TEST(pidref_dup) { + _cleanup_(pidref_freep) PidRef *pidref = NULL; + int r; + + assert_se(pidref_dup(NULL, &pidref) >= 0); + assert_se(pidref); + assert_se(!pidref_is_set(pidref)); + pidref = pidref_free(pidref); + + assert_se(pidref_dup(&PIDREF_NULL, &pidref) >= 0); + assert_se(pidref); + assert_se(!pidref_is_set(pidref)); + pidref = pidref_free(pidref); + + assert_se(pidref_dup(&PIDREF_MAKE_FROM_PID(getpid_cached()), &pidref) >= 0); + assert_se(pidref_is_self(pidref)); + pidref = pidref_free(pidref); + + r = pidref_dup(&PIDREF_MAKE_FROM_PID(1), &pidref); + if (r == -ESRCH) + return (void) log_tests_skipped_errno(r, "PID1 does not exist"); + assert_se(r >= 0); + assert_se(pidref_equal(pidref, &PIDREF_MAKE_FROM_PID(1))); +} + +TEST(pidref_new_from_pid) { + _cleanup_(pidref_freep) PidRef *pidref = NULL; + int r; + + assert_se(pidref_new_from_pid(-1, &pidref) == -ESRCH); + assert_se(!pidref); + + assert_se(pidref_new_from_pid(0, &pidref) >= 0); + assert_se(pidref_is_self(pidref)); + pidref = pidref_free(pidref); + + assert_se(pidref_new_from_pid(getpid_cached(), &pidref) >= 0); + assert_se(pidref_is_self(pidref)); + pidref = pidref_free(pidref); + + r = pidref_new_from_pid(1, &pidref); + if (r == -ESRCH) + return (void) log_tests_skipped_errno(r, "PID1 does not exist"); + assert_se(r >= 0); + assert_se(pidref_equal(pidref, &PIDREF_MAKE_FROM_PID(1))); +} + +TEST(pidref_kill) { + _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL; + siginfo_t si; + int r; + + r = pidref_safe_fork("(test-pidref-kill)", FORK_DEATHSIG_SIGKILL, &pidref); + assert_se(r >= 0); + if (r == 0) + freeze(); + + assert_se(pidref_kill(&pidref, SIGKILL) >= 0); + assert_se(pidref_wait_for_terminate(&pidref, &si) >= 0); + assert_se(si.si_signo == SIGCHLD); +} + +TEST(pidref_kill_and_sigcont) { + _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL; + siginfo_t si; + int r; + + r = pidref_safe_fork("(test-pidref-kill-and-sigcont)", FORK_DEATHSIG_SIGTERM, &pidref); + assert_se(r >= 0); + if (r == 0) + freeze(); + + assert_se(pidref_kill_and_sigcont(&pidref, SIGTERM) >= 0); + assert_se(pidref_wait_for_terminate(&pidref, &si) >= 0); + assert_se(si.si_signo == SIGCHLD); +} + +TEST(pidref_sigqueue) { + _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL; + siginfo_t si; + int r; + + r = pidref_safe_fork("(test-pidref-sigqueue)", FORK_DEATHSIG_SIGTERM, &pidref); + assert_se(r >= 0); + if (r == 0) + freeze(); + + assert_se(pidref_sigqueue(&pidref, SIGTERM, 42) >= 0); + assert_se(pidref_wait_for_terminate(&pidref, &si) >= 0); + assert_se(si.si_signo == SIGCHLD); +} + +TEST(pidref_done_sigkill_wait) { + _cleanup_(pidref_done_sigkill_wait) PidRef pidref = PIDREF_NULL; + int r; + + r = pidref_safe_fork("(test-pidref-done-sigkill-wait)", FORK_DEATHSIG_SIGKILL, &pidref); + assert_se(r >= 0); + if (r == 0) + freeze(); +} + +TEST(pidref_verify) { + _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL; + + assert_se(pidref_verify(NULL) == -ESRCH); + assert_se(pidref_verify(&PIDREF_NULL) == -ESRCH); + + assert_se(pidref_verify(&PIDREF_MAKE_FROM_PID(1)) == 1); + assert_se(pidref_verify(&PIDREF_MAKE_FROM_PID(getpid_cached())) == 0); + + assert_se(pidref_set_self(&pidref) >= 0); + assert_se(pidref_verify(&pidref) == (pidref.fd >= 0)); +} + +DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-pretty-print.c b/src/test/test-pretty-print.c index 52b2bc8..9ab52c6 100644 --- a/src/test/test-pretty-print.c +++ b/src/test/test-pretty-print.c @@ -22,7 +22,7 @@ static void test_draw_cylon_one(unsigned pos) { memset(buf, 0xff, sizeof(buf)); draw_cylon(buf, sizeof(buf), CYLON_WIDTH, pos); - assert_se(strlen(buf) < sizeof(buf)); + ASSERT_LE(strlen(buf), sizeof(buf)); } TEST(draw_cylon) { diff --git a/src/test/test-prioq.c b/src/test/test-prioq.c index 540863c..92c22d3 100644 --- a/src/test/test-prioq.c +++ b/src/test/test-prioq.c @@ -54,7 +54,7 @@ static int test_compare(const struct test *x, const struct test *y) { } static void test_hash(const struct test *x, struct siphash *state) { - siphash24_compress(&x->value, sizeof(x->value), state); + siphash24_compress_typesafe(x->value, state); } DEFINE_PRIVATE_HASH_OPS(test_hash_ops, struct test, test_hash, test_compare); @@ -70,10 +70,10 @@ TEST(struct) { assert_se(q = prioq_new((compare_func_t) test_compare)); assert_se(s = set_new(&test_hash_ops)); - assert_se(prioq_peek(q) == NULL); - assert_se(prioq_peek_by_index(q, 0) == NULL); - assert_se(prioq_peek_by_index(q, 1) == NULL); - assert_se(prioq_peek_by_index(q, UINT_MAX) == NULL); + ASSERT_NULL(prioq_peek(q)); + ASSERT_NULL(prioq_peek_by_index(q, 0)); + ASSERT_NULL(prioq_peek_by_index(q, 1)); + ASSERT_NULL(prioq_peek_by_index(q, UINT_MAX)); for (i = 0; i < SET_SIZE; i++) { assert_se(t = new0(struct test, 1)); @@ -87,7 +87,7 @@ TEST(struct) { for (i = 0; i < SET_SIZE; i++) assert_se(prioq_peek_by_index(q, i)); - assert_se(prioq_peek_by_index(q, SET_SIZE) == NULL); + ASSERT_NULL(prioq_peek_by_index(q, SET_SIZE)); unsigned count = 0; PRIOQ_FOREACH_ITEM(q, t) { diff --git a/src/test/test-proc-cmdline.c b/src/test/test-proc-cmdline.c index 8b5bbb0..420f312 100644 --- a/src/test/test-proc-cmdline.c +++ b/src/test/test-proc-cmdline.c @@ -37,7 +37,7 @@ TEST(proc_cmdline_override) { /* First test if the overrides for /proc/cmdline still work */ assert_se(proc_cmdline(&line) >= 0); - assert_se(streq(line, "foo_bar=quux wuff-piep=tuet zumm some_arg_with_space='foo bar' and_one_more=\"zzz aaa\"")); + ASSERT_STREQ(line, "foo_bar=quux wuff-piep=tuet zumm some_arg_with_space='foo bar' and_one_more=\"zzz aaa\""); line = mfree(line); assert_se(proc_cmdline_strv(&args) >= 0); assert_se(strv_equal(args, STRV_MAKE("foo_bar=quux", "wuff-piep=tuet", "zumm", "some_arg_with_space=foo bar", "and_one_more=zzz aaa"))); @@ -57,7 +57,7 @@ TEST(proc_cmdline_override) { assert_se(putenv((char*) "SYSTEMD_EFI_OPTIONS=foo_bar=quux wuff-piep=tuet zumm some_arg_with_space='foo bar' and_one_more=\"zzz aaa\"") == 0); assert_se(proc_cmdline(&line) >= 0); - assert_se(streq(line, "hoge")); + ASSERT_STREQ(line, "hoge"); line = mfree(line); assert_se(proc_cmdline_strv(&args) >= 0); assert_se(strv_equal(args, STRV_MAKE("hoge"))); @@ -83,13 +83,13 @@ static int parse_item_given(const char *key, const char *value, void *data) { log_info("%s: option <%s> = <%s>", __func__, key, strna(value)); if (proc_cmdline_key_streq(key, "foo_bar")) - assert_se(streq(value, "quux")); + ASSERT_STREQ(value, "quux"); else if (proc_cmdline_key_streq(key, "wuff-piep")) - assert_se(streq(value, "tuet ")); + ASSERT_STREQ(value, "tuet "); else if (proc_cmdline_key_streq(key, "space")) - assert_se(streq(value, "x y z")); + ASSERT_STREQ(value, "x y z"); else if (proc_cmdline_key_streq(key, "miepf")) - assert_se(streq(value, "uuu")); + ASSERT_STREQ(value, "uuu"); else if (in_initrd() && *strip && proc_cmdline_key_streq(key, "zumm")) assert_se(!value); else if (in_initrd() && !*strip && proc_cmdline_key_streq(key, "rd.zumm")) @@ -231,13 +231,13 @@ TEST(proc_cmdline_get_key_many) { "doubleticks", &value6, "zummm", &value7) == 5); - assert_se(streq_ptr(value1, "quux")); + ASSERT_STREQ(value1, "quux"); assert_se(!value2); - assert_se(streq_ptr(value3, "tuet")); + ASSERT_STREQ(value3, "tuet"); assert_se(!value4); - assert_se(streq_ptr(value5, "one two")); - assert_se(streq_ptr(value6, " aaa aaa ")); - assert_se(streq_ptr(value7, "\n")); + ASSERT_STREQ(value5, "one two"); + ASSERT_STREQ(value6, " aaa aaa "); + ASSERT_STREQ(value7, "\n"); } TEST(proc_cmdline_key_streq) { diff --git a/src/test/test-process-util.c b/src/test/test-process-util.c index 957e214..c96bd43 100644 --- a/src/test/test-process-util.c +++ b/src/test/test-process-util.c @@ -176,7 +176,7 @@ static void test_pid_get_comm_escape_one(const char *input, const char *output) log_debug("got: <%s>", n); - assert_se(streq_ptr(n, output)); + ASSERT_STREQ(n, output); } TEST(pid_get_comm_escape) { @@ -236,14 +236,14 @@ TEST(personality) { assert_se(personality_to_string(PER_LINUX)); assert_se(!personality_to_string(PERSONALITY_INVALID)); - assert_se(streq(personality_to_string(PER_LINUX), architecture_to_string(native_architecture()))); + ASSERT_STREQ(personality_to_string(PER_LINUX), architecture_to_string(native_architecture())); assert_se(personality_from_string(personality_to_string(PER_LINUX)) == PER_LINUX); assert_se(personality_from_string(architecture_to_string(native_architecture())) == PER_LINUX); #ifdef __x86_64__ - assert_se(streq_ptr(personality_to_string(PER_LINUX), "x86-64")); - assert_se(streq_ptr(personality_to_string(PER_LINUX32), "x86")); + ASSERT_STREQ(personality_to_string(PER_LINUX), "x86-64"); + ASSERT_STREQ(personality_to_string(PER_LINUX32), "x86"); assert_se(personality_from_string("x86-64") == PER_LINUX); assert_se(personality_from_string("x86") == PER_LINUX32); @@ -328,49 +328,49 @@ TEST(pid_get_cmdline_harder) { assert_se(pid_get_cmdline(0, SIZE_MAX, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "[testa]")); + ASSERT_STREQ(line, "[testa]"); line = mfree(line); assert_se(pid_get_cmdline(0, SIZE_MAX, PROCESS_CMDLINE_COMM_FALLBACK | PROCESS_CMDLINE_QUOTE, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "\"[testa]\"")); /* quoting is enabled here */ + ASSERT_STREQ(line, "\"[testa]\""); /* quoting is enabled here */ line = mfree(line); assert_se(pid_get_cmdline(0, 0, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "")); + ASSERT_STREQ(line, ""); line = mfree(line); assert_se(pid_get_cmdline(0, 1, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); - assert_se(streq(line, "…")); + ASSERT_STREQ(line, "…"); line = mfree(line); assert_se(pid_get_cmdline(0, 2, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); - assert_se(streq(line, "[…")); + ASSERT_STREQ(line, "[…"); line = mfree(line); assert_se(pid_get_cmdline(0, 3, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); - assert_se(streq(line, "[t…")); + ASSERT_STREQ(line, "[t…"); line = mfree(line); assert_se(pid_get_cmdline(0, 4, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); - assert_se(streq(line, "[te…")); + ASSERT_STREQ(line, "[te…"); line = mfree(line); assert_se(pid_get_cmdline(0, 5, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); - assert_se(streq(line, "[tes…")); + ASSERT_STREQ(line, "[tes…"); line = mfree(line); assert_se(pid_get_cmdline(0, 6, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); - assert_se(streq(line, "[test…")); + ASSERT_STREQ(line, "[test…"); line = mfree(line); assert_se(pid_get_cmdline(0, 7, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); - assert_se(streq(line, "[testa]")); + ASSERT_STREQ(line, "[testa]"); line = mfree(line); assert_se(pid_get_cmdline(0, 8, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); - assert_se(streq(line, "[testa]")); + ASSERT_STREQ(line, "[testa]"); line = mfree(line); assert_se(pid_get_cmdline_strv(0, PROCESS_CMDLINE_COMM_FALLBACK, &args) >= 0); @@ -383,11 +383,11 @@ TEST(pid_get_cmdline_harder) { assert_se(pid_get_cmdline(0, SIZE_MAX, 0, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo bar")); + ASSERT_STREQ(line, "foo bar"); line = mfree(line); assert_se(pid_get_cmdline(0, SIZE_MAX, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); - assert_se(streq(line, "foo bar")); + ASSERT_STREQ(line, "foo bar"); line = mfree(line); assert_se(pid_get_cmdline_strv(0, PROCESS_CMDLINE_COMM_FALLBACK, &args) >= 0); @@ -397,87 +397,87 @@ TEST(pid_get_cmdline_harder) { assert_se(write(fd, "quux", 4) == 4); assert_se(pid_get_cmdline(0, SIZE_MAX, 0, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo bar quux")); + ASSERT_STREQ(line, "foo bar quux"); line = mfree(line); assert_se(pid_get_cmdline(0, SIZE_MAX, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo bar quux")); + ASSERT_STREQ(line, "foo bar quux"); line = mfree(line); assert_se(pid_get_cmdline(0, 1, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "…")); + ASSERT_STREQ(line, "…"); line = mfree(line); assert_se(pid_get_cmdline(0, 2, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "f…")); + ASSERT_STREQ(line, "f…"); line = mfree(line); assert_se(pid_get_cmdline(0, 3, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "fo…")); + ASSERT_STREQ(line, "fo…"); line = mfree(line); assert_se(pid_get_cmdline(0, 4, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo…")); + ASSERT_STREQ(line, "foo…"); line = mfree(line); assert_se(pid_get_cmdline(0, 5, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo …")); + ASSERT_STREQ(line, "foo …"); line = mfree(line); assert_se(pid_get_cmdline(0, 6, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo b…")); + ASSERT_STREQ(line, "foo b…"); line = mfree(line); assert_se(pid_get_cmdline(0, 7, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo ba…")); + ASSERT_STREQ(line, "foo ba…"); line = mfree(line); assert_se(pid_get_cmdline(0, 8, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo bar…")); + ASSERT_STREQ(line, "foo bar…"); line = mfree(line); assert_se(pid_get_cmdline(0, 9, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo bar …")); + ASSERT_STREQ(line, "foo bar …"); line = mfree(line); assert_se(pid_get_cmdline(0, 10, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo bar q…")); + ASSERT_STREQ(line, "foo bar q…"); line = mfree(line); assert_se(pid_get_cmdline(0, 11, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo bar qu…")); + ASSERT_STREQ(line, "foo bar qu…"); line = mfree(line); assert_se(pid_get_cmdline(0, 12, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo bar quux")); + ASSERT_STREQ(line, "foo bar quux"); line = mfree(line); assert_se(pid_get_cmdline(0, 13, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo bar quux")); + ASSERT_STREQ(line, "foo bar quux"); line = mfree(line); assert_se(pid_get_cmdline(0, 14, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo bar quux")); + ASSERT_STREQ(line, "foo bar quux"); line = mfree(line); assert_se(pid_get_cmdline(0, 1000, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "foo bar quux")); + ASSERT_STREQ(line, "foo bar quux"); line = mfree(line); assert_se(pid_get_cmdline_strv(0, PROCESS_CMDLINE_COMM_FALLBACK, &args) >= 0); @@ -491,22 +491,22 @@ TEST(pid_get_cmdline_harder) { assert_se(pid_get_cmdline(0, SIZE_MAX, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "[aaaa bbbb cccc]")); + ASSERT_STREQ(line, "[aaaa bbbb cccc]"); line = mfree(line); assert_se(pid_get_cmdline(0, 10, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "[aaaa bbb…")); + ASSERT_STREQ(line, "[aaaa bbb…"); line = mfree(line); assert_se(pid_get_cmdline(0, 11, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "[aaaa bbbb…")); + ASSERT_STREQ(line, "[aaaa bbbb…"); line = mfree(line); assert_se(pid_get_cmdline(0, 12, PROCESS_CMDLINE_COMM_FALLBACK, &line) >= 0); log_debug("'%s'", line); - assert_se(streq(line, "[aaaa bbbb …")); + ASSERT_STREQ(line, "[aaaa bbbb …"); line = mfree(line); assert_se(pid_get_cmdline_strv(0, PROCESS_CMDLINE_COMM_FALLBACK, &args) >= 0); @@ -527,13 +527,13 @@ TEST(pid_get_cmdline_harder) { assert_se(pid_get_cmdline(0, SIZE_MAX, PROCESS_CMDLINE_QUOTE, &line) >= 0); log_debug("got: ==%s==", line); log_debug("exp: ==%s==", EXPECT1); - assert_se(streq(line, EXPECT1)); + ASSERT_STREQ(line, EXPECT1); line = mfree(line); assert_se(pid_get_cmdline(0, SIZE_MAX, PROCESS_CMDLINE_QUOTE_POSIX, &line) >= 0); log_debug("got: ==%s==", line); log_debug("exp: ==%s==", EXPECT1p); - assert_se(streq(line, EXPECT1p)); + ASSERT_STREQ(line, EXPECT1p); line = mfree(line); assert_se(pid_get_cmdline_strv(0, 0, &args) >= 0); @@ -552,13 +552,13 @@ TEST(pid_get_cmdline_harder) { assert_se(pid_get_cmdline(0, SIZE_MAX, PROCESS_CMDLINE_QUOTE, &line) >= 0); log_debug("got: ==%s==", line); log_debug("exp: ==%s==", EXPECT2); - assert_se(streq(line, EXPECT2)); + ASSERT_STREQ(line, EXPECT2); line = mfree(line); assert_se(pid_get_cmdline(0, SIZE_MAX, PROCESS_CMDLINE_QUOTE_POSIX, &line) >= 0); log_debug("got: ==%s==", line); log_debug("exp: ==%s==", EXPECT2p); - assert_se(streq(line, EXPECT2p)); + ASSERT_STREQ(line, EXPECT2p); line = mfree(line); assert_se(pid_get_cmdline_strv(0, 0, &args) >= 0); @@ -651,7 +651,7 @@ TEST(safe_fork) { TEST(pid_to_ptr) { assert_se(PTR_TO_PID(NULL) == 0); - assert_se(PID_TO_PTR(0) == NULL); + ASSERT_NULL(PID_TO_PTR(0)); assert_se(PTR_TO_PID(PID_TO_PTR(1)) == 1); assert_se(PTR_TO_PID(PID_TO_PTR(2)) == 2); @@ -946,6 +946,27 @@ TEST(is_reaper_process) { } } +TEST(pid_get_start_time) { + _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL; + + assert_se(pidref_set_self(&pidref) >= 0); + + uint64_t start_time; + assert_se(pidref_get_start_time(&pidref, &start_time) >= 0); + log_info("our starttime: %" PRIu64, start_time); + + _cleanup_(pidref_done_sigkill_wait) PidRef child = PIDREF_NULL; + + assert_se(pidref_safe_fork("(stub)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS, &child) >= 0); + + uint64_t start_time2; + assert_se(pidref_get_start_time(&child, &start_time2) >= 0); + + log_info("child starttime: %" PRIu64, start_time2); + + assert_se(start_time2 >= start_time); +} + static int intro(void) { log_show_color(true); return EXIT_SUCCESS; diff --git a/src/test/test-progress-bar.c b/src/test/test-progress-bar.c new file mode 100644 index 0000000..b47adf0 --- /dev/null +++ b/src/test/test-progress-bar.c @@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include "pretty-print.h" +#include "random-util.h" +#include "tests.h" + +#define PROGRESS_PREFIX "test: " + +TEST(progress_bar) { + + draw_progress_bar(PROGRESS_PREFIX, 0); + + bool paused = false; + + for (double d = 0; d <= 100; d += 0.5) { + usleep_safe(random_u64_range(20 * USEC_PER_MSEC)); + draw_progress_bar(PROGRESS_PREFIX, d); + + if (!paused && d >= 50) { + clear_progress_bar(PROGRESS_PREFIX); + fputs("Sleeping for 1s...", stdout); + fflush(stdout); + usleep_safe(USEC_PER_SEC); + paused = true; + } + } + + draw_progress_bar(PROGRESS_PREFIX, 100); + usleep_safe(300 * MSEC_PER_SEC); + clear_progress_bar(PROGRESS_PREFIX); + fputs("Done.\n", stdout); +} + +DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-recovery-key.c b/src/test/test-recovery-key.c new file mode 100644 index 0000000..8d5ed71 --- /dev/null +++ b/src/test/test-recovery-key.c @@ -0,0 +1,137 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include <string.h> + +#include "memory-util.h" +#include "random-util.h" +#include "recovery-key.h" +#include "tests.h" + +TEST(make_recovery_key) { + _cleanup_(erase_and_freep) char *recovery_key = NULL; + size_t length; + const size_t num_test = 10; + char *generated_keys[num_test]; + int r; + + /* Check for successful recovery-key creation */ + r = make_recovery_key(&recovery_key); + assert_se(r == 0); + ASSERT_NOT_NULL(recovery_key); + + /* Check that length of formatted key is 72 with 64 modhex characters */ + length = strlen(recovery_key); + assert_se(length == RECOVERY_KEY_MODHEX_FORMATTED_LENGTH - 1); + /* Check modhex characters in formatted key with dashes */ + for (size_t i = 0; i < length; i++) { + assert_se((recovery_key[i] >= 'a' && recovery_key[i] <= 'v') || recovery_key[i] == '-'); + if (i % 9 == 8) + /* confirm '-' is after every 8 characters */ + assert_se(recovery_key[i] == '-'); + } + /* Repeat tests to determine randomness of generated keys */ + for (size_t test = 0; test < num_test; ++test) { + r = make_recovery_key(&generated_keys[test]); + assert_se(r == 0); + length = strlen(generated_keys[test]); + assert_se(length == RECOVERY_KEY_MODHEX_FORMATTED_LENGTH - 1); + for (size_t i = 0; i < length; i++) { + assert_se((generated_keys[test][i] >= 'a' && generated_keys[test][i] <= 'v') + || generated_keys[test][i] == '-'); + if (i % 9 == 8) + assert_se(generated_keys[test][i] == '-'); + } + /* Check for uniqueness of each generated recovery key */ + for (size_t prev = 0; prev < test; ++prev) + assert_se(!streq(generated_keys[test], generated_keys[prev])); + } + for (size_t i = 0; i < num_test; i++) + free(generated_keys[i]); +} + +TEST(decode_modhex_char) { + + assert_se(decode_modhex_char('c') == 0); + assert_se(decode_modhex_char('C') == 0); + assert_se(decode_modhex_char('b') == 1); + assert_se(decode_modhex_char('B') == 1); + assert_se(decode_modhex_char('d') == 2); + assert_se(decode_modhex_char('D') == 2); + assert_se(decode_modhex_char('e') == 3); + assert_se(decode_modhex_char('E') == 3); + assert_se(decode_modhex_char('f') == 4); + assert_se(decode_modhex_char('F') == 4); + assert_se(decode_modhex_char('g') == 5); + assert_se(decode_modhex_char('G') == 5); + assert_se(decode_modhex_char('h') == 6); + assert_se(decode_modhex_char('H') == 6); + assert_se(decode_modhex_char('i') == 7); + assert_se(decode_modhex_char('I') == 7); + assert_se(decode_modhex_char('j') == 8); + assert_se(decode_modhex_char('J') == 8); + assert_se(decode_modhex_char('k') == 9); + assert_se(decode_modhex_char('K') == 9); + assert_se(decode_modhex_char('l') == 10); + assert_se(decode_modhex_char('L') == 10); + assert_se(decode_modhex_char('n') == 11); + assert_se(decode_modhex_char('N') == 11); + assert_se(decode_modhex_char('r') == 12); + assert_se(decode_modhex_char('R') == 12); + assert_se(decode_modhex_char('t') == 13); + assert_se(decode_modhex_char('T') == 13); + assert_se(decode_modhex_char('u') == 14); + assert_se(decode_modhex_char('U') == 14); + assert_se(decode_modhex_char('v') == 15); + assert_se(decode_modhex_char('V') == 15); + assert_se(decode_modhex_char('a') == -EINVAL); + assert_se(decode_modhex_char('A') == -EINVAL); + assert_se(decode_modhex_char('x') == -EINVAL); + assert_se(decode_modhex_char('.') == -EINVAL); + assert_se(decode_modhex_char('/') == -EINVAL); + assert_se(decode_modhex_char('\0') == -EINVAL); +} + +TEST(normalize_recovery_key) { + _cleanup_(erase_and_freep) char *normalized_key1 = NULL; + _cleanup_(erase_and_freep) char *normalized_key2 = NULL; + _cleanup_(erase_and_freep) char *normalized_key3 = NULL; + int r; + + /* Case 1: Normalization without dashes */ + r = normalize_recovery_key("cdefghijcdefghijcdefghijcdefghijcdefghijcdefghijcdefghijcdefghij", + &normalized_key1); + assert(r == 0); + assert(streq(normalized_key1, "cdefghij-cdefghij-cdefghij-cdefghij-cdefghij-cdefghij-cdefghij-cdefghij")); + + /* Case 2: Normalization with dashes */ + r = normalize_recovery_key("cdefVhij-cDefghij-cdefkhij-cdufghij-cdefgdij-cidefIhj-cdefNijR-cdVfguij", + &normalized_key2); + assert_se(r == 0); + ASSERT_STREQ(normalized_key2, "cdefvhij-cdefghij-cdefkhij-cdufghij-cdefgdij-cidefihj-cdefnijr-cdvfguij"); + + /* Case 3: Invalid password length */ + r = normalize_recovery_key("1234-5678-90AB-CDEF-1234-5678-90AB-CDEF", &normalized_key1); + assert(r == -EINVAL); + + /* Case 4: Invalid password format(missing dash) */ + r = normalize_recovery_key("cdefghij-cdefghij-cdefghij-cdefghij-cdefghij-cdefghij-cdefghijcdefghij", + &normalized_key1); + assert_se(r == -EINVAL); + + /* Case 5: Normalization of Upper cases password without dashes */ + r = normalize_recovery_key("BFGHICEHHIUVLKJIHFHEDlntruvcdefjiTUVKLNIJVTUTKJIHDFBCBGHIJHHFDBC", + &normalized_key3); + assert(r == 0); + ASSERT_STREQ(normalized_key3, "bfghiceh-hiuvlkji-hfhedlnt-ruvcdefj-ituvklni-jvtutkji-hdfbcbgh-ijhhfdbc"); + + /* Case 6: Minimum password length */ + r = normalize_recovery_key("", &normalized_key1); + assert_se(r == -EINVAL); + + /* Case 7: Invalid characters and numbers in password */ + r = normalize_recovery_key("cde123hi-cdefgzij-cdefghij-cdefghij-cdefghij-cdefghij-cdefghijcdefghij", + &normalized_key1); + assert_se(r == -EINVAL); +} + +DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-replace-var.c b/src/test/test-replace-var.c index f861b27..56634a8 100644 --- a/src/test/test-replace-var.c +++ b/src/test/test-replace-var.c @@ -16,7 +16,7 @@ TEST(replace_var) { assert_se(r = replace_var("@@@foobar@xyz@HALLO@foobar@test@@testtest@TEST@...@@@", lookup, NULL)); puts(r); - assert_se(streq(r, "@@@foobar@xyz<<<HALLO>>>foobar@test@@testtest<<<TEST>>>...@@@")); + ASSERT_STREQ(r, "@@@foobar@xyz<<<HALLO>>>foobar@test@@testtest<<<TEST>>>...@@@"); free(r); } @@ -25,7 +25,7 @@ TEST(strreplace) { assert_se(r = strreplace("XYZFFFFXYZFFFFXYZ", "XYZ", "ABC")); puts(r); - assert_se(streq(r, "ABCFFFFABCFFFFABC")); + ASSERT_STREQ(r, "ABCFFFFABCFFFFABC"); free(r); } diff --git a/src/test/test-rlimit-util.c b/src/test/test-rlimit-util.c index 86d0c04..fc9e89c 100644 --- a/src/test/test-rlimit-util.c +++ b/src/test/test-rlimit-util.c @@ -1,15 +1,20 @@ /* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/resource.h> +#if HAVE_VALGRIND_VALGRIND_H +#include <valgrind/valgrind.h> +#endif #include "alloc-util.h" #include "capability-util.h" #include "macro.h" #include "missing_resource.h" +#include "process-util.h" #include "rlimit-util.h" #include "string-util.h" #include "tests.h" #include "time-util.h" +#include "user-util.h" static void test_rlimit_parse_format_one(int resource, const char *string, rlim_t soft, rlim_t hard, int ret, const char *formatted) { _cleanup_free_ char *f = NULL; @@ -29,7 +34,7 @@ static void test_rlimit_parse_format_one(int resource, const char *string, rlim_ assert_se(rl.rlim_max == hard); assert_se(rlimit_format(&rl, &f) >= 0); - assert_se(streq(formatted, f)); + ASSERT_STREQ(formatted, f); assert_se(rlimit_parse(resource, formatted, &rl2) >= 0); assert_se(memcmp(&rl, &rl2, sizeof(struct rlimit)) == 0); @@ -113,8 +118,8 @@ TEST(setrlimit) { new.rlim_max = old.rlim_max; assert_se(setrlimit(RLIMIT_NOFILE, &new) >= 0); - assert_se(streq_ptr(rlimit_to_string(RLIMIT_NOFILE), "NOFILE")); - assert_se(rlimit_to_string(-1) == NULL); + ASSERT_STREQ(rlimit_to_string(RLIMIT_NOFILE), "NOFILE"); + ASSERT_NULL(rlimit_to_string(-1)); assert_se(getrlimit(RLIMIT_NOFILE, &old) == 0); assert_se(setrlimit_closest(RLIMIT_NOFILE, &old) == 0); @@ -136,4 +141,45 @@ TEST(setrlimit) { assert_se(old.rlim_max == new.rlim_max); } +TEST(pid_getrlimit) { + int r; + + /* We fork off a child and read the parent's resource limit from there (i.e. our own), and compare + * with what getrlimit() gives us */ + + for (int resource = 0; resource < _RLIMIT_MAX; resource++) { + struct rlimit direct; + + assert_se(getrlimit(resource, &direct) >= 0); + + /* We fork off a child so that getrlimit() doesn't work anymore */ + r = safe_fork("(getrlimit)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_LOG|FORK_WAIT, /* ret_pid= */ NULL); + assert_se(r >= 0); + + if (r == 0) { + struct rlimit indirect; + /* child */ + + /* Drop privs, so that prlimit() doesn't work anymore */ + (void) setresgid(GID_NOBODY, GID_NOBODY, GID_NOBODY); + (void) setresuid(UID_NOBODY, UID_NOBODY, UID_NOBODY); + + assert_se(pid_getrlimit(getppid(), resource, &indirect) >= 0); + +#if HAVE_VALGRIND_VALGRIND_H + /* Valgrind fakes some changes in RLIMIT_NOFILE getrlimit() returns, work around that */ + if (RUNNING_ON_VALGRIND && resource == RLIMIT_NOFILE) { + log_info("Skipping pid_getrlimit() check for RLIMIT_NOFILE, running in valgrind"); + _exit(EXIT_SUCCESS); + } +#endif + + assert_se(direct.rlim_cur == indirect.rlim_cur); + assert_se(direct.rlim_max == indirect.rlim_max); + + _exit(EXIT_SUCCESS); + } + } +} + DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-sd-hwdb.c b/src/test/test-sd-hwdb.c index ecb6118..307609c 100644 --- a/src/test/test-sd-hwdb.c +++ b/src/test/test-sd-hwdb.c @@ -18,8 +18,8 @@ TEST(failed_enumerate) { assert_se(sd_hwdb_seek(hwdb, "no-such-modalias-should-exist") == 0); assert_se(sd_hwdb_enumerate(hwdb, &key, &value) == 0); - assert_se(sd_hwdb_enumerate(hwdb, &key, NULL) == -EINVAL); - assert_se(sd_hwdb_enumerate(hwdb, NULL, &value) == -EINVAL); + ASSERT_RETURN_EXPECTED_SE(sd_hwdb_enumerate(hwdb, &key, NULL) == -EINVAL); + ASSERT_RETURN_EXPECTED_SE(sd_hwdb_enumerate(hwdb, NULL, &value) == -EINVAL); } #define DELL_MODALIAS \ @@ -58,8 +58,8 @@ TEST(sd_hwdb_new_from_path) { _cleanup_(sd_hwdb_unrefp) sd_hwdb *hwdb = NULL; int r; - assert_se(sd_hwdb_new_from_path(NULL, &hwdb) == -EINVAL); - assert_se(sd_hwdb_new_from_path("", &hwdb) == -EINVAL); + ASSERT_RETURN_EXPECTED_SE(sd_hwdb_new_from_path(NULL, &hwdb) == -EINVAL); + ASSERT_RETURN_EXPECTED_SE(sd_hwdb_new_from_path("", &hwdb) == -EINVAL); assert_se(sd_hwdb_new_from_path("/path/that/should/not/exist", &hwdb) < 0); NULSTR_FOREACH(hwdb_bin_path, hwdb_bin_paths) { diff --git a/src/test/test-seccomp.c b/src/test/test-seccomp.c index 279a155..74d950a 100644 --- a/src/test/test-seccomp.c +++ b/src/test/test-seccomp.c @@ -52,40 +52,40 @@ TEST(parse_syscall_and_errno) { int e; assert_se(parse_syscall_and_errno("uname:EILSEQ", &n, &e) >= 0); - assert_se(streq(n, "uname")); + ASSERT_STREQ(n, "uname"); assert_se(e == errno_from_name("EILSEQ") && e >= 0); n = mfree(n); assert_se(parse_syscall_and_errno("uname:EINVAL", &n, &e) >= 0); - assert_se(streq(n, "uname")); + ASSERT_STREQ(n, "uname"); assert_se(e == errno_from_name("EINVAL") && e >= 0); n = mfree(n); assert_se(parse_syscall_and_errno("@sync:4095", &n, &e) >= 0); - assert_se(streq(n, "@sync")); + ASSERT_STREQ(n, "@sync"); assert_se(e == 4095); n = mfree(n); /* If errno is omitted, then e is set to -1 */ assert_se(parse_syscall_and_errno("mount", &n, &e) >= 0); - assert_se(streq(n, "mount")); + ASSERT_STREQ(n, "mount"); assert_se(e == -1); n = mfree(n); /* parse_syscall_and_errno() does not check the syscall name is valid or not. */ assert_se(parse_syscall_and_errno("hoge:255", &n, &e) >= 0); - assert_se(streq(n, "hoge")); + ASSERT_STREQ(n, "hoge"); assert_se(e == 255); n = mfree(n); /* 0 is also a valid errno. */ assert_se(parse_syscall_and_errno("hoge:0", &n, &e) >= 0); - assert_se(streq(n, "hoge")); + ASSERT_STREQ(n, "hoge"); assert_se(e == 0); n = mfree(n); assert_se(parse_syscall_and_errno("hoge:kill", &n, &e) >= 0); - assert_se(streq(n, "hoge")); + ASSERT_STREQ(n, "hoge"); assert_se(e == SECCOMP_ERROR_NUMBER_KILL); n = mfree(n); @@ -151,7 +151,7 @@ TEST(architecture_table) { assert_se(seccomp_arch_from_string(n, &c) >= 0); n2 = seccomp_arch_to_string(c); log_info("seccomp-arch: %s → 0x%"PRIx32" → %s", n, c, n2); - assert_se(streq_ptr(n, n2)); + ASSERT_STREQ(n, n2); } } @@ -231,11 +231,11 @@ TEST(filter_sets) { TEST(filter_sets_ordered) { /* Ensure "@default" always remains at the beginning of the list */ assert_se(SYSCALL_FILTER_SET_DEFAULT == 0); - assert_se(streq(syscall_filter_sets[0].name, "@default")); + ASSERT_STREQ(syscall_filter_sets[0].name, "@default"); /* Ensure "@known" always remains at the end of the list */ assert_se(SYSCALL_FILTER_SET_KNOWN == _SYSCALL_FILTER_SET_MAX - 1); - assert_se(streq(syscall_filter_sets[SYSCALL_FILTER_SET_KNOWN].name, "@known")); + ASSERT_STREQ(syscall_filter_sets[SYSCALL_FILTER_SET_KNOWN].name, "@known"); for (size_t i = 0; i < _SYSCALL_FILTER_SET_MAX; i++) { const char *p = NULL; @@ -294,7 +294,7 @@ TEST(restrict_namespace) { s = mfree(s); assert_se(namespace_flags_to_string(NAMESPACE_FLAGS_ALL, &s) == 0); - assert_se(streq(s, "cgroup ipc net mnt pid user uts")); + ASSERT_STREQ(s, "cgroup ipc net mnt pid user uts"); assert_se(namespace_flags_from_string(s, &ul) == 0 && ul == NAMESPACE_FLAGS_ALL); s = mfree(s); @@ -624,17 +624,17 @@ TEST(memory_deny_write_execute_mmap) { if (pid == 0) { void *p; - p = mmap(NULL, page_size(), PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, -1,0); + p = mmap(NULL, page_size(), PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); assert_se(p != MAP_FAILED); assert_se(munmap(p, page_size()) >= 0); - p = mmap(NULL, page_size(), PROT_WRITE|PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1,0); + p = mmap(NULL, page_size(), PROT_WRITE|PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); assert_se(p != MAP_FAILED); assert_se(munmap(p, page_size()) >= 0); assert_se(seccomp_memory_deny_write_execute() >= 0); - p = mmap(NULL, page_size(), PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, -1,0); + p = mmap(NULL, page_size(), PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); #if defined(__x86_64__) || defined(__i386__) || defined(__powerpc64__) || defined(__arm__) || defined(__aarch64__) || defined(__loongarch_lp64) assert_se(p == MAP_FAILED); assert_se(errno == EPERM); @@ -644,7 +644,7 @@ TEST(memory_deny_write_execute_mmap) { if (p != MAP_FAILED) assert_se(munmap(p, page_size()) == 0); - p = mmap(NULL, page_size(), PROT_WRITE|PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1,0); + p = mmap(NULL, page_size(), PROT_WRITE|PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); assert_se(p != MAP_FAILED); assert_se(munmap(p, page_size()) >= 0); @@ -937,7 +937,7 @@ TEST(native_syscalls_filtered) { } TEST(lock_personality) { - unsigned long current; + unsigned long current_opinionated; pid_t pid; if (!is_seccomp_available()) { @@ -949,24 +949,21 @@ TEST(lock_personality) { return; } - assert_se(opinionated_personality(¤t) >= 0); - /* On ppc64le sanitizers disable ASLR (i.e. by setting ADDR_NO_RANDOMIZE), - * which opinionated_personality() doesn't return. Let's tweak the current - * personality ourselves in such cases. - * See: https://github.com/llvm/llvm-project/commit/78f7a6eaa601bfdd6ae70ffd3da2254c21ff77f9 - */ - if (FLAGS_SET(safe_personality(PERSONALITY_INVALID), ADDR_NO_RANDOMIZE)) - current |= ADDR_NO_RANDOMIZE; + assert_se(opinionated_personality(¤t_opinionated) >= 0); - log_info("current personality=0x%lX", current); + log_info("current personality=0x%lX", (unsigned long) safe_personality(PERSONALITY_INVALID)); + log_info("current opinionated personality=0x%lX", current_opinionated); pid = fork(); assert_se(pid >= 0); if (pid == 0) { - assert_se(seccomp_lock_personality(current) >= 0); + unsigned long current; - assert_se((unsigned long) safe_personality(current) == current); + assert_se(seccomp_lock_personality(current_opinionated) >= 0); + + current = safe_personality(current_opinionated); + assert_se((current & OPINIONATED_PERSONALITY_MASK) == current_opinionated); /* Note, we also test that safe_personality() works correctly, by checking whether errno is properly * set, in addition to the return value */ @@ -981,14 +978,15 @@ TEST(lock_personality) { assert_se(safe_personality(PER_LINUX_32BIT) == -EPERM); assert_se(safe_personality(PER_SVR4) == -EPERM); assert_se(safe_personality(PER_BSD) == -EPERM); - assert_se(safe_personality(current == PER_LINUX ? PER_LINUX32 : PER_LINUX) == -EPERM); + assert_se(safe_personality(current_opinionated == PER_LINUX ? PER_LINUX32 : PER_LINUX) == -EPERM); assert_se(safe_personality(PER_LINUX32_3GB) == -EPERM); assert_se(safe_personality(PER_UW7) == -EPERM); assert_se(safe_personality(0x42) == -EPERM); assert_se(safe_personality(PERSONALITY_INVALID) == -EPERM); /* maybe remove this later */ - assert_se((unsigned long) personality(current) == current); + current = safe_personality(current_opinionated); + assert_se((current & OPINIONATED_PERSONALITY_MASK) == current_opinionated); _exit(EXIT_SUCCESS); } diff --git a/src/test/test-secure-bits.c b/src/test/test-secure-bits.c index 27e6a20..3d353ae 100644 --- a/src/test/test-secure-bits.c +++ b/src/test/test-secure-bits.c @@ -31,7 +31,7 @@ TEST(secure_bits_basic) { assert_se(secure_bits_is_valid(r)); assert_se(secure_bits_to_string_alloc(r, &s) >= 0); printf("%s = 0x%x = %s\n", *bit, (unsigned)r, s); - assert_se(streq(*bit, s)); + ASSERT_STREQ(*bit, s); } /* Ditto, but with all bits at once */ @@ -42,7 +42,7 @@ TEST(secure_bits_basic) { assert_se(secure_bits_is_valid(r)); assert_se(secure_bits_to_string_alloc(r, &str) >= 0); printf("%s = 0x%x = %s\n", joined, (unsigned)r, str); - assert_se(streq(joined, str)); + ASSERT_STREQ(joined, str); str = mfree(str); @@ -61,11 +61,11 @@ TEST(secure_bits_basic) { /* Bits to string with check */ assert_se(secure_bits_to_string_alloc_with_check(INT_MAX, &str) == -EINVAL); - assert_se(str == NULL); + ASSERT_NULL(str); assert_se(secure_bits_to_string_alloc_with_check( (1 << SECURE_KEEP_CAPS) | (1 << SECURE_KEEP_CAPS_LOCKED), &str) >= 0); - assert_se(streq(str, "keep-caps keep-caps-locked")); + ASSERT_STREQ(str, "keep-caps keep-caps-locked"); } TEST(secure_bits_mix) { @@ -90,7 +90,7 @@ TEST(secure_bits_mix) { assert_se(secure_bits_is_valid(r)); assert_se(secure_bits_to_string_alloc(r, &str) >= 0); printf("%s = 0x%x = %s\n", s->input, (unsigned)r, str); - assert_se(streq(s->expected, str)); + ASSERT_STREQ(s->expected, str); } } diff --git a/src/test/test-serialize.c b/src/test/test-serialize.c index 8f74472..40abf6c 100644 --- a/src/test/test-serialize.c +++ b/src/test/test-serialize.c @@ -32,13 +32,13 @@ TEST(serialize_item) { _cleanup_free_ char *line1 = NULL, *line2 = NULL, *line3 = NULL, *line4 = NULL; assert_se(read_line(f, LONG_LINE_MAX, &line1) > 0); - assert_se(streq(line1, "a=bbb")); + ASSERT_STREQ(line1, "a=bbb"); assert_se(read_line(f, LONG_LINE_MAX, &line2) > 0); - assert_se(streq(line2, "a=bbb")); + ASSERT_STREQ(line2, "a=bbb"); assert_se(read_line(f, LONG_LINE_MAX, &line3) > 0); - assert_se(streq(line3, "c=yes")); + ASSERT_STREQ(line3, "c=yes"); assert_se(read_line(f, LONG_LINE_MAX, &line4) == 0); - assert_se(streq(line4, "")); + ASSERT_STREQ(line4, ""); } TEST(serialize_item_escaped) { @@ -59,11 +59,11 @@ TEST(serialize_item_escaped) { _cleanup_free_ char *line1 = NULL, *line2 = NULL, *line3 = NULL; assert_se(read_line(f, LONG_LINE_MAX, &line1) > 0); - assert_se(streq(line1, "a=bbb")); + ASSERT_STREQ(line1, "a=bbb"); assert_se(read_line(f, LONG_LINE_MAX, &line2) > 0); - assert_se(streq(line2, "a=bbb")); + ASSERT_STREQ(line2, "a=bbb"); assert_se(read_line(f, LONG_LINE_MAX, &line3) == 0); - assert_se(streq(line3, "")); + ASSERT_STREQ(line3, ""); } TEST(serialize_usec) { @@ -83,7 +83,7 @@ TEST(serialize_usec) { usec_t x; assert_se(read_line(f, LONG_LINE_MAX, &line1) > 0); - assert_se(streq(line1, "usec2=0")); + ASSERT_STREQ(line1, "usec2=0"); assert_se(deserialize_usec(line1 + 6, &x) == 0); assert_se(x == 0); @@ -204,7 +204,7 @@ TEST(serialize_item_hexmem) { _cleanup_free_ char *line = NULL; assert_se(read_line(f, LONG_LINE_MAX, &line) > 0); - assert_se(streq(line, "a=ffffff")); + ASSERT_STREQ(line, "a=ffffff"); } @@ -222,7 +222,7 @@ TEST(serialize_item_base64mem) { _cleanup_free_ char *line = NULL; assert_se(read_line(f, LONG_LINE_MAX, &line) > 0); - assert_se(streq(line, "a=////")); + ASSERT_STREQ(line, "a=////"); } TEST(serialize_string_set) { diff --git a/src/test/test-set.c b/src/test/test-set.c index 0d5a6a1..23bac02 100644 --- a/src/test/test-set.c +++ b/src/test/test-set.c @@ -141,7 +141,7 @@ TEST(set_ensure_allocated) { assert_se(set_ensure_allocated(&m, &string_hash_ops) == 1); assert_se(set_ensure_allocated(&m, &string_hash_ops) == 0); assert_se(set_ensure_allocated(&m, NULL) == 0); - assert_se(set_size(m) == 0); + assert_se(set_isempty(m)); } TEST(set_copy) { @@ -231,28 +231,28 @@ TEST(set_strjoin) { /* Single entry */ assert_se(set_put_strdup(&m, "aaa") == 1); assert_se(set_strjoin(m, NULL, false, &joined) >= 0); - assert_se(streq(joined, "aaa")); + ASSERT_STREQ(joined, "aaa"); joined = mfree(joined); assert_se(set_strjoin(m, "", false, &joined) >= 0); - assert_se(streq(joined, "aaa")); + ASSERT_STREQ(joined, "aaa"); joined = mfree(joined); assert_se(set_strjoin(m, " ", false, &joined) >= 0); - assert_se(streq(joined, "aaa")); + ASSERT_STREQ(joined, "aaa"); joined = mfree(joined); assert_se(set_strjoin(m, "xxx", false, &joined) >= 0); - assert_se(streq(joined, "aaa")); + ASSERT_STREQ(joined, "aaa"); joined = mfree(joined); assert_se(set_strjoin(m, NULL, true, &joined) >= 0); - assert_se(streq(joined, "aaa")); + ASSERT_STREQ(joined, "aaa"); joined = mfree(joined); assert_se(set_strjoin(m, "", true, &joined) >= 0); - assert_se(streq(joined, "aaa")); + ASSERT_STREQ(joined, "aaa"); joined = mfree(joined); assert_se(set_strjoin(m, " ", true, &joined) >= 0); - assert_se(streq(joined, " aaa ")); + ASSERT_STREQ(joined, " aaa "); joined = mfree(joined); assert_se(set_strjoin(m, "xxx", true, &joined) >= 0); - assert_se(streq(joined, "xxxaaaxxx")); + ASSERT_STREQ(joined, "xxxaaaxxx"); /* Two entries */ assert_se(set_put_strdup(&m, "bbb") == 1); diff --git a/src/test/test-sha256.c b/src/test/test-sha256.c index f168e4c..1acc893 100644 --- a/src/test/test-sha256.c +++ b/src/test/test-sha256.c @@ -31,7 +31,7 @@ static void test_sha256_one(const char *key, const char *expect) { sha256_finish_ctx(&ctx, result + j); hex_result = hexmem(result + j, SHA256_DIGEST_SIZE); - assert_se(streq_ptr(hex_result, expect)); + ASSERT_STREQ(hex_result, expect); } } } diff --git a/src/test/test-sleep-config.c b/src/test/test-sleep-config.c index 112fec6..dc1a8fb 100644 --- a/src/test/test-sleep-config.c +++ b/src/test/test-sleep-config.c @@ -52,10 +52,10 @@ TEST(sleep_supported) { log_info("Standby configured: %s", yes_no(sleep_state_supported(standby) > 0)); log_info("Suspend configured: %s", yes_no(sleep_state_supported(mem) > 0)); log_info("Hibernate configured: %s", yes_no(sleep_state_supported(disk) > 0)); - log_info("Hibernate+Suspend (Hybrid-Sleep) configured: %s", yes_no(sleep_mode_supported(suspend) > 0)); - log_info("Hibernate+Reboot configured: %s", yes_no(sleep_mode_supported(reboot) > 0)); - log_info("Hibernate+Platform configured: %s", yes_no(sleep_mode_supported(platform) > 0)); - log_info("Hibernate+Shutdown configured: %s", yes_no(sleep_mode_supported(shutdown) > 0)); + log_info("Hibernate+Suspend (Hybrid-Sleep) configured: %s", yes_no(sleep_mode_supported("/sys/power/disk", suspend) > 0)); + log_info("Hibernate+Reboot configured: %s", yes_no(sleep_mode_supported("/sys/power/disk", reboot) > 0)); + log_info("Hibernate+Platform configured: %s", yes_no(sleep_mode_supported("/sys/power/disk", platform) > 0)); + log_info("Hibernate+Shutdown configured: %s", yes_no(sleep_mode_supported("/sys/power/disk", shutdown) > 0)); log_info("Freeze configured: %s", yes_no(sleep_state_supported(freeze) > 0)); log_info("/= high-level sleep verbs =/"); diff --git a/src/test/test-socket-bind.c b/src/test/test-socket-bind.c index 84a8978..13ffa92 100644 --- a/src/test/test-socket-bind.c +++ b/src/test/test-socket-bind.c @@ -66,7 +66,7 @@ static int test_socket_bind( fputc('\n', stderr); exec_start = strjoin("-timeout --preserve-status -sSIGTERM 1s ", netcat_path, " -l ", port, " -vv"); - assert_se(exec_start != NULL); + ASSERT_NOT_NULL(exec_start); r = config_parse_exec(u->id, "filename", 1, "Service", 1, "ExecStart", SERVICE_EXEC_START, exec_start, SERVICE(u)->exec_command, u); @@ -83,7 +83,7 @@ static int test_socket_bind( while (!IN_SET(SERVICE(u)->state, SERVICE_DEAD, SERVICE_FAILED)) { r = sd_event_run(m->event, UINT64_MAX); if (r < 0) - return log_error_errno(errno, "Event run failed %m"); + return log_error_errno(r, "Event run failed %m"); } cld_code = SERVICE(u)->exec_command[SERVICE_EXEC_START]->exec_status.code; diff --git a/src/test/test-socket-netlink.c b/src/test/test-socket-netlink.c index 6dbd50f..1849585 100644 --- a/src/test/test-socket-netlink.c +++ b/src/test/test-socket-netlink.c @@ -29,7 +29,7 @@ static void test_socket_address_parse_one(const char *in, int ret, int family, c assert_se(r == ret); if (r >= 0) { assert_se(a.sockaddr.sa.sa_family == family); - assert_se(streq(out, expected ?: in)); + ASSERT_STREQ(out, expected ?: in); } } @@ -199,7 +199,7 @@ TEST(socket_address_get_path) { assert_se(!socket_address_get_path(&a)); assert_se(socket_address_parse(&a, "/foo/bar") >= 0); - assert_se(streq(socket_address_get_path(&a), "/foo/bar")); + ASSERT_STREQ(socket_address_get_path(&a), "/foo/bar"); assert_se(socket_address_parse(&a, "vsock:2:1234") >= 0); assert_se(!socket_address_get_path(&a)); @@ -235,7 +235,7 @@ static void test_in_addr_ifindex_to_string_one(int f, const char *a, int ifindex assert_se(in_addr_from_string(f, a, &ua) >= 0); assert_se(in_addr_ifindex_to_string(f, &ua, ifindex, &r) >= 0); printf("test_in_addr_ifindex_to_string_one: %s == %s\n", b, r); - assert_se(streq(b, r)); + ASSERT_STREQ(b, r); assert_se(in_addr_ifindex_from_string_auto(b, &ff, &uuaa, &ifindex2) >= 0); assert_se(ff == f); @@ -248,9 +248,9 @@ TEST(in_addr_ifindex_to_string) { test_in_addr_ifindex_to_string_one(AF_INET, "10.11.12.13", 9, "10.11.12.13"); test_in_addr_ifindex_to_string_one(AF_INET6, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 10, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); test_in_addr_ifindex_to_string_one(AF_INET6, "::1", 11, "::1"); - test_in_addr_ifindex_to_string_one(AF_INET6, "fe80::", 12, "fe80::%12"); + test_in_addr_ifindex_to_string_one(AF_INET6, "fe80::", LOOPBACK_IFINDEX, "fe80::%1"); test_in_addr_ifindex_to_string_one(AF_INET6, "fe80::", 0, "fe80::"); - test_in_addr_ifindex_to_string_one(AF_INET6, "fe80::14", 12, "fe80::14%12"); + test_in_addr_ifindex_to_string_one(AF_INET6, "fe80::14", 0, "fe80::14"); test_in_addr_ifindex_to_string_one(AF_INET6, "fe80::15", -7, "fe80::15"); test_in_addr_ifindex_to_string_one(AF_INET6, "fe80::16", LOOPBACK_IFINDEX, "fe80::16%1"); } @@ -265,9 +265,9 @@ TEST(in_addr_ifindex_from_string_auto) { assert_se(family == AF_INET6); assert_se(ifindex == 0); - assert_se(in_addr_ifindex_from_string_auto("fe80::18%19", &family, &ua, &ifindex) >= 0); + assert_se(in_addr_ifindex_from_string_auto("fe80::18%1", &family, &ua, &ifindex) >= 0); assert_se(family == AF_INET6); - assert_se(ifindex == 19); + assert_se(ifindex == 1); assert_se(in_addr_ifindex_from_string_auto("fe80::18%lo", &family, &ua, &ifindex) >= 0); assert_se(family == AF_INET6); @@ -282,14 +282,14 @@ static void test_in_addr_ifindex_name_from_string_auto_one(const char *a, const _cleanup_free_ char *server_name = NULL; assert_se(in_addr_ifindex_name_from_string_auto(a, &family, &ua, &ifindex, &server_name) >= 0); - assert_se(streq_ptr(server_name, expected)); + ASSERT_STREQ(server_name, expected); } TEST(in_addr_ifindex_name_from_string_auto) { test_in_addr_ifindex_name_from_string_auto_one("192.168.0.1", NULL); test_in_addr_ifindex_name_from_string_auto_one("192.168.0.1#test.com", "test.com"); - test_in_addr_ifindex_name_from_string_auto_one("fe80::18%19", NULL); - test_in_addr_ifindex_name_from_string_auto_one("fe80::18%19#another.test.com", "another.test.com"); + test_in_addr_ifindex_name_from_string_auto_one("fe80::18%1", NULL); + test_in_addr_ifindex_name_from_string_auto_one("fe80::18%1#another.test.com", "another.test.com"); } static void test_in_addr_port_ifindex_name_from_string_auto_one(const char *str, int family, uint16_t port, int ifindex, @@ -307,9 +307,9 @@ static void test_in_addr_port_ifindex_name_from_string_auto_one(const char *str, assert_se(family == f); assert_se(port == p); assert_se(ifindex == i); - assert_se(streq_ptr(server_name, name)); + ASSERT_STREQ(server_name, name); assert_se(in_addr_port_ifindex_name_to_string(f, &a, p, i, name, &x) >= 0); - assert_se(streq(str_repr ?: str, x)); + ASSERT_STREQ(str_repr ?: str, x); } if (port > 0) @@ -319,9 +319,9 @@ static void test_in_addr_port_ifindex_name_from_string_auto_one(const char *str, assert_se(in_addr_port_ifindex_name_from_string_auto(str, &f, &a, NULL, &i, &name) == 0); assert_se(family == f); assert_se(ifindex == i); - assert_se(streq_ptr(server_name, name)); + ASSERT_STREQ(server_name, name); assert_se(in_addr_port_ifindex_name_to_string(f, &a, 0, i, name, &x) >= 0); - assert_se(streq(str_repr ?: str, x)); + ASSERT_STREQ(str_repr ?: str, x); } if (ifindex > 0) @@ -331,9 +331,9 @@ static void test_in_addr_port_ifindex_name_from_string_auto_one(const char *str, assert_se(in_addr_port_ifindex_name_from_string_auto(str, &f, &a, &p, NULL, &name) == 0); assert_se(family == f); assert_se(port == p); - assert_se(streq_ptr(server_name, name)); + ASSERT_STREQ(server_name, name); assert_se(in_addr_port_ifindex_name_to_string(f, &a, p, 0, name, &x) >= 0); - assert_se(streq(str_repr ?: str, x)); + ASSERT_STREQ(str_repr ?: str, x); } if (server_name) @@ -345,7 +345,7 @@ static void test_in_addr_port_ifindex_name_from_string_auto_one(const char *str, assert_se(port == p); assert_se(ifindex == i); assert_se(in_addr_port_ifindex_name_to_string(f, &a, p, i, NULL, &x) >= 0); - assert_se(streq(str_repr ?: str, x)); + ASSERT_STREQ(str_repr ?: str, x); } } @@ -356,17 +356,29 @@ TEST(in_addr_port_ifindex_name_from_string_auto) { test_in_addr_port_ifindex_name_from_string_auto_one("192.168.0.1:53#example.com", AF_INET, 53, 0, "example.com", NULL); test_in_addr_port_ifindex_name_from_string_auto_one("fe80::18", AF_INET6, 0, 0, NULL, NULL); test_in_addr_port_ifindex_name_from_string_auto_one("fe80::18#hoge.com", AF_INET6, 0, 0, "hoge.com", NULL); - test_in_addr_port_ifindex_name_from_string_auto_one("fe80::18%19", AF_INET6, 0, 19, NULL, NULL); + test_in_addr_port_ifindex_name_from_string_auto_one("fe80::18%1", AF_INET6, 0, 1, NULL, NULL); test_in_addr_port_ifindex_name_from_string_auto_one("fe80::18%lo", AF_INET6, 0, 1, NULL, "fe80::18%1"); test_in_addr_port_ifindex_name_from_string_auto_one("[fe80::18]:53", AF_INET6, 53, 0, NULL, NULL); - test_in_addr_port_ifindex_name_from_string_auto_one("[fe80::18]:53%19", AF_INET6, 53, 19, NULL, NULL); + test_in_addr_port_ifindex_name_from_string_auto_one("[fe80::18]:53%1", AF_INET6, 53, 1, NULL, NULL); test_in_addr_port_ifindex_name_from_string_auto_one("[fe80::18]:53%lo", AF_INET6, 53, 1, NULL, "[fe80::18]:53%1"); - test_in_addr_port_ifindex_name_from_string_auto_one("fe80::18%19#hoge.com", AF_INET6, 0, 19, "hoge.com", NULL); + test_in_addr_port_ifindex_name_from_string_auto_one("fe80::18%1#hoge.com", AF_INET6, 0, 1, "hoge.com", NULL); test_in_addr_port_ifindex_name_from_string_auto_one("[fe80::18]:53#hoge.com", AF_INET6, 53, 0, "hoge.com", NULL); - test_in_addr_port_ifindex_name_from_string_auto_one("[fe80::18]:53%19", AF_INET6, 53, 19, NULL, NULL); - test_in_addr_port_ifindex_name_from_string_auto_one("[fe80::18]:53%19#hoge.com", AF_INET6, 53, 19, "hoge.com", NULL); + test_in_addr_port_ifindex_name_from_string_auto_one("[fe80::18]:53%1", AF_INET6, 53, 1, NULL, NULL); + test_in_addr_port_ifindex_name_from_string_auto_one("[fe80::18]:53%1#hoge.com", AF_INET6, 53, 1, "hoge.com", NULL); test_in_addr_port_ifindex_name_from_string_auto_one("[fe80::18]:53%lo", AF_INET6, 53, 1, NULL, "[fe80::18]:53%1"); test_in_addr_port_ifindex_name_from_string_auto_one("[fe80::18]:53%lo#hoge.com", AF_INET6, 53, 1, "hoge.com", "[fe80::18]:53%1#hoge.com"); } +TEST(netns_get_nsid) { + uint32_t u; + int r; + + r = netns_get_nsid(-EBADF, &u); + assert_se(r == -ENODATA || r >= 0); + if (r == -ENODATA) + log_info("Our network namespace has no NSID assigned."); + else + log_info("Our NSID is %" PRIu32, u); +} + DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-socket-util.c b/src/test/test-socket-util.c index e9c776a..e34aa10 100644 --- a/src/test/test-socket-util.c +++ b/src/test/test-socket-util.c @@ -69,7 +69,7 @@ static void test_socket_print_unix_one(const char *in, size_t len_in, const char assert_se(socket_address_print(&a, &out) >= 0); assert_se(c = cescape(in)); log_info("\"%s\" → \"%s\" (expect \"%s\")", in, out, expected); - assert_se(streq(out, expected)); + ASSERT_STREQ(out, expected); } TEST(socket_print_unix) { @@ -168,7 +168,7 @@ TEST(getpeercred_getpeergroups) { uid_t test_uid; gid_t test_gid; struct ucred ucred; - int pair[2]; + int pair[2] = EBADF_PAIR; if (geteuid() == 0) { test_uid = 1; @@ -176,10 +176,7 @@ TEST(getpeercred_getpeergroups) { test_gids = (gid_t*) gids; n_test_gids = ELEMENTSOF(gids); - assert_se(setgroups(n_test_gids, test_gids) >= 0); - assert_se(setresgid(test_gid, test_gid, test_gid) >= 0); - assert_se(setresuid(test_uid, test_uid, test_uid) >= 0); - + assert_se(fully_set_uid_gid(test_uid, test_gid, test_gids, n_test_gids) >= 0); } else { long ngroups_max; @@ -223,7 +220,7 @@ TEST(getpeercred_getpeergroups) { TEST(passfd_read) { static const char file_contents[] = "test contents for passfd"; - _cleanup_close_pair_ int pair[2]; + _cleanup_close_pair_ int pair[2] = EBADF_PAIR; int r; assert_se(socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) >= 0); @@ -249,7 +246,7 @@ TEST(passfd_read) { /* Parent */ char buf[64]; struct iovec iov = IOVEC_MAKE(buf, sizeof(buf)-1); - _cleanup_close_ int fd; + _cleanup_close_ int fd = -EBADF; pair[1] = safe_close(pair[1]); @@ -259,11 +256,11 @@ TEST(passfd_read) { r = read(fd, buf, sizeof(buf)-1); assert_se(r >= 0); buf[r] = 0; - assert_se(streq(buf, file_contents)); + ASSERT_STREQ(buf, file_contents); } TEST(passfd_contents_read) { - _cleanup_close_pair_ int pair[2]; + _cleanup_close_pair_ int pair[2] = EBADF_PAIR; static const char file_contents[] = "test contents in the file"; static const char wire_contents[] = "test contents on the wire"; int r; @@ -293,7 +290,7 @@ TEST(passfd_contents_read) { /* Parent */ char buf[64]; struct iovec iov = IOVEC_MAKE(buf, sizeof(buf)-1); - _cleanup_close_ int fd; + _cleanup_close_ int fd = -EBADF; ssize_t k; pair[1] = safe_close(pair[1]); @@ -301,17 +298,17 @@ TEST(passfd_contents_read) { k = receive_one_fd_iov(pair[0], &iov, 1, MSG_DONTWAIT, &fd); assert_se(k > 0); buf[k] = 0; - assert_se(streq(buf, wire_contents)); + ASSERT_STREQ(buf, wire_contents); assert_se(fd >= 0); r = read(fd, buf, sizeof(buf)-1); assert_se(r >= 0); buf[r] = 0; - assert_se(streq(buf, file_contents)); + ASSERT_STREQ(buf, file_contents); } TEST(pass_many_fds_contents_read) { - _cleanup_close_pair_ int pair[2]; + _cleanup_close_pair_ int pair[2] = EBADF_PAIR; static const char file_contents[][STRLEN("test contents in the fileX") + 1] = { "test contents in the file0", "test contents in the file1", @@ -361,7 +358,7 @@ TEST(pass_many_fds_contents_read) { k = receive_many_fds_iov(pair[0], &iov, 1, &fds, &n_fds, MSG_DONTWAIT); assert_se(k > 0); buf[k] = 0; - assert_se(streq(buf, wire_contents)); + ASSERT_STREQ(buf, wire_contents); assert_se(n_fds == 3); @@ -370,13 +367,13 @@ TEST(pass_many_fds_contents_read) { r = read(fds[i], buf, sizeof(buf)-1); assert_se(r >= 0); buf[r] = 0; - assert_se(streq(buf, file_contents[i])); + ASSERT_STREQ(buf, file_contents[i]); safe_close(fds[i]); } } TEST(receive_nopassfd) { - _cleanup_close_pair_ int pair[2]; + _cleanup_close_pair_ int pair[2] = EBADF_PAIR; static const char wire_contents[] = "no fd passed here"; int r; @@ -406,14 +403,14 @@ TEST(receive_nopassfd) { k = receive_one_fd_iov(pair[0], &iov, 1, MSG_DONTWAIT, &fd); assert_se(k > 0); buf[k] = 0; - assert_se(streq(buf, wire_contents)); + ASSERT_STREQ(buf, wire_contents); /* no fd passed here, confirm it was reset */ assert_se(fd == -EBADF); } TEST(send_nodata_nofd) { - _cleanup_close_pair_ int pair[2]; + _cleanup_close_pair_ int pair[2] = EBADF_PAIR; int r; assert_se(socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) >= 0); @@ -446,7 +443,7 @@ TEST(send_nodata_nofd) { } TEST(send_emptydata) { - _cleanup_close_pair_ int pair[2]; + _cleanup_close_pair_ int pair[2] = EBADF_PAIR; int r; assert_se(socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) >= 0); diff --git a/src/test/test-specifier.c b/src/test/test-specifier.c index d6a8b79..7d25969 100644 --- a/src/test/test-specifier.c +++ b/src/test/test-specifier.c @@ -16,7 +16,7 @@ static void test_specifier_escape_one(const char *a, const char *b) { _cleanup_free_ char *x = NULL; x = specifier_escape(a); - assert_se(streq_ptr(x, b)); + ASSERT_STREQ(x, b); } TEST(specifier_escape) { @@ -73,7 +73,7 @@ TEST(specifier_printf) { assert_se(w); puts(w); - assert_se(streq(w, "xxx a=AAAA b=BBBB e= yyy")); + ASSERT_STREQ(w, "xxx a=AAAA b=BBBB e= yyy"); free(w); r = specifier_printf("boot=%b, host=%H, pretty=%q, version=%v, arch=%a, empty=%e", SIZE_MAX, table, NULL, NULL, &w); @@ -107,7 +107,7 @@ TEST(specifier_real_path) { /* /dev/initctl should normally be a symlink to /run/initctl */ if (inode_same("/dev/initctl", "/run/initctl", 0) > 0) - assert_se(streq(w, "p=/dev/initctl y=/run/initctl Y=/run w=/dev/tty W=/dev")); + ASSERT_STREQ(w, "p=/dev/initctl y=/run/initctl Y=/run w=/dev/tty W=/dev"); } TEST(specifier_real_path_missing_file) { @@ -138,6 +138,8 @@ TEST(specifiers) { xsprintf(spec, "%%%c", s->specifier); r = specifier_printf(spec, SIZE_MAX, specifier_table, NULL, NULL, &resolved); + if (s->specifier == 'A' && r == -EUNATCH) /* os-release might be missing in build chroots */ + continue; if (s->specifier == 'm' && IN_SET(r, -EUNATCH, -ENOMEDIUM, -ENOPKG)) /* machine-id might be missing in build chroots */ continue; assert_se(r >= 0); @@ -176,11 +178,11 @@ TEST(specifiers_missing_data_ok) { assert_se(setenv("SYSTEMD_OS_RELEASE", "/dev/null", 1) == 0); assert_se(specifier_printf("%A-%B-%M-%o-%w-%W", SIZE_MAX, specifier_table, NULL, NULL, &resolved) >= 0); - assert_se(streq(resolved, "-----")); + ASSERT_STREQ(resolved, "-----"); assert_se(setenv("SYSTEMD_OS_RELEASE", "/nosuchfileordirectory", 1) == 0); assert_se(specifier_printf("%A-%B-%M-%o-%w-%W", SIZE_MAX, specifier_table, NULL, NULL, &resolved) == -EUNATCH); - assert_se(streq(resolved, "-----")); + ASSERT_STREQ(resolved, "-----"); assert_se(unsetenv("SYSTEMD_OS_RELEASE") == 0); } diff --git a/src/test/test-stat-util.c b/src/test/test-stat-util.c index 8d7fd5b..6f274c9 100644 --- a/src/test/test-stat-util.c +++ b/src/test/test-stat-util.c @@ -3,6 +3,7 @@ #include <fcntl.h> #include <linux/magic.h> #include <sched.h> +#include <sys/eventfd.h> #include <unistd.h> #include "alloc-util.h" @@ -73,11 +74,11 @@ TEST(is_symlink) { TEST(path_is_fs_type) { /* run might not be a mount point in build chroots */ - if (path_is_mount_point("/run", NULL, AT_SYMLINK_FOLLOW) > 0) { + if (path_is_mount_point_full("/run", NULL, AT_SYMLINK_FOLLOW) > 0) { assert_se(path_is_fs_type("/run", TMPFS_MAGIC) > 0); assert_se(path_is_fs_type("/run", BTRFS_SUPER_MAGIC) == 0); } - if (path_is_mount_point("/proc", NULL, AT_SYMLINK_FOLLOW) > 0) { + if (path_is_mount_point_full("/proc", NULL, AT_SYMLINK_FOLLOW) > 0) { assert_se(path_is_fs_type("/proc", PROC_SUPER_MAGIC) > 0); assert_se(path_is_fs_type("/proc", BTRFS_SUPER_MAGIC) == 0); } @@ -95,7 +96,7 @@ TEST(path_is_temporary_fs) { } /* run might not be a mount point in build chroots */ - if (path_is_mount_point("/run", NULL, AT_SYMLINK_FOLLOW) > 0) + if (path_is_mount_point_full("/run", NULL, AT_SYMLINK_FOLLOW) > 0) assert_se(path_is_temporary_fs("/run") > 0); assert_se(path_is_temporary_fs("/proc") == 0); assert_se(path_is_temporary_fs("/i-dont-exist") == -ENOENT); @@ -111,7 +112,7 @@ TEST(path_is_read_only_fs) { s, r, r < 0 ? errno_to_name(r) : yes_no(r)); } - if (path_is_mount_point("/sys", NULL, AT_SYMLINK_FOLLOW) > 0) + if (path_is_mount_point_full("/sys", NULL, AT_SYMLINK_FOLLOW) > 0) assert_se(IN_SET(path_is_read_only_fs("/sys"), 0, 1)); assert_se(path_is_read_only_fs("/proc") == 0); @@ -180,6 +181,36 @@ TEST(dir_is_empty) { assert_se(dir_is_empty_at(AT_FDCWD, empty_dir, /* ignore_hidden_or_backup= */ false) > 0); } +TEST(inode_type_from_string) { + static const mode_t types[] = { + S_IFREG, + S_IFDIR, + S_IFLNK, + S_IFCHR, + S_IFBLK, + S_IFIFO, + S_IFSOCK, + }; + + FOREACH_ELEMENT(m, types) + assert_se(inode_type_from_string(inode_type_to_string(*m)) == *m); +} + +TEST(anonymous_inode) { + _cleanup_close_ int fd = -EBADF; + + fd = eventfd(0, EFD_CLOEXEC); + assert_se(fd >= 0); + + /* Verify that we handle anonymous inodes correctly, i.e. those which have no file type */ + + struct stat st; + ASSERT_OK_ERRNO(fstat(fd, &st)); + assert_se((st.st_mode & S_IFMT) == 0); + + assert_se(!inode_type_to_string(st.st_mode)); +} + TEST(fd_verify_linked) { _cleanup_(rm_rf_physical_and_freep) char *t = NULL; _cleanup_close_ int tfd = -EBADF, fd = -EBADF; diff --git a/src/test/test-strbuf.c b/src/test/test-strbuf.c index 39a7142..c0a4d11 100644 --- a/src/test/test-strbuf.c +++ b/src/test/test-strbuf.c @@ -32,12 +32,12 @@ TEST(strbuf) { l = strv_parse_nulstr(sb->buf, sb->len); assert_se(l); - assert_se(streq(l[0], "")); /* root */ - assert_se(streq(l[1], "waldo")); - assert_se(streq(l[2], "foo")); - assert_se(streq(l[3], "bar")); - assert_se(streq(l[4], "waldorf")); - assert_se(l[5] == NULL); + ASSERT_STREQ(l[0], ""); /* root */ + ASSERT_STREQ(l[1], "waldo"); + ASSERT_STREQ(l[2], "foo"); + ASSERT_STREQ(l[3], "bar"); + ASSERT_STREQ(l[4], "waldorf"); + ASSERT_NULL(l[5]); assert_se(sb->nodes_count == 5); /* root + 4 non-duplicates */ assert_se(sb->dedup_count == 4); @@ -57,17 +57,17 @@ TEST(strbuf) { assert_se(g == 15); assert_se(h == 0); - assert_se(streq(sb->buf + a, "waldo")); - assert_se(streq(sb->buf + b, "foo")); - assert_se(streq(sb->buf + c, "bar")); - assert_se(streq(sb->buf + d, "waldo")); - assert_se(streq(sb->buf + e, "aldo")); - assert_se(streq(sb->buf + f, "do")); - assert_se(streq(sb->buf + g, "waldorf")); - assert_se(streq(sb->buf + h, "")); + ASSERT_STREQ(sb->buf + a, "waldo"); + ASSERT_STREQ(sb->buf + b, "foo"); + ASSERT_STREQ(sb->buf + c, "bar"); + ASSERT_STREQ(sb->buf + d, "waldo"); + ASSERT_STREQ(sb->buf + e, "aldo"); + ASSERT_STREQ(sb->buf + f, "do"); + ASSERT_STREQ(sb->buf + g, "waldorf"); + ASSERT_STREQ(sb->buf + h, ""); strbuf_complete(sb); - assert_se(sb->root == NULL); + ASSERT_NULL(sb->root); } DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-string-util.c b/src/test/test-string-util.c index a8fd45d..4bf7548 100644 --- a/src/test/test-string-util.c +++ b/src/test/test-string-util.c @@ -13,13 +13,13 @@ TEST(string_erase) { char *x; x = strdupa_safe(""); - assert_se(streq(string_erase(x), "")); + ASSERT_STREQ(string_erase(x), ""); x = strdupa_safe("1"); - assert_se(streq(string_erase(x), "")); + ASSERT_STREQ(string_erase(x), ""); x = strdupa_safe("123456789"); - assert_se(streq(string_erase(x), "")); + ASSERT_STREQ(string_erase(x), ""); assert_se(x[1] == '\0'); assert_se(x[2] == '\0'); @@ -37,7 +37,7 @@ static void test_free_and_strndup_one(char **t, const char *src, size_t l, const __func__, strnull(*t), strnull(src), l, strnull(expected), yes_no(change)); int r = free_and_strndup(t, src, l); - assert_se(streq_ptr(*t, expected)); + ASSERT_STREQ(*t, expected); assert_se(r == change); /* check that change occurs only when necessary */ } @@ -88,6 +88,35 @@ TEST(free_and_strndup) { } } +TEST(strdup_to_full) { + _cleanup_free_ char *dst; + + assert_se(strdup_to_full(NULL, NULL) == 0); + assert_se(strdup_to_full(&dst, NULL) == 0); + + assert_se(strdup_to_full(NULL, "") == 1); + assert_se(strdup_to_full(&dst, "") == 1); + ASSERT_STREQ(dst, ""); + dst = mfree(dst); + + assert_se(strdup_to_full(NULL, "x") == 1); + assert_se(strdup_to_full(&dst, "x") == 1); + ASSERT_STREQ(dst, "x"); +} + +TEST(strdup_to) { + _cleanup_free_ char *dst; + + assert_se(strdup_to(&dst, NULL) == 0); + + assert_se(strdup_to(&dst, "") == 0); + ASSERT_STREQ(dst, ""); + dst = mfree(dst); + + assert_se(strdup_to(&dst, "x") == 0); + ASSERT_STREQ(dst, "x"); +} + TEST(ascii_strcasecmp_n) { assert_se(ascii_strcasecmp_n("", "", 0) == 0); assert_se(ascii_strcasecmp_n("", "", 1) == 0); @@ -134,82 +163,82 @@ TEST(ascii_strcasecmp_nn) { TEST(cellescape) { char buf[40]; - assert_se(streq(cellescape(buf, 1, ""), "")); - assert_se(streq(cellescape(buf, 1, "1"), "")); - assert_se(streq(cellescape(buf, 1, "12"), "")); - - assert_se(streq(cellescape(buf, 2, ""), "")); - assert_se(streq(cellescape(buf, 2, "1"), "1")); - assert_se(streq(cellescape(buf, 2, "12"), ".")); - assert_se(streq(cellescape(buf, 2, "123"), ".")); - - assert_se(streq(cellescape(buf, 3, ""), "")); - assert_se(streq(cellescape(buf, 3, "1"), "1")); - assert_se(streq(cellescape(buf, 3, "12"), "12")); - assert_se(streq(cellescape(buf, 3, "123"), "..")); - assert_se(streq(cellescape(buf, 3, "1234"), "..")); - - assert_se(streq(cellescape(buf, 4, ""), "")); - assert_se(streq(cellescape(buf, 4, "1"), "1")); - assert_se(streq(cellescape(buf, 4, "12"), "12")); - assert_se(streq(cellescape(buf, 4, "123"), "123")); - assert_se(streq(cellescape(buf, 4, "1234"), is_locale_utf8() ? "…" : "...")); - assert_se(streq(cellescape(buf, 4, "12345"), is_locale_utf8() ? "…" : "...")); - - assert_se(streq(cellescape(buf, 5, ""), "")); - assert_se(streq(cellescape(buf, 5, "1"), "1")); - assert_se(streq(cellescape(buf, 5, "12"), "12")); - assert_se(streq(cellescape(buf, 5, "123"), "123")); - assert_se(streq(cellescape(buf, 5, "1234"), "1234")); - assert_se(streq(cellescape(buf, 5, "12345"), is_locale_utf8() ? "1…" : "1...")); - assert_se(streq(cellescape(buf, 5, "123456"), is_locale_utf8() ? "1…" : "1...")); - - assert_se(streq(cellescape(buf, 1, "\020"), "")); - assert_se(streq(cellescape(buf, 2, "\020"), ".")); - assert_se(streq(cellescape(buf, 3, "\020"), "..")); - assert_se(streq(cellescape(buf, 4, "\020"), is_locale_utf8() ? "…" : "...")); - assert_se(streq(cellescape(buf, 5, "\020"), "\\020")); - - assert_se(streq(cellescape(buf, 5, "1234\020"), is_locale_utf8() ? "1…" : "1...")); - assert_se(streq(cellescape(buf, 6, "1234\020"), is_locale_utf8() ? "12…" : "12...")); - assert_se(streq(cellescape(buf, 7, "1234\020"), is_locale_utf8() ? "123…" : "123...")); - assert_se(streq(cellescape(buf, 8, "1234\020"), is_locale_utf8() ? "1234…" : "1234...")); - assert_se(streq(cellescape(buf, 9, "1234\020"), "1234\\020")); - - assert_se(streq(cellescape(buf, 1, "\t\n"), "")); - assert_se(streq(cellescape(buf, 2, "\t\n"), ".")); - assert_se(streq(cellescape(buf, 3, "\t\n"), "..")); - assert_se(streq(cellescape(buf, 4, "\t\n"), is_locale_utf8() ? "…" : "...")); - assert_se(streq(cellescape(buf, 5, "\t\n"), "\\t\\n")); - - assert_se(streq(cellescape(buf, 5, "1234\t\n"), is_locale_utf8() ? "1…" : "1...")); - assert_se(streq(cellescape(buf, 6, "1234\t\n"), is_locale_utf8() ? "12…" : "12...")); - assert_se(streq(cellescape(buf, 7, "1234\t\n"), is_locale_utf8() ? "123…" : "123...")); - assert_se(streq(cellescape(buf, 8, "1234\t\n"), is_locale_utf8() ? "1234…" : "1234...")); - assert_se(streq(cellescape(buf, 9, "1234\t\n"), "1234\\t\\n")); - - assert_se(streq(cellescape(buf, 4, "x\t\020\n"), is_locale_utf8() ? "…" : "...")); - assert_se(streq(cellescape(buf, 5, "x\t\020\n"), is_locale_utf8() ? "x…" : "x...")); - assert_se(streq(cellescape(buf, 6, "x\t\020\n"), is_locale_utf8() ? "x…" : "x...")); - assert_se(streq(cellescape(buf, 7, "x\t\020\n"), is_locale_utf8() ? "x\\t…" : "x\\t...")); - assert_se(streq(cellescape(buf, 8, "x\t\020\n"), is_locale_utf8() ? "x\\t…" : "x\\t...")); - assert_se(streq(cellescape(buf, 9, "x\t\020\n"), is_locale_utf8() ? "x\\t…" : "x\\t...")); - assert_se(streq(cellescape(buf, 10, "x\t\020\n"), "x\\t\\020\\n")); - - assert_se(streq(cellescape(buf, 6, "1\011"), "1\\t")); - assert_se(streq(cellescape(buf, 6, "1\020"), "1\\020")); - assert_se(streq(cellescape(buf, 6, "1\020x"), is_locale_utf8() ? "1…" : "1...")); - - assert_se(streq(cellescape(buf, 40, "1\020"), "1\\020")); - assert_se(streq(cellescape(buf, 40, "1\020x"), "1\\020x")); - - assert_se(streq(cellescape(buf, 40, "\a\b\f\n\r\t\v\\\"'"), "\\a\\b\\f\\n\\r\\t\\v\\\\\\\"\\'")); - assert_se(streq(cellescape(buf, 6, "\a\b\f\n\r\t\v\\\"'"), is_locale_utf8() ? "\\a…" : "\\a...")); - assert_se(streq(cellescape(buf, 7, "\a\b\f\n\r\t\v\\\"'"), is_locale_utf8() ? "\\a…" : "\\a...")); - assert_se(streq(cellescape(buf, 8, "\a\b\f\n\r\t\v\\\"'"), is_locale_utf8() ? "\\a\\b…" : "\\a\\b...")); - - assert_se(streq(cellescape(buf, sizeof buf, "1\020"), "1\\020")); - assert_se(streq(cellescape(buf, sizeof buf, "1\020x"), "1\\020x")); + ASSERT_STREQ(cellescape(buf, 1, ""), ""); + ASSERT_STREQ(cellescape(buf, 1, "1"), ""); + ASSERT_STREQ(cellescape(buf, 1, "12"), ""); + + ASSERT_STREQ(cellescape(buf, 2, ""), ""); + ASSERT_STREQ(cellescape(buf, 2, "1"), "1"); + ASSERT_STREQ(cellescape(buf, 2, "12"), "."); + ASSERT_STREQ(cellescape(buf, 2, "123"), "."); + + ASSERT_STREQ(cellescape(buf, 3, ""), ""); + ASSERT_STREQ(cellescape(buf, 3, "1"), "1"); + ASSERT_STREQ(cellescape(buf, 3, "12"), "12"); + ASSERT_STREQ(cellescape(buf, 3, "123"), ".."); + ASSERT_STREQ(cellescape(buf, 3, "1234"), ".."); + + ASSERT_STREQ(cellescape(buf, 4, ""), ""); + ASSERT_STREQ(cellescape(buf, 4, "1"), "1"); + ASSERT_STREQ(cellescape(buf, 4, "12"), "12"); + ASSERT_STREQ(cellescape(buf, 4, "123"), "123"); + ASSERT_STREQ(cellescape(buf, 4, "1234"), is_locale_utf8() ? "…" : "..."); + ASSERT_STREQ(cellescape(buf, 4, "12345"), is_locale_utf8() ? "…" : "..."); + + ASSERT_STREQ(cellescape(buf, 5, ""), ""); + ASSERT_STREQ(cellescape(buf, 5, "1"), "1"); + ASSERT_STREQ(cellescape(buf, 5, "12"), "12"); + ASSERT_STREQ(cellescape(buf, 5, "123"), "123"); + ASSERT_STREQ(cellescape(buf, 5, "1234"), "1234"); + ASSERT_STREQ(cellescape(buf, 5, "12345"), is_locale_utf8() ? "1…" : "1..."); + ASSERT_STREQ(cellescape(buf, 5, "123456"), is_locale_utf8() ? "1…" : "1..."); + + ASSERT_STREQ(cellescape(buf, 1, "\020"), ""); + ASSERT_STREQ(cellescape(buf, 2, "\020"), "."); + ASSERT_STREQ(cellescape(buf, 3, "\020"), ".."); + ASSERT_STREQ(cellescape(buf, 4, "\020"), is_locale_utf8() ? "…" : "..."); + ASSERT_STREQ(cellescape(buf, 5, "\020"), "\\020"); + + ASSERT_STREQ(cellescape(buf, 5, "1234\020"), is_locale_utf8() ? "1…" : "1..."); + ASSERT_STREQ(cellescape(buf, 6, "1234\020"), is_locale_utf8() ? "12…" : "12..."); + ASSERT_STREQ(cellescape(buf, 7, "1234\020"), is_locale_utf8() ? "123…" : "123..."); + ASSERT_STREQ(cellescape(buf, 8, "1234\020"), is_locale_utf8() ? "1234…" : "1234..."); + ASSERT_STREQ(cellescape(buf, 9, "1234\020"), "1234\\020"); + + ASSERT_STREQ(cellescape(buf, 1, "\t\n"), ""); + ASSERT_STREQ(cellescape(buf, 2, "\t\n"), "."); + ASSERT_STREQ(cellescape(buf, 3, "\t\n"), ".."); + ASSERT_STREQ(cellescape(buf, 4, "\t\n"), is_locale_utf8() ? "…" : "..."); + ASSERT_STREQ(cellescape(buf, 5, "\t\n"), "\\t\\n"); + + ASSERT_STREQ(cellescape(buf, 5, "1234\t\n"), is_locale_utf8() ? "1…" : "1..."); + ASSERT_STREQ(cellescape(buf, 6, "1234\t\n"), is_locale_utf8() ? "12…" : "12..."); + ASSERT_STREQ(cellescape(buf, 7, "1234\t\n"), is_locale_utf8() ? "123…" : "123..."); + ASSERT_STREQ(cellescape(buf, 8, "1234\t\n"), is_locale_utf8() ? "1234…" : "1234..."); + ASSERT_STREQ(cellescape(buf, 9, "1234\t\n"), "1234\\t\\n"); + + ASSERT_STREQ(cellescape(buf, 4, "x\t\020\n"), is_locale_utf8() ? "…" : "..."); + ASSERT_STREQ(cellescape(buf, 5, "x\t\020\n"), is_locale_utf8() ? "x…" : "x..."); + ASSERT_STREQ(cellescape(buf, 6, "x\t\020\n"), is_locale_utf8() ? "x…" : "x..."); + ASSERT_STREQ(cellescape(buf, 7, "x\t\020\n"), is_locale_utf8() ? "x\\t…" : "x\\t..."); + ASSERT_STREQ(cellescape(buf, 8, "x\t\020\n"), is_locale_utf8() ? "x\\t…" : "x\\t..."); + ASSERT_STREQ(cellescape(buf, 9, "x\t\020\n"), is_locale_utf8() ? "x\\t…" : "x\\t..."); + ASSERT_STREQ(cellescape(buf, 10, "x\t\020\n"), "x\\t\\020\\n"); + + ASSERT_STREQ(cellescape(buf, 6, "1\011"), "1\\t"); + ASSERT_STREQ(cellescape(buf, 6, "1\020"), "1\\020"); + ASSERT_STREQ(cellescape(buf, 6, "1\020x"), is_locale_utf8() ? "1…" : "1..."); + + ASSERT_STREQ(cellescape(buf, 40, "1\020"), "1\\020"); + ASSERT_STREQ(cellescape(buf, 40, "1\020x"), "1\\020x"); + + ASSERT_STREQ(cellescape(buf, 40, "\a\b\f\n\r\t\v\\\"'"), "\\a\\b\\f\\n\\r\\t\\v\\\\\\\"\\'"); + ASSERT_STREQ(cellescape(buf, 6, "\a\b\f\n\r\t\v\\\"'"), is_locale_utf8() ? "\\a…" : "\\a..."); + ASSERT_STREQ(cellescape(buf, 7, "\a\b\f\n\r\t\v\\\"'"), is_locale_utf8() ? "\\a…" : "\\a..."); + ASSERT_STREQ(cellescape(buf, 8, "\a\b\f\n\r\t\v\\\"'"), is_locale_utf8() ? "\\a\\b…" : "\\a\\b..."); + + ASSERT_STREQ(cellescape(buf, sizeof buf, "1\020"), "1\\020"); + ASSERT_STREQ(cellescape(buf, sizeof buf, "1\020x"), "1\\020x"); } TEST(streq_ptr) { @@ -221,41 +250,41 @@ TEST(strstrip) { char *ret, input[] = " hello, waldo. "; ret = strstrip(input); - assert_se(streq(ret, "hello, waldo.")); + ASSERT_STREQ(ret, "hello, waldo."); } TEST(strextend) { _cleanup_free_ char *str = NULL; assert_se(strextend(&str, NULL)); - assert_se(streq_ptr(str, "")); + ASSERT_STREQ(str, ""); assert_se(strextend(&str, "", "0", "", "", "123")); - assert_se(streq_ptr(str, "0123")); + ASSERT_STREQ(str, "0123"); assert_se(strextend(&str, "456", "78", "9")); - assert_se(streq_ptr(str, "0123456789")); + ASSERT_STREQ(str, "0123456789"); } TEST(strextend_with_separator) { _cleanup_free_ char *str = NULL; assert_se(strextend_with_separator(&str, NULL, NULL)); - assert_se(streq_ptr(str, "")); + ASSERT_STREQ(str, ""); str = mfree(str); assert_se(strextend_with_separator(&str, "...", NULL)); - assert_se(streq_ptr(str, "")); + ASSERT_STREQ(str, ""); assert_se(strextend_with_separator(&str, "...", NULL)); - assert_se(streq_ptr(str, "")); + ASSERT_STREQ(str, ""); str = mfree(str); assert_se(strextend_with_separator(&str, "xyz", "a", "bb", "ccc")); - assert_se(streq_ptr(str, "axyzbbxyzccc")); + ASSERT_STREQ(str, "axyzbbxyzccc"); str = mfree(str); assert_se(strextend_with_separator(&str, ",", "start", "", "1", "234")); - assert_se(streq_ptr(str, "start,,1,234")); + ASSERT_STREQ(str, "start,,1,234"); assert_se(strextend_with_separator(&str, ";", "more", "5", "678")); - assert_se(streq_ptr(str, "start,,1,234;more;5;678")); + ASSERT_STREQ(str, "start,,1,234;more;5;678"); } TEST(strrep) { @@ -266,15 +295,15 @@ TEST(strrep) { three = strrep("waldo", 3); zero = strrep("waldo", 0); - assert_se(streq(one, "waldo")); - assert_se(streq(three, "waldowaldowaldo")); - assert_se(streq(zero, "")); + ASSERT_STREQ(one, "waldo"); + ASSERT_STREQ(three, "waldowaldowaldo"); + ASSERT_STREQ(zero, ""); onea = strrepa("waldo", 1); threea = strrepa("waldo", 3); - assert_se(streq(onea, "waldo")); - assert_se(streq(threea, "waldowaldowaldo")); + ASSERT_STREQ(onea, "waldo"); + ASSERT_STREQ(threea, "waldowaldowaldo"); } TEST(string_has_cc) { @@ -293,14 +322,19 @@ TEST(string_has_cc) { TEST(ascii_strlower) { char a[] = "AabBcC Jk Ii Od LKJJJ kkd LK"; - assert_se(streq(ascii_strlower(a), "aabbcc jk ii od lkjjj kkd lk")); + ASSERT_STREQ(ascii_strlower(a), "aabbcc jk ii od lkjjj kkd lk"); } TEST(strshorten) { char s[] = "foobar"; + assert_se(strlen(strshorten(s, SIZE_MAX)) == 6); + assert_se(strlen(strshorten(s, SIZE_MAX-1)) == 6); + assert_se(strlen(strshorten(s, SIZE_MAX-2)) == 6); assert_se(strlen(strshorten(s, 6)) == 6); + assert_se(strlen(strshorten(s, 7)) == 6); assert_se(strlen(strshorten(s, 12)) == 6); + assert_se(strlen(strshorten(s, 5)) == 5); assert_se(strlen(strshorten(s, 2)) == 2); assert_se(strlen(strshorten(s, 0)) == 0); } @@ -309,63 +343,63 @@ TEST(strjoina) { char *actual; actual = strjoina("", "foo", "bar"); - assert_se(streq(actual, "foobar")); + ASSERT_STREQ(actual, "foobar"); actual = strjoina("foo", "bar", "baz"); - assert_se(streq(actual, "foobarbaz")); + ASSERT_STREQ(actual, "foobarbaz"); actual = strjoina("foo", "", "bar", "baz"); - assert_se(streq(actual, "foobarbaz")); + ASSERT_STREQ(actual, "foobarbaz"); actual = strjoina("foo"); - assert_se(streq(actual, "foo")); + ASSERT_STREQ(actual, "foo"); actual = strjoina(NULL); - assert_se(streq(actual, "")); + ASSERT_STREQ(actual, ""); actual = strjoina(NULL, "foo"); - assert_se(streq(actual, "")); + ASSERT_STREQ(actual, ""); actual = strjoina("foo", NULL, "bar"); - assert_se(streq(actual, "foo")); + ASSERT_STREQ(actual, "foo"); actual = strjoina("/sys/fs/cgroup/", "dn", "/a/b/c", "/cgroup.procs"); - assert_se(streq(actual, "/sys/fs/cgroup/dn/a/b/c/cgroup.procs")); + ASSERT_STREQ(actual, "/sys/fs/cgroup/dn/a/b/c/cgroup.procs"); actual = strjoina("/sys/fs/cgroup/", "dn", NULL, NULL); - assert_se(streq(actual, "/sys/fs/cgroup/dn")); + ASSERT_STREQ(actual, "/sys/fs/cgroup/dn"); } TEST(strjoin) { char *actual; actual = strjoin("", "foo", "bar"); - assert_se(streq(actual, "foobar")); - mfree(actual); + ASSERT_STREQ(actual, "foobar"); + free(actual); actual = strjoin("foo", "bar", "baz"); - assert_se(streq(actual, "foobarbaz")); - mfree(actual); + ASSERT_STREQ(actual, "foobarbaz"); + free(actual); actual = strjoin("foo", "", "bar", "baz"); - assert_se(streq(actual, "foobarbaz")); - mfree(actual); + ASSERT_STREQ(actual, "foobarbaz"); + free(actual); actual = strjoin("foo", NULL); - assert_se(streq(actual, "foo")); - mfree(actual); + ASSERT_STREQ(actual, "foo"); + free(actual); actual = strjoin(NULL, NULL); - assert_se(streq(actual, "")); - mfree(actual); + ASSERT_STREQ(actual, ""); + free(actual); actual = strjoin(NULL, "foo"); - assert_se(streq(actual, "")); - mfree(actual); + ASSERT_STREQ(actual, ""); + free(actual); actual = strjoin("foo", NULL, "bar"); - assert_se(streq(actual, "foo")); - mfree(actual); + ASSERT_STREQ(actual, "foo"); + free(actual); } TEST(strcmp_ptr) { @@ -402,7 +436,7 @@ TEST(foreach_word) { } assert_se(r > 0); - assert_se(streq(expected[i++], word)); + ASSERT_STREQ(expected[i++], word); } } @@ -423,10 +457,10 @@ static void check(const char *test, char** expected, bool trailing) { break; } - assert_se(streq(word, expected[i++])); + ASSERT_STREQ(word, expected[i++]); printf("<%s>\n", word); } - assert_se(expected[i] == NULL); + ASSERT_NULL(expected[i]); } TEST(foreach_word_quoted) { @@ -478,7 +512,7 @@ TEST(delete_chars) { char *s, input[] = " hello, waldo. abc"; s = delete_chars(input, WHITESPACE); - assert_se(streq(s, "hello,waldo.abc")); + ASSERT_STREQ(s, "hello,waldo.abc"); assert_se(s == input); } @@ -489,19 +523,19 @@ TEST(delete_trailing_chars) { input3[] = "abcdef"; s = delete_trailing_chars(input1, WHITESPACE); - assert_se(streq(s, " \n \r k")); + ASSERT_STREQ(s, " \n \r k"); assert_se(s == input1); s = delete_trailing_chars(input2, "kt"); - assert_se(streq(s, "kkkkthiskkkiskkkaktes")); + ASSERT_STREQ(s, "kkkkthiskkkiskkkaktes"); assert_se(s == input2); s = delete_trailing_chars(input3, WHITESPACE); - assert_se(streq(s, "abcdef")); + ASSERT_STREQ(s, "abcdef"); assert_se(s == input3); s = delete_trailing_chars(input3, "fe"); - assert_se(streq(s, "abcd")); + ASSERT_STREQ(s, "abcd"); assert_se(s == input3); } @@ -511,11 +545,11 @@ TEST(delete_trailing_slashes) { s3[] = "foobar", s4[] = ""; - assert_se(streq(delete_trailing_chars(s1, "_"), "foobar//")); - assert_se(streq(delete_trailing_chars(s1, "/"), "foobar")); - assert_se(streq(delete_trailing_chars(s2, "/"), "foobar")); - assert_se(streq(delete_trailing_chars(s3, "/"), "foobar")); - assert_se(streq(delete_trailing_chars(s4, "/"), "")); + ASSERT_STREQ(delete_trailing_chars(s1, "_"), "foobar//"); + ASSERT_STREQ(delete_trailing_chars(s1, "/"), "foobar"); + ASSERT_STREQ(delete_trailing_chars(s2, "/"), "foobar"); + ASSERT_STREQ(delete_trailing_chars(s3, "/"), "foobar"); + ASSERT_STREQ(delete_trailing_chars(s4, "/"), ""); } TEST(skip_leading_chars) { @@ -523,11 +557,11 @@ TEST(skip_leading_chars) { input2[] = "kkkkthiskkkiskkkaktestkkk", input3[] = "abcdef"; - assert_se(streq(skip_leading_chars(input1, WHITESPACE), "k \n \r ")); - assert_se(streq(skip_leading_chars(input2, "k"), "thiskkkiskkkaktestkkk")); - assert_se(streq(skip_leading_chars(input2, "tk"), "hiskkkiskkkaktestkkk")); - assert_se(streq(skip_leading_chars(input3, WHITESPACE), "abcdef")); - assert_se(streq(skip_leading_chars(input3, "bcaef"), "def")); + ASSERT_STREQ(skip_leading_chars(input1, WHITESPACE), "k \n \r "); + ASSERT_STREQ(skip_leading_chars(input2, "k"), "thiskkkiskkkaktestkkk"); + ASSERT_STREQ(skip_leading_chars(input2, "tk"), "hiskkkiskkkaktestkkk"); + ASSERT_STREQ(skip_leading_chars(input3, WHITESPACE), "abcdef"); + ASSERT_STREQ(skip_leading_chars(input3, "bcaef"), "def"); } TEST(in_charset) { @@ -542,19 +576,19 @@ TEST(split_pair) { assert_se(split_pair("foo=bar", "", &a, &b) == -EINVAL); assert_se(split_pair("", "=", &a, &b) == -EINVAL); assert_se(split_pair("foo=bar", "=", &a, &b) >= 0); - assert_se(streq(a, "foo")); - assert_se(streq(b, "bar")); + ASSERT_STREQ(a, "foo"); + ASSERT_STREQ(b, "bar"); free(a); free(b); assert_se(split_pair("==", "==", &a, &b) >= 0); - assert_se(streq(a, "")); - assert_se(streq(b, "")); + ASSERT_STREQ(a, ""); + ASSERT_STREQ(b, ""); free(a); free(b); assert_se(split_pair("===", "==", &a, &b) >= 0); - assert_se(streq(a, "")); - assert_se(streq(b, "=")); + ASSERT_STREQ(a, ""); + ASSERT_STREQ(b, "="); } TEST(first_word) { @@ -578,33 +612,33 @@ TEST(strlen_ptr) { } TEST(memory_startswith) { - assert_se(streq(memory_startswith("", 0, ""), "")); - assert_se(streq(memory_startswith("", 1, ""), "")); - assert_se(streq(memory_startswith("x", 2, ""), "x")); + ASSERT_STREQ(memory_startswith("", 0, ""), ""); + ASSERT_STREQ(memory_startswith("", 1, ""), ""); + ASSERT_STREQ(memory_startswith("x", 2, ""), "x"); assert_se(!memory_startswith("", 1, "x")); assert_se(!memory_startswith("", 1, "xxxxxxxx")); - assert_se(streq(memory_startswith("xxx", 4, "x"), "xx")); - assert_se(streq(memory_startswith("xxx", 4, "xx"), "x")); - assert_se(streq(memory_startswith("xxx", 4, "xxx"), "")); + ASSERT_STREQ(memory_startswith("xxx", 4, "x"), "xx"); + ASSERT_STREQ(memory_startswith("xxx", 4, "xx"), "x"); + ASSERT_STREQ(memory_startswith("xxx", 4, "xxx"), ""); assert_se(!memory_startswith("xxx", 4, "xxxx")); } TEST(memory_startswith_no_case) { - assert_se(streq(memory_startswith_no_case("", 0, ""), "")); - assert_se(streq(memory_startswith_no_case("", 1, ""), "")); - assert_se(streq(memory_startswith_no_case("x", 2, ""), "x")); - assert_se(streq(memory_startswith_no_case("X", 2, ""), "X")); + ASSERT_STREQ(memory_startswith_no_case("", 0, ""), ""); + ASSERT_STREQ(memory_startswith_no_case("", 1, ""), ""); + ASSERT_STREQ(memory_startswith_no_case("x", 2, ""), "x"); + ASSERT_STREQ(memory_startswith_no_case("X", 2, ""), "X"); assert_se(!memory_startswith_no_case("", 1, "X")); assert_se(!memory_startswith_no_case("", 1, "xxxxXXXX")); - assert_se(streq(memory_startswith_no_case("xxx", 4, "X"), "xx")); - assert_se(streq(memory_startswith_no_case("XXX", 4, "x"), "XX")); - assert_se(streq(memory_startswith_no_case("XXX", 4, "X"), "XX")); - assert_se(streq(memory_startswith_no_case("xxx", 4, "XX"), "x")); - assert_se(streq(memory_startswith_no_case("XXX", 4, "xx"), "X")); - assert_se(streq(memory_startswith_no_case("XXX", 4, "XX"), "X")); - assert_se(streq(memory_startswith_no_case("xxx", 4, "XXX"), "")); - assert_se(streq(memory_startswith_no_case("XXX", 4, "xxx"), "")); - assert_se(streq(memory_startswith_no_case("XXX", 4, "XXX"), "")); + ASSERT_STREQ(memory_startswith_no_case("xxx", 4, "X"), "xx"); + ASSERT_STREQ(memory_startswith_no_case("XXX", 4, "x"), "XX"); + ASSERT_STREQ(memory_startswith_no_case("XXX", 4, "X"), "XX"); + ASSERT_STREQ(memory_startswith_no_case("xxx", 4, "XX"), "x"); + ASSERT_STREQ(memory_startswith_no_case("XXX", 4, "xx"), "X"); + ASSERT_STREQ(memory_startswith_no_case("XXX", 4, "XX"), "X"); + ASSERT_STREQ(memory_startswith_no_case("xxx", 4, "XXX"), ""); + ASSERT_STREQ(memory_startswith_no_case("XXX", 4, "xxx"), ""); + ASSERT_STREQ(memory_startswith_no_case("XXX", 4, "XXX"), ""); assert_se(memory_startswith_no_case((char[2]){'x', 'x'}, 2, "xx")); assert_se(memory_startswith_no_case((char[2]){'x', 'X'}, 2, "xX")); @@ -617,7 +651,7 @@ static void test_string_truncate_lines_one(const char *input, size_t n_lines, co int k; assert_se((k = string_truncate_lines(input, n_lines, &b)) >= 0); - assert_se(streq(b, output)); + ASSERT_STREQ(b, output); assert_se(!!k == truncation); } @@ -688,7 +722,7 @@ static void test_string_extract_lines_one(const char *input, size_t i, const cha int k; assert_se((k = string_extract_line(input, i, &b)) >= 0); - assert_se(streq(b ?: input, output)); + ASSERT_STREQ(b ?: input, output); assert_se(!!k == more); } @@ -765,25 +799,25 @@ TEST(string_contains_word_strv) { assert_se(string_contains_word_strv("a b cc", NULL, STRV_MAKE("a", "b"), NULL)); assert_se(string_contains_word_strv("a b cc", NULL, STRV_MAKE("a", "b"), &w)); - assert_se(streq(w, "a")); + ASSERT_STREQ(w, "a"); assert_se(!string_contains_word_strv("a b cc", NULL, STRV_MAKE("d"), &w)); - assert_se(w == NULL); + ASSERT_NULL(w); assert_se(string_contains_word_strv("a b cc", NULL, STRV_MAKE("b", "a"), &w)); - assert_se(streq(w, "a")); + ASSERT_STREQ(w, "a"); assert_se(string_contains_word_strv("b a b cc", NULL, STRV_MAKE("b", "a", "b"), &w)); - assert_se(streq(w, "b")); + ASSERT_STREQ(w, "b"); assert_se(string_contains_word_strv("a b cc", NULL, STRV_MAKE("b", ""), &w)); - assert_se(streq(w, "b")); + ASSERT_STREQ(w, "b"); assert_se(!string_contains_word_strv("a b cc", NULL, STRV_MAKE(""), &w)); - assert_se(w == NULL); + ASSERT_NULL(w); assert_se(string_contains_word_strv("a b cc", " ", STRV_MAKE(""), &w)); - assert_se(streq(w, "")); + ASSERT_STREQ(w, ""); } TEST(string_contains_word) { @@ -1105,38 +1139,38 @@ TEST(strextendf) { _cleanup_free_ char *p = NULL; assert_se(strextendf(&p, "<%i>", 77) >= 0); - assert_se(streq(p, "<77>")); + ASSERT_STREQ(p, "<77>"); assert_se(strextendf(&p, "<%i>", 99) >= 0); - assert_se(streq(p, "<77><99>")); + ASSERT_STREQ(p, "<77><99>"); assert_se(strextendf(&p, "<%80i>", 88) >= 0); - assert_se(streq(p, "<77><99>< 88>")); + ASSERT_STREQ(p, "<77><99>< 88>"); assert_se(strextendf(&p, "<%08x>", 0x1234u) >= 0); - assert_se(streq(p, "<77><99>< 88><00001234>")); + ASSERT_STREQ(p, "<77><99>< 88><00001234>"); p = mfree(p); assert_se(strextendf_with_separator(&p, ",", "<%i>", 77) >= 0); - assert_se(streq(p, "<77>")); + ASSERT_STREQ(p, "<77>"); assert_se(strextendf_with_separator(&p, ",", "<%i>", 99) >= 0); - assert_se(streq(p, "<77>,<99>")); + ASSERT_STREQ(p, "<77>,<99>"); assert_se(strextendf_with_separator(&p, ",", "<%80i>", 88) >= 0); - assert_se(streq(p, "<77>,<99>,< 88>")); + ASSERT_STREQ(p, "<77>,<99>,< 88>"); assert_se(strextendf_with_separator(&p, ",", "<%08x>", 0x1234u) >= 0); - assert_se(streq(p, "<77>,<99>,< 88>,<00001234>")); + ASSERT_STREQ(p, "<77>,<99>,< 88>,<00001234>"); } TEST(string_replace_char) { - assert_se(streq(string_replace_char(strdupa_safe(""), 'a', 'b'), "")); - assert_se(streq(string_replace_char(strdupa_safe("abc"), 'a', 'b'), "bbc")); - assert_se(streq(string_replace_char(strdupa_safe("hoge"), 'a', 'b'), "hoge")); - assert_se(streq(string_replace_char(strdupa_safe("aaaa"), 'a', 'b'), "bbbb")); - assert_se(streq(string_replace_char(strdupa_safe("aaaa"), 'a', '\t'), "\t\t\t\t")); + ASSERT_STREQ(string_replace_char(strdupa_safe(""), 'a', 'b'), ""); + ASSERT_STREQ(string_replace_char(strdupa_safe("abc"), 'a', 'b'), "bbc"); + ASSERT_STREQ(string_replace_char(strdupa_safe("hoge"), 'a', 'b'), "hoge"); + ASSERT_STREQ(string_replace_char(strdupa_safe("aaaa"), 'a', 'b'), "bbbb"); + ASSERT_STREQ(string_replace_char(strdupa_safe("aaaa"), 'a', '\t'), "\t\t\t\t"); } TEST(strspn_from_end) { @@ -1180,7 +1214,7 @@ TEST(streq_skip_trailing_chars) { do { \ _cleanup_free_ char *b = NULL; \ assert_se(make_cstring((x), ELEMENTSOF(x), (mode), &b) == (ret)); \ - assert_se(streq_ptr(b, (expect))); \ + ASSERT_STREQ(b, (expect)); \ } while(false) TEST(make_cstring) { @@ -1261,7 +1295,7 @@ TEST(strstrafter) { assert_se(!strstrafter(NULL, NULL)); assert_se(!strstrafter("", NULL)); assert_se(!strstrafter(NULL, "")); - assert_se(streq_ptr(strstrafter("", ""), "")); + ASSERT_STREQ(strstrafter("", ""), ""); assert_se(strstrafter(buffer, "a") == buffer + 1); assert_se(strstrafter(buffer, "") == buffer); @@ -1285,18 +1319,18 @@ TEST(version_is_valid) { TEST(strextendn) { _cleanup_free_ char *x = NULL; - assert_se(streq_ptr(strextendn(&x, NULL, 0), "")); + ASSERT_STREQ(strextendn(&x, NULL, 0), ""); x = mfree(x); - assert_se(streq_ptr(strextendn(&x, "", 0), "")); + ASSERT_STREQ(strextendn(&x, "", 0), ""); x = mfree(x); - assert_se(streq_ptr(strextendn(&x, "xxx", 3), "xxx")); - assert_se(streq_ptr(strextendn(&x, "xxx", 3), "xxxxxx")); - assert_se(streq_ptr(strextendn(&x, "...", 1), "xxxxxx.")); - assert_se(streq_ptr(strextendn(&x, "...", 2), "xxxxxx...")); - assert_se(streq_ptr(strextendn(&x, "...", 3), "xxxxxx......")); - assert_se(streq_ptr(strextendn(&x, "...", 4), "xxxxxx.........")); + ASSERT_STREQ(strextendn(&x, "xxx", 3), "xxx"); + ASSERT_STREQ(strextendn(&x, "xxx", 3), "xxxxxx"); + ASSERT_STREQ(strextendn(&x, "...", 1), "xxxxxx."); + ASSERT_STREQ(strextendn(&x, "...", 2), "xxxxxx..."); + ASSERT_STREQ(strextendn(&x, "...", 3), "xxxxxx......"); + ASSERT_STREQ(strextendn(&x, "...", 4), "xxxxxx........."); x = mfree(x); } @@ -1324,4 +1358,27 @@ TEST(strlevenshtein) { assert_se(strlevenshtein("sunday", "saturday") == 3); } +TEST(strrstr) { + assert_se(!strrstr(NULL, NULL)); + assert_se(!strrstr("foo", NULL)); + assert_se(!strrstr(NULL, "foo")); + + const char *p = "foo"; + assert_se(strrstr(p, "foo") == p); + assert_se(strrstr(p, "fo") == p); + assert_se(strrstr(p, "f") == p); + assert_se(strrstr(p, "oo") == p + 1); + assert_se(strrstr(p, "o") == p + 2); + assert_se(strrstr(p, "") == p + strlen(p)); + assert_se(!strrstr(p, "bar")); + + p = "xoxoxox"; + assert_se(strrstr(p, "") == p + strlen(p)); + assert_se(strrstr(p, "x") == p + 6); + assert_se(strrstr(p, "ox") == p + 5); + assert_se(strrstr(p, "xo") == p + 4); + assert_se(strrstr(p, "xox") == p + 4); + assert_se(!strrstr(p, "xx")); +} + DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-strip-tab-ansi.c b/src/test/test-strip-tab-ansi.c index 6f73d26..3ad0fcd 100644 --- a/src/test/test-strip-tab-ansi.c +++ b/src/test/test-strip-tab-ansi.c @@ -15,38 +15,38 @@ TEST(strip_tab_ansi) { assert_se(p = strdup("\tFoobar\tbar\twaldo\t")); assert_se(strip_tab_ansi(&p, NULL, NULL)); fprintf(stdout, "<%s>\n", p); - assert_se(streq(p, " Foobar bar waldo ")); + ASSERT_STREQ(p, " Foobar bar waldo "); free(p); assert_se(p = strdup(ANSI_HIGHLIGHT "Hello" ANSI_NORMAL ANSI_HIGHLIGHT_RED " world!" ANSI_NORMAL)); assert_se(strip_tab_ansi(&p, NULL, NULL)); fprintf(stdout, "<%s>\n", p); - assert_se(streq(p, "Hello world!")); + ASSERT_STREQ(p, "Hello world!"); free(p); assert_se(p = strdup("\x1B[\x1B[\t\x1B[" ANSI_HIGHLIGHT "\x1B[" "Hello" ANSI_NORMAL ANSI_HIGHLIGHT_RED " world!" ANSI_NORMAL)); assert_se(strip_tab_ansi(&p, NULL, NULL)); - assert_se(streq(p, "\x1B[\x1B[ \x1B[\x1B[Hello world!")); + ASSERT_STREQ(p, "\x1B[\x1B[ \x1B[\x1B[Hello world!"); free(p); assert_se(p = strdup("\x1B[waldo")); assert_se(strip_tab_ansi(&p, NULL, NULL)); - assert_se(streq(p, "\x1B[waldo")); + ASSERT_STREQ(p, "\x1B[waldo"); free(p); assert_se(p = strdup("\r\rwaldo")); assert_se(strip_tab_ansi(&p, NULL, NULL)); - assert_se(streq(p, "\r\rwaldo")); + ASSERT_STREQ(p, "\r\rwaldo"); free(p); assert_se(p = strdup("waldo\r\r")); assert_se(strip_tab_ansi(&p, NULL, NULL)); - assert_se(streq(p, "waldo")); + ASSERT_STREQ(p, "waldo"); free(p); assert_se(p = strdup("waldo\r\r\n\r\n")); assert_se(strip_tab_ansi(&p, NULL, NULL)); - assert_se(streq(p, "waldo\n\n")); + ASSERT_STREQ(p, "waldo\n\n"); free(p); assert_se(terminal_urlify_path("/etc/fstab", "i am a fabulous link", &urlified) >= 0); @@ -55,7 +55,7 @@ TEST(strip_tab_ansi) { printf("<%s>\n", p); assert_se(strip_tab_ansi(&p, NULL, NULL)); printf("<%s>\n", p); - assert_se(streq(p, "something i am a fabulous link something-else")); + ASSERT_STREQ(p, "something i am a fabulous link something-else"); p = mfree(p); /* Truncate the formatted string in the middle of an ANSI sequence (in which case we shouldn't touch the @@ -65,7 +65,7 @@ TEST(strip_tab_ansi) { *z = 0; assert_se(qq = strdup(q)); assert_se(strip_tab_ansi(&q, NULL, NULL)); - assert_se(streq(q, qq)); + ASSERT_STREQ(q, qq); } } diff --git a/src/test/test-strv.c b/src/test/test-strv.c index cfd662b..28b8b22 100644 --- a/src/test/test-strv.c +++ b/src/test/test-strv.c @@ -34,9 +34,9 @@ TEST(startswith_set) { assert_se(STARTSWITH_SET("abc", "ax", "abx", "abc")); assert_se(!STARTSWITH_SET("abc", "ax", "abx", "abcx")); - assert_se(streq_ptr(STARTSWITH_SET("foobar", "hhh", "kkk", "foo", "zzz"), "bar")); - assert_se(streq_ptr(STARTSWITH_SET("foobar", "hhh", "kkk", "", "zzz"), "foobar")); - assert_se(streq_ptr(STARTSWITH_SET("", "hhh", "kkk", "zzz", ""), "")); + ASSERT_STREQ(STARTSWITH_SET("foobar", "hhh", "kkk", "foo", "zzz"), "bar"); + ASSERT_STREQ(STARTSWITH_SET("foobar", "hhh", "kkk", "", "zzz"), "foobar"); + ASSERT_STREQ(STARTSWITH_SET("", "hhh", "kkk", "zzz", ""), ""); } static const char* const input_table_multiple[] = { @@ -125,78 +125,78 @@ TEST(strv_find_startswith) { TEST(strv_join) { _cleanup_free_ char *p = strv_join((char **)input_table_multiple, ", "); assert_se(p); - assert_se(streq(p, "one, two, three")); + ASSERT_STREQ(p, "one, two, three"); _cleanup_free_ char *q = strv_join((char **)input_table_multiple, ";"); assert_se(q); - assert_se(streq(q, "one;two;three")); + ASSERT_STREQ(q, "one;two;three"); _cleanup_free_ char *r = strv_join((char **)input_table_multiple, NULL); assert_se(r); - assert_se(streq(r, "one two three")); + ASSERT_STREQ(r, "one two three"); _cleanup_free_ char *s = strv_join(STRV_MAKE("1", "2", "3,3"), ","); assert_se(s); - assert_se(streq(s, "1,2,3,3")); + ASSERT_STREQ(s, "1,2,3,3"); _cleanup_free_ char *t = strv_join((char **)input_table_one, ", "); assert_se(t); - assert_se(streq(t, "one")); + ASSERT_STREQ(t, "one"); _cleanup_free_ char *u = strv_join((char **)input_table_none, ", "); assert_se(u); - assert_se(streq(u, "")); + ASSERT_STREQ(u, ""); _cleanup_free_ char *v = strv_join((char **)input_table_two_empties, ", "); assert_se(v); - assert_se(streq(v, ", ")); + ASSERT_STREQ(v, ", "); _cleanup_free_ char *w = strv_join((char **)input_table_one_empty, ", "); assert_se(w); - assert_se(streq(w, "")); + ASSERT_STREQ(w, ""); } TEST(strv_join_full) { _cleanup_free_ char *p = strv_join_full((char **)input_table_multiple, ", ", "foo", false); assert_se(p); - assert_se(streq(p, "fooone, footwo, foothree")); + ASSERT_STREQ(p, "fooone, footwo, foothree"); _cleanup_free_ char *q = strv_join_full((char **)input_table_multiple, ";", "foo", false); assert_se(q); - assert_se(streq(q, "fooone;footwo;foothree")); + ASSERT_STREQ(q, "fooone;footwo;foothree"); _cleanup_free_ char *r = strv_join_full(STRV_MAKE("a", "a;b", "a:c"), ";", NULL, true); assert_se(r); - assert_se(streq(r, "a;a\\;b;a:c")); + ASSERT_STREQ(r, "a;a\\;b;a:c"); _cleanup_free_ char *s = strv_join_full(STRV_MAKE("a", "a;b", "a;;c", ";", ";x"), ";", NULL, true); assert_se(s); - assert_se(streq(s, "a;a\\;b;a\\;\\;c;\\;;\\;x")); + ASSERT_STREQ(s, "a;a\\;b;a\\;\\;c;\\;;\\;x"); _cleanup_free_ char *t = strv_join_full(STRV_MAKE("a", "a;b", "a:c", ";"), ";", "=", true); assert_se(t); - assert_se(streq(t, "=a;=a\\;b;=a:c;=\\;")); + ASSERT_STREQ(t, "=a;=a\\;b;=a:c;=\\;"); t = mfree(t); _cleanup_free_ char *u = strv_join_full((char **)input_table_multiple, NULL, "foo", false); assert_se(u); - assert_se(streq(u, "fooone footwo foothree")); + ASSERT_STREQ(u, "fooone footwo foothree"); _cleanup_free_ char *v = strv_join_full((char **)input_table_one, ", ", "foo", false); assert_se(v); - assert_se(streq(v, "fooone")); + ASSERT_STREQ(v, "fooone"); _cleanup_free_ char *w = strv_join_full((char **)input_table_none, ", ", "foo", false); assert_se(w); - assert_se(streq(w, "")); + ASSERT_STREQ(w, ""); _cleanup_free_ char *x = strv_join_full((char **)input_table_two_empties, ", ", "foo", false); assert_se(x); - assert_se(streq(x, "foo, foo")); + ASSERT_STREQ(x, "foo, foo"); _cleanup_free_ char *y = strv_join_full((char **)input_table_one_empty, ", ", "foo", false); assert_se(y); - assert_se(streq(y, "foo")); + ASSERT_STREQ(y, "foo"); } static void test_strv_unquote_one(const char *quoted, char **list) { @@ -215,9 +215,9 @@ static void test_strv_unquote_one(const char *quoted, char **list) { puts(j); STRV_FOREACH(t, s) - assert_se(streq(list[i++], *t)); + ASSERT_STREQ(list[i++], *t); - assert_se(list[i] == NULL); + ASSERT_NULL(list[i]); } TEST(strv_unquote) { @@ -245,7 +245,7 @@ static void test_invalid_unquote_one(const char *quoted) { log_info("/* %s */", __func__); r = strv_split_full(&s, quoted, WHITESPACE, EXTRACT_UNQUOTE); - assert_se(s == NULL); + ASSERT_NULL(s); assert_se(r == -EINVAL); } @@ -402,12 +402,12 @@ TEST(strv_split_full) { r = strv_split_full(&l, str, ":", EXTRACT_DONT_COALESCE_SEPARATORS); assert_se(r == (int) strv_length(l)); - assert_se(streq_ptr(l[0], "")); - assert_se(streq_ptr(l[1], "foo:bar")); - assert_se(streq_ptr(l[2], "")); - assert_se(streq_ptr(l[3], "waldo")); - assert_se(streq_ptr(l[4], "")); - assert_se(streq_ptr(l[5], NULL)); + ASSERT_STREQ(l[0], ""); + ASSERT_STREQ(l[1], "foo:bar"); + ASSERT_STREQ(l[2], ""); + ASSERT_STREQ(l[3], "waldo"); + ASSERT_STREQ(l[4], ""); + ASSERT_STREQ(l[5], NULL); } TEST(strv_split_and_extend_full) { @@ -420,14 +420,14 @@ TEST(strv_split_and_extend_full) { assert_se(r == (int) strv_length(l)); r = strv_split_and_extend_full(&l, str1, ":", false, EXTRACT_DONT_COALESCE_SEPARATORS); assert_se(r == (int) strv_length(l)); - assert_se(streq_ptr(l[0], "")); - assert_se(streq_ptr(l[1], "foo:bar")); - assert_se(streq_ptr(l[2], "")); + ASSERT_STREQ(l[0], ""); + ASSERT_STREQ(l[1], "foo:bar"); + ASSERT_STREQ(l[2], ""); r = strv_split_and_extend_full(&l, str2, ":", false, 0); assert_se(r == (int) strv_length(l)); - assert_se(streq_ptr(l[3], "waldo")); - assert_se(streq_ptr(l[4], "baz")); - assert_se(streq_ptr(l[5], NULL)); + ASSERT_STREQ(l[3], "waldo"); + ASSERT_STREQ(l[4], "baz"); + ASSERT_STREQ(l[5], NULL); } TEST(strv_split_colon_pairs) { @@ -439,19 +439,19 @@ TEST(strv_split_colon_pairs) { r = strv_split_colon_pairs(&l, str); assert_se(r == (int) strv_length(l)); assert_se(r == 12); - assert_se(streq_ptr(l[0], "one")); - assert_se(streq_ptr(l[1], "two")); - assert_se(streq_ptr(l[2], "three")); - assert_se(streq_ptr(l[3], "")); - assert_se(streq_ptr(l[4], "four")); - assert_se(streq_ptr(l[5], "five")); - assert_se(streq_ptr(l[6], "six")); - assert_se(streq_ptr(l[7], "")); - assert_se(streq_ptr(l[8], "seven")); - assert_se(streq_ptr(l[9], "eight:nine")); - assert_se(streq_ptr(l[10], "ten:eleven\\")); - assert_se(streq_ptr(l[11], "")); - assert_se(streq_ptr(l[12], NULL)); + ASSERT_STREQ(l[0], "one"); + ASSERT_STREQ(l[1], "two"); + ASSERT_STREQ(l[2], "three"); + ASSERT_STREQ(l[3], ""); + ASSERT_STREQ(l[4], "four"); + ASSERT_STREQ(l[5], "five"); + ASSERT_STREQ(l[6], "six"); + ASSERT_STREQ(l[7], ""); + ASSERT_STREQ(l[8], "seven"); + ASSERT_STREQ(l[9], "eight:nine"); + ASSERT_STREQ(l[10], "ten:eleven\\"); + ASSERT_STREQ(l[11], ""); + ASSERT_STREQ(l[12], NULL); r = strv_split_colon_pairs(&l, str_inval); assert_se(r == -EINVAL); @@ -466,7 +466,7 @@ TEST(strv_split_newlines) { assert_se(l); STRV_FOREACH(s, l) - assert_se(streq(*s, input_table_multiple[i++])); + ASSERT_STREQ(*s, input_table_multiple[i++]); } TEST(strv_split_newlines_full) { @@ -520,11 +520,27 @@ TEST(strv_sort) { strv_sort((char **)input_table); - assert_se(streq(input_table[0], "CAPITAL LETTERS FIRST")); - assert_se(streq(input_table[1], "apple")); - assert_se(streq(input_table[2], "banana")); - assert_se(streq(input_table[3], "citrus")); - assert_se(streq(input_table[4], "durian")); + ASSERT_STREQ(input_table[0], "CAPITAL LETTERS FIRST"); + ASSERT_STREQ(input_table[1], "apple"); + ASSERT_STREQ(input_table[2], "banana"); + ASSERT_STREQ(input_table[3], "citrus"); + ASSERT_STREQ(input_table[4], "durian"); +} + +TEST(strv_extend_strv_biconcat) { + _cleanup_strv_free_ char **a = NULL, **b = NULL; + + a = strv_new("without", "suffix"); + b = strv_new("with", "suffix"); + assert_se(a); + assert_se(b); + + assert_se(strv_extend_strv_biconcat(&a, "prefix_", (const char* const*) b, "_suffix") >= 0); + + ASSERT_STREQ(a[0], "without"); + ASSERT_STREQ(a[1], "suffix"); + ASSERT_STREQ(a[2], "prefix_with_suffix"); + ASSERT_STREQ(a[3], "prefix_suffix_suffix"); } TEST(strv_extend_strv_concat) { @@ -535,12 +551,12 @@ TEST(strv_extend_strv_concat) { assert_se(a); assert_se(b); - assert_se(strv_extend_strv_concat(&a, b, "_suffix") >= 0); + assert_se(strv_extend_strv_concat(&a, (const char* const*) b, "_suffix") >= 0); - assert_se(streq(a[0], "without")); - assert_se(streq(a[1], "suffix")); - assert_se(streq(a[2], "with_suffix")); - assert_se(streq(a[3], "suffix_suffix")); + ASSERT_STREQ(a[0], "without"); + ASSERT_STREQ(a[1], "suffix"); + ASSERT_STREQ(a[2], "with_suffix"); + ASSERT_STREQ(a[3], "suffix_suffix"); } TEST(strv_extend_strv) { @@ -553,19 +569,19 @@ TEST(strv_extend_strv) { assert_se(strv_extend_strv(&a, b, true) == 3); - assert_se(streq(a[0], "abc")); - assert_se(streq(a[1], "def")); - assert_se(streq(a[2], "ghi")); - assert_se(streq(a[3], "jkl")); - assert_se(streq(a[4], "mno")); - assert_se(streq(a[5], "pqr")); + ASSERT_STREQ(a[0], "abc"); + ASSERT_STREQ(a[1], "def"); + ASSERT_STREQ(a[2], "ghi"); + ASSERT_STREQ(a[3], "jkl"); + ASSERT_STREQ(a[4], "mno"); + ASSERT_STREQ(a[5], "pqr"); assert_se(strv_length(a) == 6); assert_se(strv_extend_strv(&n, b, false) >= 0); - assert_se(streq(n[0], "jkl")); - assert_se(streq(n[1], "mno")); - assert_se(streq(n[2], "abc")); - assert_se(streq(n[3], "pqr")); + ASSERT_STREQ(n[0], "jkl"); + ASSERT_STREQ(n[1], "mno"); + ASSERT_STREQ(n[2], "abc"); + ASSERT_STREQ(n[3], "pqr"); assert_se(strv_length(n) == 4); } @@ -581,11 +597,11 @@ TEST(strv_extend_with_size) { assert_se(strv_extend_with_size(&a, &n, "test3") >= 0); assert_se(n == 4); - assert_se(streq(a[0], "test")); - assert_se(streq(a[1], "test1")); - assert_se(streq(a[2], "test2")); - assert_se(streq(a[3], "test3")); - assert_se(a[4] == NULL); + ASSERT_STREQ(a[0], "test"); + ASSERT_STREQ(a[1], "test1"); + ASSERT_STREQ(a[2], "test2"); + ASSERT_STREQ(a[3], "test3"); + ASSERT_NULL(a[4]); } TEST(strv_extend) { @@ -596,10 +612,10 @@ TEST(strv_extend) { assert_se(strv_extend(&a, "test2") >= 0); assert_se(strv_extend(&b, "test3") >= 0); - assert_se(streq(a[0], "test")); - assert_se(streq(a[1], "test1")); - assert_se(streq(a[2], "test2")); - assert_se(streq(b[0], "test3")); + ASSERT_STREQ(a[0], "test"); + ASSERT_STREQ(a[1], "test1"); + ASSERT_STREQ(a[2], "test2"); + ASSERT_STREQ(b[0], "test3"); } TEST(strv_extendf) { @@ -610,10 +626,10 @@ TEST(strv_extendf) { assert_se(strv_extendf(&a, "test2 %s %d %s", "foo", 128, "bar") >= 0); assert_se(strv_extendf(&b, "test3 %s %s %d", "bar", "foo", 128) >= 0); - assert_se(streq(a[0], "test")); - assert_se(streq(a[1], "test1")); - assert_se(streq(a[2], "test2 foo 128 bar")); - assert_se(streq(b[0], "test3 bar foo 128")); + ASSERT_STREQ(a[0], "test"); + ASSERT_STREQ(a[1], "test1"); + ASSERT_STREQ(a[2], "test2 foo 128 bar"); + ASSERT_STREQ(b[0], "test3 bar foo 128"); } TEST(strv_foreach) { @@ -624,7 +640,7 @@ TEST(strv_foreach) { assert_se(a); STRV_FOREACH(check, a) - assert_se(streq(*check, input_table_multiple[i++])); + ASSERT_STREQ(*check, input_table_multiple[i++]); } TEST(strv_foreach_backwards) { @@ -636,7 +652,7 @@ TEST(strv_foreach_backwards) { assert_se(a); STRV_FOREACH_BACKWARDS(check, a) - assert_se(streq_ptr(*check, input_table_multiple[i--])); + ASSERT_STREQ(*check, input_table_multiple[i--]); STRV_FOREACH_BACKWARDS(check, (char**) NULL) assert_not_reached(); @@ -657,7 +673,7 @@ TEST(strv_foreach_pair) { "pair_two", "pair_two", "pair_three", "pair_three"); STRV_FOREACH_PAIR(x, y, a) - assert_se(streq(*x, *y)); + ASSERT_STREQ(*x, *y); } static void test_strv_from_stdarg_alloca_one(char **l, const char *first, ...) { @@ -669,7 +685,7 @@ static void test_strv_from_stdarg_alloca_one(char **l, const char *first, ...) { j = strv_from_stdarg_alloca(first); for (i = 0;; i++) { - assert_se(streq_ptr(l[i], j[i])); + ASSERT_STREQ(l[i], j[i]); if (!l[i]) break; @@ -686,29 +702,29 @@ TEST(strv_insert) { _cleanup_strv_free_ char **a = NULL; assert_se(strv_insert(&a, 0, strdup("first")) == 0); - assert_se(streq(a[0], "first")); + ASSERT_STREQ(a[0], "first"); assert_se(!a[1]); assert_se(strv_insert(&a, 0, NULL) == 0); - assert_se(streq(a[0], "first")); + ASSERT_STREQ(a[0], "first"); assert_se(!a[1]); assert_se(strv_insert(&a, 1, strdup("two")) == 0); - assert_se(streq(a[0], "first")); - assert_se(streq(a[1], "two")); + ASSERT_STREQ(a[0], "first"); + ASSERT_STREQ(a[1], "two"); assert_se(!a[2]); assert_se(strv_insert(&a, 4, strdup("tri")) == 0); - assert_se(streq(a[0], "first")); - assert_se(streq(a[1], "two")); - assert_se(streq(a[2], "tri")); + ASSERT_STREQ(a[0], "first"); + ASSERT_STREQ(a[1], "two"); + ASSERT_STREQ(a[2], "tri"); assert_se(!a[3]); assert_se(strv_insert(&a, 1, strdup("duo")) == 0); - assert_se(streq(a[0], "first")); - assert_se(streq(a[1], "duo")); - assert_se(streq(a[2], "two")); - assert_se(streq(a[3], "tri")); + ASSERT_STREQ(a[0], "first"); + ASSERT_STREQ(a[1], "duo"); + ASSERT_STREQ(a[2], "two"); + ASSERT_STREQ(a[3], "tri"); assert_se(!a[4]); } @@ -718,18 +734,18 @@ TEST(strv_push_prepend) { assert_se(a = strv_new("foo", "bar", "three")); assert_se(strv_push_prepend(&a, strdup("first")) >= 0); - assert_se(streq(a[0], "first")); - assert_se(streq(a[1], "foo")); - assert_se(streq(a[2], "bar")); - assert_se(streq(a[3], "three")); + ASSERT_STREQ(a[0], "first"); + ASSERT_STREQ(a[1], "foo"); + ASSERT_STREQ(a[2], "bar"); + ASSERT_STREQ(a[3], "three"); assert_se(!a[4]); assert_se(strv_consume_prepend(&a, strdup("first2")) >= 0); - assert_se(streq(a[0], "first2")); - assert_se(streq(a[1], "first")); - assert_se(streq(a[2], "foo")); - assert_se(streq(a[3], "bar")); - assert_se(streq(a[4], "three")); + ASSERT_STREQ(a[0], "first2"); + ASSERT_STREQ(a[1], "first"); + ASSERT_STREQ(a[2], "foo"); + ASSERT_STREQ(a[3], "bar"); + ASSERT_STREQ(a[4], "three"); assert_se(!a[5]); } @@ -749,10 +765,10 @@ TEST(strv_push_with_size) { assert_se(strv_push_with_size(&a, &n, j) >= 0); assert_se(n == 3); - assert_se(streq_ptr(a[0], "foo")); - assert_se(streq_ptr(a[1], "a")); - assert_se(streq_ptr(a[2], "b")); - assert_se(streq_ptr(a[3], NULL)); + ASSERT_STREQ(a[0], "foo"); + ASSERT_STREQ(a[1], "a"); + ASSERT_STREQ(a[2], "b"); + ASSERT_STREQ(a[3], NULL); assert_se(n = strv_length(a)); } @@ -768,10 +784,10 @@ TEST(strv_push) { assert_se(j = strdup("b")); assert_se(strv_push_pair(&a, i, j) >= 0); - assert_se(streq_ptr(a[0], "foo")); - assert_se(streq_ptr(a[1], "a")); - assert_se(streq_ptr(a[2], "b")); - assert_se(streq_ptr(a[3], NULL)); + ASSERT_STREQ(a[0], "foo"); + ASSERT_STREQ(a[1], "a"); + ASSERT_STREQ(a[2], "b"); + ASSERT_STREQ(a[3], NULL); } TEST(strv_compare) { @@ -833,23 +849,23 @@ TEST(strv_reverse) { b = strv_new("foo"); assert_se(b); strv_reverse(b); - assert_se(streq_ptr(b[0], "foo")); - assert_se(streq_ptr(b[1], NULL)); + ASSERT_STREQ(b[0], "foo"); + ASSERT_STREQ(b[1], NULL); c = strv_new("foo", "bar"); assert_se(c); strv_reverse(c); - assert_se(streq_ptr(c[0], "bar")); - assert_se(streq_ptr(c[1], "foo")); - assert_se(streq_ptr(c[2], NULL)); + ASSERT_STREQ(c[0], "bar"); + ASSERT_STREQ(c[1], "foo"); + ASSERT_STREQ(c[2], NULL); d = strv_new("foo", "bar", "waldo"); assert_se(d); strv_reverse(d); - assert_se(streq_ptr(d[0], "waldo")); - assert_se(streq_ptr(d[1], "bar")); - assert_se(streq_ptr(d[2], "foo")); - assert_se(streq_ptr(d[3], NULL)); + ASSERT_STREQ(d[0], "waldo"); + ASSERT_STREQ(d[1], "bar"); + ASSERT_STREQ(d[2], "foo"); + ASSERT_STREQ(d[3], NULL); } TEST(strv_shell_escape) { @@ -858,10 +874,10 @@ TEST(strv_shell_escape) { v = strv_new("foo:bar", "bar,baz", "wal\\do"); assert_se(v); assert_se(strv_shell_escape(v, ",:")); - assert_se(streq_ptr(v[0], "foo\\:bar")); - assert_se(streq_ptr(v[1], "bar\\,baz")); - assert_se(streq_ptr(v[2], "wal\\\\do")); - assert_se(streq_ptr(v[3], NULL)); + ASSERT_STREQ(v[0], "foo\\:bar"); + ASSERT_STREQ(v[1], "bar\\,baz"); + ASSERT_STREQ(v[2], "wal\\\\do"); + ASSERT_STREQ(v[3], NULL); } static void test_strv_skip_one(char **a, size_t n, char **b) { @@ -895,22 +911,22 @@ TEST(strv_extend_n) { assert_se(strv_extend_n(&v, "waldo", 3) >= 0); assert_se(strv_extend_n(&v, "piep", 2) >= 0); - assert_se(streq(v[0], "foo")); - assert_se(streq(v[1], "bar")); - assert_se(streq(v[2], "waldo")); - assert_se(streq(v[3], "waldo")); - assert_se(streq(v[4], "waldo")); - assert_se(streq(v[5], "piep")); - assert_se(streq(v[6], "piep")); - assert_se(v[7] == NULL); + ASSERT_STREQ(v[0], "foo"); + ASSERT_STREQ(v[1], "bar"); + ASSERT_STREQ(v[2], "waldo"); + ASSERT_STREQ(v[3], "waldo"); + ASSERT_STREQ(v[4], "waldo"); + ASSERT_STREQ(v[5], "piep"); + ASSERT_STREQ(v[6], "piep"); + ASSERT_NULL(v[7]); v = strv_free(v); assert_se(strv_extend_n(&v, "foo", 1) >= 0); assert_se(strv_extend_n(&v, "bar", 0) >= 0); - assert_se(streq(v[0], "foo")); - assert_se(v[1] == NULL); + ASSERT_STREQ(v[0], "foo"); + ASSERT_NULL(v[1]); } TEST(foreach_string) { @@ -923,11 +939,11 @@ TEST(foreach_string) { unsigned i = 0; FOREACH_STRING(x, "foo", "bar", "waldo") - assert_se(streq_ptr(t[i++], x)); + ASSERT_STREQ(t[i++], x); assert_se(i == 3); FOREACH_STRING(x, "zzz") - assert_se(streq(x, "zzz")); + ASSERT_STREQ(x, "zzz"); } TEST(strv_fnmatch) { @@ -950,8 +966,8 @@ TEST(strv_extend_join) { assert_se(strv_extend_assignment(&v, "MISSING", NULL) >= 0); assert_se(strv_length(v) == 2); - assert_se(streq(v[0], "MESSAGE=ABC")); - assert_se(streq(v[1], "ABC=QER")); + ASSERT_STREQ(v[0], "MESSAGE=ABC"); + ASSERT_STREQ(v[1], "ABC=QER"); } TEST(strv_copy_n) { @@ -997,13 +1013,46 @@ TEST(strv_copy_n) { TEST(strv_find_first_field) { char **haystack = STRV_MAKE("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"); - assert_se(strv_find_first_field(NULL, NULL) == NULL); - assert_se(strv_find_first_field(NULL, haystack) == NULL); - assert_se(strv_find_first_field(STRV_MAKE("k", "l", "m", "d", "b"), NULL) == NULL); - assert_se(strv_find_first_field(STRV_MAKE("k", "l", "m", "d", "b"), haystack) == NULL); - assert_se(streq_ptr(strv_find_first_field(STRV_MAKE("k", "l", "m", "d", "a", "c"), haystack), "b")); - assert_se(streq_ptr(strv_find_first_field(STRV_MAKE("k", "l", "m", "d", "c", "a"), haystack), "d")); - assert_se(streq_ptr(strv_find_first_field(STRV_MAKE("i", "k", "l", "m", "d", "c", "a", "b"), haystack), "j")); + ASSERT_NULL(strv_find_first_field(NULL, NULL)); + ASSERT_NULL(strv_find_first_field(NULL, haystack)); + ASSERT_NULL(strv_find_first_field(STRV_MAKE("k", "l", "m", "d", "b"), NULL)); + ASSERT_NULL(strv_find_first_field(STRV_MAKE("k", "l", "m", "d", "b"), haystack)); + ASSERT_STREQ(strv_find_first_field(STRV_MAKE("k", "l", "m", "d", "a", "c"), haystack), "b"); + ASSERT_STREQ(strv_find_first_field(STRV_MAKE("k", "l", "m", "d", "c", "a"), haystack), "d"); + ASSERT_STREQ(strv_find_first_field(STRV_MAKE("i", "k", "l", "m", "d", "c", "a", "b"), haystack), "j"); +} + +TEST(endswith_strv) { + ASSERT_STREQ(endswith_strv("waldo", STRV_MAKE("xxx", "yyy", "ldo", "zzz")), "ldo"); + ASSERT_STREQ(endswith_strv("waldo", STRV_MAKE("xxx", "yyy", "zzz")), NULL); + ASSERT_STREQ(endswith_strv("waldo", STRV_MAKE("waldo")), "waldo"); + ASSERT_STREQ(endswith_strv("waldo", STRV_MAKE("w", "o", "ldo")), "o"); + ASSERT_STREQ(endswith_strv("waldo", STRV_MAKE("knurz", "", "waldo")), ""); +} + +TEST(strv_extend_many) { + _cleanup_strv_free_ char **l = NULL; + + assert_se(strv_extend_many(&l, NULL) >= 0); + assert_se(strv_isempty(l)); + + assert_se(strv_extend_many(&l, NULL, NULL, NULL) >= 0); + assert_se(strv_isempty(l)); + + assert_se(strv_extend_many(&l, "foo") >= 0); + assert_se(strv_equal(l, STRV_MAKE("foo"))); + + assert_se(strv_extend_many(&l, NULL, "bar", NULL) >= 0); + assert_se(strv_equal(l, STRV_MAKE("foo", "bar"))); + + assert_se(strv_extend_many(&l, "waldo", "quux") >= 0); + assert_se(strv_equal(l, STRV_MAKE("foo", "bar", "waldo", "quux"))); + + assert_se(strv_extend_many(&l, "1", "2", "3", "4") >= 0); + assert_se(strv_equal(l, STRV_MAKE("foo", "bar", "waldo", "quux", "1", "2", "3", "4"))); + + assert_se(strv_extend_many(&l, "yes", NULL, "no") >= 0); + assert_se(strv_equal(l, STRV_MAKE("foo", "bar", "waldo", "quux", "1", "2", "3", "4", "yes", "no"))); } DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-strxcpyx.c b/src/test/test-strxcpyx.c index b679522..00f595c 100644 --- a/src/test/test-strxcpyx.c +++ b/src/test/test-strxcpyx.c @@ -24,27 +24,27 @@ TEST(strpcpy) { space_left = strpcpy_full(&s, space_left, "r", &truncated); assert_se(!truncated); assert_se(space_left == 1); - assert_se(streq(target, "12345hey hey heywaldobar")); + ASSERT_STREQ(target, "12345hey hey heywaldobar"); space_left = strpcpy_full(&s, space_left, "", &truncated); assert_se(!truncated); assert_se(space_left == 1); - assert_se(streq(target, "12345hey hey heywaldobar")); + ASSERT_STREQ(target, "12345hey hey heywaldobar"); space_left = strpcpy_full(&s, space_left, "f", &truncated); assert_se(truncated); assert_se(space_left == 0); - assert_se(streq(target, "12345hey hey heywaldobar")); + ASSERT_STREQ(target, "12345hey hey heywaldobar"); space_left = strpcpy_full(&s, space_left, "", &truncated); assert_se(!truncated); assert_se(space_left == 0); - assert_se(streq(target, "12345hey hey heywaldobar")); + ASSERT_STREQ(target, "12345hey hey heywaldobar"); space_left = strpcpy_full(&s, space_left, "foo", &truncated); assert_se(truncated); assert_se(space_left == 0); - assert_se(streq(target, "12345hey hey heywaldobar")); + ASSERT_STREQ(target, "12345hey hey heywaldobar"); } TEST(strpcpyf) { @@ -59,38 +59,38 @@ TEST(strpcpyf) { space_left = strpcpyf_full(&s, space_left, &truncated, "foo%s", "bar"); assert_se(!truncated); assert_se(space_left == 3); - assert_se(streq(target, "space left: 25. foobar")); + ASSERT_STREQ(target, "space left: 25. foobar"); space_left = strpcpyf_full(&s, space_left, &truncated, "%i", 42); assert_se(!truncated); assert_se(space_left == 1); - assert_se(streq(target, "space left: 25. foobar42")); + ASSERT_STREQ(target, "space left: 25. foobar42"); space_left = strpcpyf_full(&s, space_left, &truncated, "%s", ""); assert_se(!truncated); assert_se(space_left == 1); - assert_se(streq(target, "space left: 25. foobar42")); + ASSERT_STREQ(target, "space left: 25. foobar42"); space_left = strpcpyf_full(&s, space_left, &truncated, "%c", 'x'); assert_se(truncated); assert_se(space_left == 0); - assert_se(streq(target, "space left: 25. foobar42")); + ASSERT_STREQ(target, "space left: 25. foobar42"); space_left = strpcpyf_full(&s, space_left, &truncated, "%s", ""); assert_se(!truncated); assert_se(space_left == 0); - assert_se(streq(target, "space left: 25. foobar42")); + ASSERT_STREQ(target, "space left: 25. foobar42"); space_left = strpcpyf_full(&s, space_left, &truncated, "abc%s", "hoge"); assert_se(truncated); assert_se(space_left == 0); - assert_se(streq(target, "space left: 25. foobar42")); + ASSERT_STREQ(target, "space left: 25. foobar42"); /* test overflow */ s = target; space_left = strpcpyf_full(&s, 12, &truncated, "00 left: %i. ", 999); assert_se(truncated); - assert_se(streq(target, "00 left: 99")); + ASSERT_STREQ(target, "00 left: 99"); assert_se(space_left == 0); assert_se(target[12] == '2'); } @@ -107,22 +107,22 @@ TEST(strpcpyl) { space_left = strpcpyl_full(&s, space_left, &truncated, "Banana", NULL); assert_se(!truncated); assert_se(space_left == 1); - assert_se(streq(target, "waldo test waldo. Banana")); + ASSERT_STREQ(target, "waldo test waldo. Banana"); space_left = strpcpyl_full(&s, space_left, &truncated, "", "", "", NULL); assert_se(!truncated); assert_se(space_left == 1); - assert_se(streq(target, "waldo test waldo. Banana")); + ASSERT_STREQ(target, "waldo test waldo. Banana"); space_left = strpcpyl_full(&s, space_left, &truncated, "", "x", "", NULL); assert_se(truncated); assert_se(space_left == 0); - assert_se(streq(target, "waldo test waldo. Banana")); + ASSERT_STREQ(target, "waldo test waldo. Banana"); space_left = strpcpyl_full(&s, space_left, &truncated, "hoge", NULL); assert_se(truncated); assert_se(space_left == 0); - assert_se(streq(target, "waldo test waldo. Banana")); + ASSERT_STREQ(target, "waldo test waldo. Banana"); } TEST(strscpy) { @@ -134,7 +134,7 @@ TEST(strscpy) { space_left = strscpy_full(target, space_left, "12345", &truncated); assert_se(!truncated); - assert_se(streq(target, "12345")); + ASSERT_STREQ(target, "12345"); assert_se(space_left == 20); } @@ -147,7 +147,7 @@ TEST(strscpyl) { space_left = strscpyl_full(target, space_left, &truncated, "12345", "waldo", "waldo", NULL); assert_se(!truncated); - assert_se(streq(target, "12345waldowaldo")); + ASSERT_STREQ(target, "12345waldowaldo"); assert_se(space_left == 10); } @@ -169,7 +169,7 @@ TEST(sd_event_code_migration) { for (i = 0; i < 100; i++) l = strpcpyf(&p, l, "%u ", i); - assert_se(streq(b, c)); + ASSERT_STREQ(b, c); } DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-sysctl-util.c b/src/test/test-sysctl-util.c index 81207f5..e940996 100644 --- a/src/test/test-sysctl-util.c +++ b/src/test/test-sysctl-util.c @@ -34,7 +34,7 @@ TEST(sysctl_normalize) { assert_se(sysctl_normalize(t) == t); log_info("\"%s\" → \"%s\", expected \"%s\"", *s, t, *expected); - assert_se(streq(t, *expected)); + ASSERT_STREQ(t, *expected); } } @@ -66,7 +66,7 @@ TEST(sysctl_read) { assert_se(sysctl_read("kernel/hostname", &s) >= 0); assert_se(uname(&u) >= 0); - assert_se(streq_ptr(s, u.nodename)); + ASSERT_STREQ(s, u.nodename); r = sysctl_write("kernel/hostname", s); assert_se(r >= 0 || ERRNO_IS_PRIVILEGE(r) || r == -EROFS); diff --git a/src/test/test-taint.c b/src/test/test-taint.c new file mode 100644 index 0000000..d9aa79d --- /dev/null +++ b/src/test/test-taint.c @@ -0,0 +1,14 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include "taint.h" +#include "tests.h" + +TEST(taint_string) { + _cleanup_free_ char *a = taint_string(); + assert_se(a); + log_debug("taint string: '%s'", a); + + assert_se(!!strstr(a, "cgroupsv1") == (cg_all_unified() == 0)); +} + +DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-terminal-util.c b/src/test/test-terminal-util.c index a2b7101..dbd7654 100644 --- a/src/test/test-terminal-util.c +++ b/src/test/test-terminal-util.c @@ -155,7 +155,7 @@ TEST(get_ctty) { } /* In almost all cases STDIN will match our controlling TTY. Let's verify that and then compare paths */ - assert_se(fstat(STDIN_FILENO, &st) >= 0); + ASSERT_OK_ERRNO(fstat(STDIN_FILENO, &st)); if (S_ISCHR(st.st_mode) && st.st_rdev == devnr) { _cleanup_free_ char *stdin_name = NULL; @@ -165,4 +165,15 @@ TEST(get_ctty) { log_notice("Not invoked with stdin == ctty, cutting get_ctty() test short"); } +TEST(get_default_background_color) { + double red, green, blue; + int r; + + r = get_default_background_color(&red, &green, &blue); + if (r < 0) + log_notice_errno(r, "Can't get terminal default background color: %m"); + else + log_notice("R=%g G=%g B=%g", red, green, blue); +} + DEFINE_TEST_MAIN(LOG_INFO); diff --git a/src/test/test-time-util.c b/src/test/test-time-util.c index 53bc779..9943923 100644 --- a/src/test/test-time-util.c +++ b/src/test/test-time-util.c @@ -413,7 +413,7 @@ static void test_format_timestamp_impl(usec_t x) { override ? ", ignoring." : ""); if (!override) { assert_se(x / USEC_PER_SEC == y / USEC_PER_SEC); - assert_se(streq(xx, yy)); + ASSERT_STREQ(xx, yy); } } @@ -482,69 +482,69 @@ TEST(format_timestamp_relative_full) { x = now(CLOCK_REALTIME) - (1*USEC_PER_YEAR + 1*USEC_PER_MONTH); assert_se(format_timestamp_relative_full(buf, sizeof(buf), x, CLOCK_REALTIME, true)); log_debug("%s", buf); - assert_se(streq(buf, "1 year 1 month ago")); + ASSERT_STREQ(buf, "1 year 1 month ago"); x = now(CLOCK_MONOTONIC) + (1*USEC_PER_YEAR + 1.5*USEC_PER_MONTH); assert_se(format_timestamp_relative_full(buf, sizeof(buf), x, CLOCK_MONOTONIC, false)); log_debug("%s", buf); - assert_se(streq(buf, "1 year 1 month left")); + ASSERT_STREQ(buf, "1 year 1 month left"); x = now(CLOCK_REALTIME) - (1*USEC_PER_YEAR + 2*USEC_PER_MONTH); assert_se(format_timestamp_relative_full(buf, sizeof(buf), x, CLOCK_REALTIME, true)); log_debug("%s", buf); - assert_se(streq(buf, "1 year 2 months ago")); + ASSERT_STREQ(buf, "1 year 2 months ago"); x = now(CLOCK_REALTIME) - (2*USEC_PER_YEAR + 1*USEC_PER_MONTH); assert_se(format_timestamp_relative_full(buf, sizeof(buf), x, CLOCK_REALTIME, true)); log_debug("%s", buf); - assert_se(streq(buf, "2 years 1 month ago")); + ASSERT_STREQ(buf, "2 years 1 month ago"); x = now(CLOCK_REALTIME) - (2*USEC_PER_YEAR + 2*USEC_PER_MONTH); assert_se(format_timestamp_relative_full(buf, sizeof(buf), x, CLOCK_REALTIME, true)); log_debug("%s", buf); - assert_se(streq(buf, "2 years 2 months ago")); + ASSERT_STREQ(buf, "2 years 2 months ago"); /* Months and days */ x = now(CLOCK_REALTIME) - (1*USEC_PER_MONTH + 1*USEC_PER_DAY); assert_se(format_timestamp_relative_full(buf, sizeof(buf), x, CLOCK_REALTIME, true)); log_debug("%s", buf); - assert_se(streq(buf, "1 month 1 day ago")); + ASSERT_STREQ(buf, "1 month 1 day ago"); x = now(CLOCK_REALTIME) - (1*USEC_PER_MONTH + 2*USEC_PER_DAY); assert_se(format_timestamp_relative_full(buf, sizeof(buf), x, CLOCK_REALTIME, true)); log_debug("%s", buf); - assert_se(streq(buf, "1 month 2 days ago")); + ASSERT_STREQ(buf, "1 month 2 days ago"); x = now(CLOCK_REALTIME) - (2*USEC_PER_MONTH + 1*USEC_PER_DAY); assert_se(format_timestamp_relative_full(buf, sizeof(buf), x, CLOCK_REALTIME, true)); log_debug("%s", buf); - assert_se(streq(buf, "2 months 1 day ago")); + ASSERT_STREQ(buf, "2 months 1 day ago"); x = now(CLOCK_REALTIME) - (2*USEC_PER_MONTH + 2*USEC_PER_DAY); assert_se(format_timestamp_relative_full(buf, sizeof(buf), x, CLOCK_REALTIME, true)); log_debug("%s", buf); - assert_se(streq(buf, "2 months 2 days ago")); + ASSERT_STREQ(buf, "2 months 2 days ago"); /* Weeks and days */ x = now(CLOCK_REALTIME) - (1*USEC_PER_WEEK + 1*USEC_PER_DAY); assert_se(format_timestamp_relative_full(buf, sizeof(buf), x, CLOCK_REALTIME, true)); log_debug("%s", buf); - assert_se(streq(buf, "1 week 1 day ago")); + ASSERT_STREQ(buf, "1 week 1 day ago"); x = now(CLOCK_REALTIME) - (1*USEC_PER_WEEK + 2*USEC_PER_DAY); assert_se(format_timestamp_relative_full(buf, sizeof(buf), x, CLOCK_REALTIME, true)); log_debug("%s", buf); - assert_se(streq(buf, "1 week 2 days ago")); + ASSERT_STREQ(buf, "1 week 2 days ago"); x = now(CLOCK_REALTIME) - (2*USEC_PER_WEEK + 1*USEC_PER_DAY); assert_se(format_timestamp_relative_full(buf, sizeof(buf), x, CLOCK_REALTIME, true)); log_debug("%s", buf); - assert_se(streq(buf, "2 weeks 1 day ago")); + ASSERT_STREQ(buf, "2 weeks 1 day ago"); x = now(CLOCK_REALTIME) - (2*USEC_PER_WEEK + 2*USEC_PER_DAY); assert_se(format_timestamp_relative_full(buf, sizeof(buf), x, CLOCK_REALTIME, true)); log_debug("%s", buf); - assert_se(streq(buf, "2 weeks 2 days ago")); + ASSERT_STREQ(buf, "2 weeks 2 days ago"); } TEST(format_timestamp_relative) { @@ -559,64 +559,64 @@ TEST(format_timestamp_relative) { x = now(CLOCK_REALTIME) - (1*USEC_PER_YEAR + 1*USEC_PER_MONTH); assert_se(format_timestamp_relative(buf, sizeof(buf), x)); log_debug("%s", buf); - assert_se(streq(buf, "1 year 1 month ago")); + ASSERT_STREQ(buf, "1 year 1 month ago"); x = now(CLOCK_REALTIME) - (1*USEC_PER_YEAR + 2*USEC_PER_MONTH); assert_se(format_timestamp_relative(buf, sizeof(buf), x)); log_debug("%s", buf); - assert_se(streq(buf, "1 year 2 months ago")); + ASSERT_STREQ(buf, "1 year 2 months ago"); x = now(CLOCK_REALTIME) - (2*USEC_PER_YEAR + 1*USEC_PER_MONTH); assert_se(format_timestamp_relative(buf, sizeof(buf), x)); log_debug("%s", buf); - assert_se(streq(buf, "2 years 1 month ago")); + ASSERT_STREQ(buf, "2 years 1 month ago"); x = now(CLOCK_REALTIME) - (2*USEC_PER_YEAR + 2*USEC_PER_MONTH); assert_se(format_timestamp_relative(buf, sizeof(buf), x)); log_debug("%s", buf); - assert_se(streq(buf, "2 years 2 months ago")); + ASSERT_STREQ(buf, "2 years 2 months ago"); /* Months and days */ x = now(CLOCK_REALTIME) - (1*USEC_PER_MONTH + 1*USEC_PER_DAY); assert_se(format_timestamp_relative(buf, sizeof(buf), x)); log_debug("%s", buf); - assert_se(streq(buf, "1 month 1 day ago")); + ASSERT_STREQ(buf, "1 month 1 day ago"); x = now(CLOCK_REALTIME) - (1*USEC_PER_MONTH + 2*USEC_PER_DAY); assert_se(format_timestamp_relative(buf, sizeof(buf), x)); log_debug("%s", buf); - assert_se(streq(buf, "1 month 2 days ago")); + ASSERT_STREQ(buf, "1 month 2 days ago"); x = now(CLOCK_REALTIME) - (2*USEC_PER_MONTH + 1*USEC_PER_DAY); assert_se(format_timestamp_relative(buf, sizeof(buf), x)); log_debug("%s", buf); - assert_se(streq(buf, "2 months 1 day ago")); + ASSERT_STREQ(buf, "2 months 1 day ago"); x = now(CLOCK_REALTIME) - (2*USEC_PER_MONTH + 2*USEC_PER_DAY); assert_se(format_timestamp_relative(buf, sizeof(buf), x)); log_debug("%s", buf); - assert_se(streq(buf, "2 months 2 days ago")); + ASSERT_STREQ(buf, "2 months 2 days ago"); /* Weeks and days */ x = now(CLOCK_REALTIME) - (1*USEC_PER_WEEK + 1*USEC_PER_DAY); assert_se(format_timestamp_relative(buf, sizeof(buf), x)); log_debug("%s", buf); - assert_se(streq(buf, "1 week 1 day ago")); + ASSERT_STREQ(buf, "1 week 1 day ago"); x = now(CLOCK_REALTIME) - (1*USEC_PER_WEEK + 2*USEC_PER_DAY); assert_se(format_timestamp_relative(buf, sizeof(buf), x)); log_debug("%s", buf); - assert_se(streq(buf, "1 week 2 days ago")); + ASSERT_STREQ(buf, "1 week 2 days ago"); x = now(CLOCK_REALTIME) - (2*USEC_PER_WEEK + 1*USEC_PER_DAY); assert_se(format_timestamp_relative(buf, sizeof(buf), x)); log_debug("%s", buf); - assert_se(streq(buf, "2 weeks 1 day ago")); + ASSERT_STREQ(buf, "2 weeks 1 day ago"); x = now(CLOCK_REALTIME) - (2*USEC_PER_WEEK + 2*USEC_PER_DAY); assert_se(format_timestamp_relative(buf, sizeof(buf), x)); log_debug("%s", buf); - assert_se(streq(buf, "2 weeks 2 days ago")); + ASSERT_STREQ(buf, "2 weeks 2 days ago"); } static void test_format_timestamp_one(usec_t val, TimestampStyle style, const char *result) { @@ -624,7 +624,7 @@ static void test_format_timestamp_one(usec_t val, TimestampStyle style, const ch const char *t; t = format_timestamp_style(buf, sizeof(buf), val, style); - assert_se(streq_ptr(t, result)); + ASSERT_STREQ(t, result); } TEST(format_timestamp_range) { @@ -1062,15 +1062,15 @@ TEST(in_utc_timezone) { assert_se(setenv("TZ", ":UTC", 1) >= 0); assert_se(in_utc_timezone()); - assert_se(streq(tzname[0], "UTC")); - assert_se(streq(tzname[1], "UTC")); + ASSERT_STREQ(tzname[0], "UTC"); + ASSERT_STREQ(tzname[1], "UTC"); assert_se(timezone == 0); assert_se(daylight == 0); assert_se(setenv("TZ", ":Europe/Berlin", 1) >= 0); assert_se(!in_utc_timezone()); - assert_se(streq(tzname[0], "CET")); - assert_se(streq(tzname[1], "CEST")); + ASSERT_STREQ(tzname[0], "CET"); + ASSERT_STREQ(tzname[1], "CEST"); assert_se(set_unset_env("TZ", tz, true) == 0); tzset(); @@ -1089,9 +1089,9 @@ TEST(map_clock_usec) { assert_se(nowr < USEC_INFINITY - USEC_PER_DAY*7); /* overflow check */ x = nowr + USEC_PER_DAY*7; /* 1 week from now */ y = map_clock_usec(x, CLOCK_REALTIME, CLOCK_MONOTONIC); - assert_se(y > 0 && y < USEC_INFINITY); + assert_se(timestamp_is_set(y)); z = map_clock_usec(y, CLOCK_MONOTONIC, CLOCK_REALTIME); - assert_se(z > 0 && z < USEC_INFINITY); + assert_se(timestamp_is_set(z)); assert_se((z > x ? z - x : x - z) < USEC_PER_HOUR); assert_se(nowr > USEC_PER_DAY * 7); /* underflow check */ @@ -1100,7 +1100,7 @@ TEST(map_clock_usec) { if (y != 0) { /* might underflow if machine is not up long enough for the monotonic clock to be beyond 1w */ assert_se(y < USEC_INFINITY); z = map_clock_usec(y, CLOCK_MONOTONIC, CLOCK_REALTIME); - assert_se(z > 0 && z < USEC_INFINITY); + assert_se(timestamp_is_set(z)); assert_se((z > x ? z - x : x - z) < USEC_PER_HOUR); } } @@ -1114,14 +1114,14 @@ static void test_timezone_offset_change_one(const char *utc, const char *pretty) s = FORMAT_TIMESTAMP_STYLE(x, TIMESTAMP_UTC); assert_se(parse_timestamp(s, &y) >= 0); log_debug("%s -> " USEC_FMT " -> %s -> " USEC_FMT, utc, x, s, y); - assert_se(streq(s, utc)); + ASSERT_STREQ(s, utc); assert_se(x == y); assert_se(parse_timestamp(pretty, &y) >= 0); s = FORMAT_TIMESTAMP_STYLE(y, TIMESTAMP_PRETTY); assert_se(parse_timestamp(s, &z) >= 0); log_debug("%s -> " USEC_FMT " -> %s -> " USEC_FMT, pretty, y, s, z); - assert_se(streq(s, pretty)); + ASSERT_STREQ(s, pretty); assert_se(x == y); assert_se(x == z); } diff --git a/src/test/test-tmpfile-util.c b/src/test/test-tmpfile-util.c index 4859f62..bef503b 100644 --- a/src/test/test-tmpfile-util.c +++ b/src/test/test-tmpfile-util.c @@ -105,7 +105,7 @@ static void test_tempfn_xxxxxx_one(const char *p, const char *extra, const char const char *suffix; assert_se(suffix = startswith(s, expect)); - assert_se(streq(suffix, "XXXXXX")); + ASSERT_STREQ(suffix, "XXXXXX"); } assert_se(ret == r); } @@ -283,7 +283,7 @@ TEST(link_tmpfile) { assert_se(link_tmpfile(fd, tmp, d, /* flags= */ 0) >= 0); assert_se(read_one_line_file(d, &line) >= 0); - assert_se(streq(line, "foobar")); + ASSERT_STREQ(line, "foobar"); fd = safe_close(fd); tmp = mfree(tmp); @@ -298,7 +298,7 @@ TEST(link_tmpfile) { line = mfree(line); assert_se(read_one_line_file(d, &line) >= 0); - assert_se(streq(line, "waumiau")); + ASSERT_STREQ(line, "waumiau"); assert_se(unlink(d) >= 0); } diff --git a/src/test/test-tpm2.c b/src/test/test-tpm2.c index e3c7da8..3b5a375 100644 --- a/src/test/test-tpm2.c +++ b/src/test/test-tpm2.c @@ -74,7 +74,7 @@ TEST(tpm2_util_pbkdf2_hmac_sha256) { }; uint8_t res[SHA256_DIGEST_SIZE]; - for(size_t i = 0; i < sizeof(test_vectors)/sizeof(test_vectors[0]); i++) { + for (size_t i = 0; i < sizeof(test_vectors)/sizeof(test_vectors[0]); i++) { int rc = tpm2_util_pbkdf2_hmac_sha256( test_vectors[i].pass, @@ -199,7 +199,7 @@ static void _test_tpms_sw( tpm2_tpms_pcr_selection_from_mask(mask, hash, &s); _cleanup_free_ char *tpms_str = tpm2_tpms_pcr_selection_to_string(&s); - assert_se(streq(tpms_str, expected_str)); + ASSERT_STREQ(tpms_str, expected_str); assert_se(tpm2_tpms_pcr_selection_weight(&s) == expected_weight); assert_se(tpm2_tpms_pcr_selection_is_empty(&s) == (expected_weight == 0)); @@ -242,7 +242,7 @@ static void _test_tpml_sw( assert_se(l.count == expected_count); _cleanup_free_ char *tpml_str = tpm2_tpml_pcr_selection_to_string(&l); - assert_se(streq(tpml_str, expected_str)); + ASSERT_STREQ(tpml_str, expected_str); assert_se(tpm2_tpml_pcr_selection_weight(&l) == expected_weight); assert_se(tpm2_tpml_pcr_selection_is_empty(&l) == (expected_weight == 0)); @@ -678,7 +678,7 @@ TEST(parse_pcr_argument) { assert_se(tpm2_parse_pcr_argument("1,2=123456abc", &v, &n_v) < 0); assert_se(tpm2_parse_pcr_argument("1,2:invalid", &v, &n_v) < 0); assert_se(tpm2_parse_pcr_argument("1:sha1=invalid", &v, &n_v) < 0); - assert_se(v == NULL); + ASSERT_NULL(v); assert_se(n_v == 0); check_parse_pcr_argument_to_mask("", 0x0); @@ -1139,42 +1139,38 @@ static void calculate_seal_and_unseal( assert_se(asprintf(&secret_string, "The classified documents are in room %x", parent_index) > 0); size_t secret_size = strlen(secret_string) + 1; - _cleanup_free_ void *blob = NULL; - size_t blob_size = 0; - _cleanup_free_ void *serialized_parent = NULL; - size_t serialized_parent_size; + _cleanup_(iovec_done) struct iovec blob = {}, serialized_parent = {}; assert_se(tpm2_calculate_seal( parent_index, parent_public, /* attributes= */ NULL, - secret_string, secret_size, + &IOVEC_MAKE(secret_string, secret_size), /* policy= */ NULL, /* pin= */ NULL, - /* ret_secret= */ NULL, /* ret_secret_size= */ 0, - &blob, &blob_size, - &serialized_parent, &serialized_parent_size) >= 0); + /* ret_secret= */ NULL, + &blob, + &serialized_parent) >= 0); - _cleanup_free_ void *unsealed_secret = NULL; - size_t unsealed_secret_size; + _cleanup_(iovec_done) struct iovec unsealed_secret = {}; assert_se(tpm2_unseal( c, /* hash_pcr_mask= */ 0, /* pcr_bank= */ 0, - /* pubkey= */ NULL, /* pubkey_size= */ 0, + /* pubkey= */ NULL, /* pubkey_pcr_mask= */ 0, /* signature= */ NULL, /* pin= */ NULL, /* pcrlock_policy= */ NULL, /* primary_alg= */ 0, - blob, blob_size, - /* known_policy_hash= */ NULL, /* known_policy_hash_size= */ 0, - serialized_parent, serialized_parent_size, - &unsealed_secret, &unsealed_secret_size) >= 0); + &blob, + /* known_policy_hash= */ NULL, + &serialized_parent, + &unsealed_secret) >= 0); - assert_se(memcmp_nn(secret_string, secret_size, unsealed_secret, unsealed_secret_size) == 0); + assert_se(memcmp_nn(secret_string, secret_size, unsealed_secret.iov_base, unsealed_secret.iov_len) == 0); - char unsealed_string[unsealed_secret_size]; - assert_se(snprintf(unsealed_string, unsealed_secret_size, "%s", (char*) unsealed_secret) == (int) unsealed_secret_size - 1); + char unsealed_string[unsealed_secret.iov_len]; + assert_se(snprintf(unsealed_string, unsealed_secret.iov_len, "%s", (char*) unsealed_secret.iov_base) == (int) unsealed_secret.iov_len - 1); log_debug("Unsealed secret is: %s", unsealed_string); } @@ -1226,34 +1222,33 @@ static void check_seal_unseal_for_handle(Tpm2Context *c, TPM2_HANDLE handle) { log_debug("Check seal/unseal for handle 0x%" PRIx32, handle); - _cleanup_free_ void *secret = NULL, *blob = NULL, *srk = NULL, *unsealed_secret = NULL; - size_t secret_size, blob_size, srk_size, unsealed_secret_size; + _cleanup_(iovec_done) struct iovec secret = {}, blob = {}, srk = {}, unsealed_secret = {}; assert_se(tpm2_seal( c, handle, &policy, /* pin= */ NULL, - &secret, &secret_size, - &blob, &blob_size, + &secret, + &blob, /* ret_primary_alg= */ NULL, - &srk, &srk_size) >= 0); + &srk) >= 0); assert_se(tpm2_unseal( c, /* hash_pcr_mask= */ 0, /* pcr_bank= */ 0, - /* pubkey= */ NULL, /* pubkey_size= */ 0, + /* pubkey= */ NULL, /* pubkey_pcr_mask= */ 0, /* signature= */ NULL, /* pin= */ NULL, /* pcrlock_policy= */ NULL, /* primary_alg= */ 0, - blob, blob_size, - /* policy_hash= */ NULL, /* policy_hash_size= */ 0, - srk, srk_size, - &unsealed_secret, &unsealed_secret_size) >= 0); + &blob, + /* policy_hash= */ NULL, + &srk, + &unsealed_secret) >= 0); - assert_se(memcmp_nn(secret, secret_size, unsealed_secret, unsealed_secret_size) == 0); + assert_se(iovec_memcmp(&secret, &unsealed_secret) == 0); } static void check_seal_unseal(Tpm2Context *c) { @@ -1271,7 +1266,7 @@ static void check_seal_unseal(Tpm2Context *c) { check_seal_unseal_for_handle(c, 0); check_seal_unseal_for_handle(c, TPM2_SRK_HANDLE); - FOREACH_ARRAY(template, test_templates, ELEMENTSOF(test_templates)) { + FOREACH_ELEMENT(template, test_templates) { TPM2B_PUBLIC public = { .publicArea = **template, .size = sizeof(**template), diff --git a/src/test/test-udev-util.c b/src/test/test-udev-util.c index cb80c69..07f4e01 100644 --- a/src/test/test-udev-util.c +++ b/src/test/test-udev-util.c @@ -16,7 +16,7 @@ static void test_udev_replace_whitespace_one_len(const char *str, size_t len, co assert_se(result); r = udev_replace_whitespace(str, result, len); assert_se((size_t) r == strlen(expected)); - assert_se(streq(result, expected)); + ASSERT_STREQ(result, expected); } static void test_udev_replace_whitespace_one(const char *str, const char *expected) { diff --git a/src/test/test-uid-alloc-range.c b/src/test/test-uid-classification.c index cd06463..9c7500a 100644 --- a/src/test/test-uid-alloc-range.c +++ b/src/test/test-uid-classification.c @@ -9,7 +9,7 @@ #include "fs-util.h" #include "tests.h" #include "tmpfile-util.h" -#include "uid-alloc-range.h" +#include "uid-classification.h" static void test_read_login_defs_one(const char *path) { log_info("/* %s(\"%s\") */", __func__, path ?: "<custom>"); diff --git a/src/test/test-uid-range.c b/src/test/test-uid-range.c index 186f6ee..6041d08 100644 --- a/src/test/test-uid-range.c +++ b/src/test/test-uid-range.c @@ -14,16 +14,24 @@ #include "virt.h" TEST(uid_range) { - _cleanup_(uid_range_freep) UidRange *p = NULL; + _cleanup_(uid_range_freep) UIDRange *p = NULL; uid_t search; assert_se(uid_range_covers(p, 0, 0)); assert_se(!uid_range_covers(p, 0, 1)); assert_se(!uid_range_covers(p, 100, UINT32_MAX)); + assert_se(!uid_range_covers(p, UINT32_MAX, 1)); + assert_se(!uid_range_covers(p, UINT32_MAX - 10, 11)); + + assert_se(uid_range_entries(p) == 0); + assert_se(uid_range_size(p) == 0); + assert_se(uid_range_is_empty(p)); assert_se(uid_range_add_str(&p, "500-999") >= 0); assert_se(p); - assert_se(p->n_entries == 1); + assert_se(uid_range_entries(p) == 1); + assert_se(uid_range_size(p) == 500); + assert_se(!uid_range_is_empty(p)); assert_se(p->entries[0].start == 500); assert_se(p->entries[0].nr == 500); @@ -54,19 +62,23 @@ TEST(uid_range) { assert_se(uid_range_next_lower(p, &search) == -EBUSY); assert_se(uid_range_add_str(&p, "1000") >= 0); - assert_se(p->n_entries == 1); + assert_se(uid_range_entries(p) == 1); assert_se(p->entries[0].start == 500); assert_se(p->entries[0].nr == 501); assert_se(uid_range_add_str(&p, "30-40") >= 0); - assert_se(p->n_entries == 2); + assert_se(uid_range_entries(p) == 2); + assert_se(uid_range_size(p) == 500 + 1 + 11); + assert_se(!uid_range_is_empty(p)); assert_se(p->entries[0].start == 30); assert_se(p->entries[0].nr == 11); assert_se(p->entries[1].start == 500); assert_se(p->entries[1].nr == 501); assert_se(uid_range_add_str(&p, "60-70") >= 0); - assert_se(p->n_entries == 3); + assert_se(uid_range_entries(p) == 3); + assert_se(uid_range_size(p) == 500 + 1 + 11 + 11); + assert_se(!uid_range_is_empty(p)); assert_se(p->entries[0].start == 30); assert_se(p->entries[0].nr == 11); assert_se(p->entries[1].start == 60); @@ -75,31 +87,44 @@ TEST(uid_range) { assert_se(p->entries[2].nr == 501); assert_se(uid_range_add_str(&p, "20-2000") >= 0); - assert_se(p->n_entries == 1); + assert_se(uid_range_entries(p) == 1); + assert_se(uid_range_size(p) == 1981); assert_se(p->entries[0].start == 20); assert_se(p->entries[0].nr == 1981); assert_se(uid_range_add_str(&p, "2002") >= 0); - assert_se(p->n_entries == 2); + assert_se(uid_range_entries(p) == 2); + assert_se(uid_range_size(p) == 1982); assert_se(p->entries[0].start == 20); assert_se(p->entries[0].nr == 1981); assert_se(p->entries[1].start == 2002); assert_se(p->entries[1].nr == 1); + _cleanup_(uid_range_freep) UIDRange *q = NULL; + assert_se(!uid_range_equal(p, q)); + assert_se(uid_range_add_str(&q, "20-2000") >= 0); + assert_se(!uid_range_equal(p, q)); + assert_se(uid_range_add_str(&q, "2002") >= 0); + assert_se(uid_range_equal(p, q)); + assert_se(uid_range_add_str(&p, "2001") >= 0); - assert_se(p->n_entries == 1); + assert_se(uid_range_entries(p) == 1); + assert_se(uid_range_size(p) == 1983); assert_se(p->entries[0].start == 20); assert_se(p->entries[0].nr == 1983); + + assert_se(uid_range_add_str(&q, "2001") >= 0); + assert_se(uid_range_equal(p, q)); } TEST(load_userns) { - _cleanup_(uid_range_freep) UidRange *p = NULL; + _cleanup_(uid_range_freep) UIDRange *p = NULL; _cleanup_(unlink_and_freep) char *fn = NULL; _cleanup_fclose_ FILE *f = NULL; int r; - r = uid_range_load_userns(&p, NULL); - if (r < 0 && ERRNO_IS_NOT_SUPPORTED(r)) + r = uid_range_load_userns(NULL, UID_RANGE_USERNS_INSIDE, &p); + if (ERRNO_IS_NEG_NOT_SUPPORTED(r)) return; assert_se(r >= 0); @@ -121,7 +146,7 @@ TEST(load_userns) { p = uid_range_free(p); - assert_se(uid_range_load_userns(&p, fn) >= 0); + assert_se(uid_range_load_userns(fn, UID_RANGE_USERNS_INSIDE, &p) >= 0); assert_se(uid_range_contains(p, 0)); assert_se(uid_range_contains(p, 19)); @@ -134,7 +159,7 @@ TEST(load_userns) { } TEST(uid_range_coalesce) { - _cleanup_(uid_range_freep) UidRange *p = NULL; + _cleanup_(uid_range_freep) UIDRange *p = NULL; for (size_t i = 0; i < 10; i++) { assert_se(uid_range_add_internal(&p, i * 10, 10, /* coalesce = */ false) >= 0); diff --git a/src/test/test-unit-file.c b/src/test/test-unit-file.c index 9f8787b..63e5000 100644 --- a/src/test/test-unit-file.c +++ b/src/test/test-unit-file.c @@ -26,7 +26,7 @@ TEST(unit_validate_alias_symlink_and_warn) { } TEST(unit_file_build_name_map) { - _cleanup_(lookup_paths_free) LookupPaths lp = {}; + _cleanup_(lookup_paths_done) LookupPaths lp = {}; _cleanup_hashmap_free_ Hashmap *unit_ids = NULL; _cleanup_hashmap_free_ Hashmap *unit_names = NULL; const char *k, *dst; @@ -88,18 +88,18 @@ TEST(unit_file_build_name_map) { TEST(runlevel_to_target) { in_initrd_force(false); - assert_se(streq_ptr(runlevel_to_target(NULL), NULL)); - assert_se(streq_ptr(runlevel_to_target("unknown-runlevel"), NULL)); - assert_se(streq_ptr(runlevel_to_target("rd.unknown-runlevel"), NULL)); - assert_se(streq_ptr(runlevel_to_target("3"), SPECIAL_MULTI_USER_TARGET)); - assert_se(streq_ptr(runlevel_to_target("rd.rescue"), NULL)); + ASSERT_STREQ(runlevel_to_target(NULL), NULL); + ASSERT_STREQ(runlevel_to_target("unknown-runlevel"), NULL); + ASSERT_STREQ(runlevel_to_target("rd.unknown-runlevel"), NULL); + ASSERT_STREQ(runlevel_to_target("3"), SPECIAL_MULTI_USER_TARGET); + ASSERT_STREQ(runlevel_to_target("rd.rescue"), NULL); in_initrd_force(true); - assert_se(streq_ptr(runlevel_to_target(NULL), NULL)); - assert_se(streq_ptr(runlevel_to_target("unknown-runlevel"), NULL)); - assert_se(streq_ptr(runlevel_to_target("rd.unknown-runlevel"), NULL)); - assert_se(streq_ptr(runlevel_to_target("3"), NULL)); - assert_se(streq_ptr(runlevel_to_target("rd.rescue"), SPECIAL_RESCUE_TARGET)); + ASSERT_STREQ(runlevel_to_target(NULL), NULL); + ASSERT_STREQ(runlevel_to_target("unknown-runlevel"), NULL); + ASSERT_STREQ(runlevel_to_target("rd.unknown-runlevel"), NULL); + ASSERT_STREQ(runlevel_to_target("3"), NULL); + ASSERT_STREQ(runlevel_to_target("rd.rescue"), SPECIAL_RESCUE_TARGET); } static int intro(void) { diff --git a/src/test/test-unit-name.c b/src/test/test-unit-name.c index 8e9332c..b482104 100644 --- a/src/test/test-unit-name.c +++ b/src/test/test-unit-name.c @@ -92,7 +92,7 @@ static void test_unit_name_replace_instance_one(const char *pattern, const char _cleanup_free_ char *t = NULL; assert_se(unit_name_replace_instance(pattern, repl, &t) == ret); puts(strna(t)); - assert_se(streq_ptr(t, expected)); + ASSERT_STREQ(t, expected); } TEST(unit_name_replace_instance) { @@ -112,7 +112,7 @@ static void test_unit_name_from_path_one(const char *path, const char *suffix, c assert_se(unit_name_from_path(path, suffix, &t) == ret); puts(strna(t)); - assert_se(streq_ptr(t, expected)); + ASSERT_STREQ(t, expected); if (t) { _cleanup_free_ char *k = NULL; @@ -159,7 +159,7 @@ static void test_unit_name_from_path_instance_one(const char *pattern, const cha assert_se(unit_name_from_path_instance(pattern, path, suffix, &t) == ret); puts(strna(t)); - assert_se(streq_ptr(t, expected)); + ASSERT_STREQ(t, expected); if (t) { _cleanup_free_ char *k = NULL, *v = NULL; @@ -185,7 +185,7 @@ static void test_unit_name_to_path_one(const char *unit, const char *path, int r _cleanup_free_ char *p = NULL; assert_se(unit_name_to_path(unit, &p) == ret); - assert_se(streq_ptr(path, p)); + ASSERT_STREQ(path, p); } TEST(unit_name_to_path) { @@ -208,7 +208,7 @@ static void test_unit_name_mangle_one(bool allow_globs, const char *pattern, con assert_se(r == ret); puts(strna(t)); - assert_se(streq_ptr(t, expect)); + ASSERT_STREQ(t, expect); if (t) { _cleanup_free_ char *k = NULL; @@ -217,7 +217,7 @@ static void test_unit_name_mangle_one(bool allow_globs, const char *pattern, con (allow_globs && string_is_glob(t))); assert_se(unit_name_mangle(t, (allow_globs * UNIT_NAME_MANGLE_GLOB) | UNIT_NAME_MANGLE_WARN, &k) == 0); - assert_se(streq_ptr(t, k)); + ASSERT_STREQ(t, k); } } @@ -246,7 +246,7 @@ static void test_unit_name_mangle_with_suffix_one(const char *arg, int expected, log_debug("%s: %s -> %d, %s", __func__, arg, r, strnull(s)); assert_se(r == expected); - assert_se(streq_ptr(s, expected_name)); + ASSERT_STREQ(s, expected_name); } TEST(unit_name_mangle_with_suffix) { @@ -499,11 +499,11 @@ TEST(unit_name_change_suffix) { char *t; assert_se(unit_name_change_suffix("foo.mount", ".service", &t) == 0); - assert_se(streq(t, "foo.service")); + ASSERT_STREQ(t, "foo.service"); free(t); assert_se(unit_name_change_suffix("foo@stuff.service", ".socket", &t) == 0); - assert_se(streq(t, "foo@stuff.socket")); + ASSERT_STREQ(t, "foo@stuff.socket"); free(t); } @@ -511,15 +511,15 @@ TEST(unit_name_build) { char *t; assert_se(unit_name_build("foo", "bar", ".service", &t) == 0); - assert_se(streq(t, "foo@bar.service")); + ASSERT_STREQ(t, "foo@bar.service"); free(t); assert_se(unit_name_build("fo0-stUff_b", "bar", ".mount", &t) == 0); - assert_se(streq(t, "fo0-stUff_b@bar.mount")); + ASSERT_STREQ(t, "fo0-stUff_b@bar.mount"); free(t); assert_se(unit_name_build("foo", NULL, ".service", &t) == 0); - assert_se(streq(t, "foo.service")); + ASSERT_STREQ(t, "foo.service"); free(t); } @@ -563,7 +563,7 @@ TEST(build_subslice) { free(b); assert_se(slice_build_subslice(a, "foobar", &b) >= 0); free(a); - assert_se(streq(b, "foo-bar-barfoo-foobar.slice")); + ASSERT_STREQ(b, "foo-bar-barfoo-foobar.slice"); free(b); assert_se(slice_build_subslice("foo.service", "bar", &a) < 0); @@ -574,7 +574,7 @@ static void test_build_parent_slice_one(const char *name, const char *expect, in _cleanup_free_ char *s = NULL; assert_se(slice_build_parent_slice(name, &s) == ret); - assert_se(streq_ptr(s, expect)); + ASSERT_STREQ(s, expect); } TEST(build_parent_slice) { @@ -602,17 +602,17 @@ TEST(unit_name_to_instance) { r = unit_name_to_instance("foo@bar.service", &instance); assert_se(r == UNIT_NAME_INSTANCE); - assert_se(streq(instance, "bar")); + ASSERT_STREQ(instance, "bar"); free(instance); r = unit_name_to_instance("foo@.service", &instance); assert_se(r == UNIT_NAME_TEMPLATE); - assert_se(streq(instance, "")); + ASSERT_STREQ(instance, ""); free(instance); r = unit_name_to_instance("fo0-stUff_b@b.service", &instance); assert_se(r == UNIT_NAME_INSTANCE); - assert_se(streq(instance, "b")); + ASSERT_STREQ(instance, "b"); free(instance); r = unit_name_to_instance("foo.service", &instance); @@ -633,7 +633,7 @@ TEST(unit_name_escape) { r = unit_name_escape("ab+-c.a/bc@foo.service"); assert_se(r); - assert_se(streq(r, "ab\\x2b\\x2dc.a-bc\\x40foo.service")); + ASSERT_STREQ(r, "ab\\x2b\\x2dc.a-bc\\x40foo.service"); } static void test_u_n_t_one(const char *name, const char *expected, int ret) { @@ -641,7 +641,7 @@ static void test_u_n_t_one(const char *name, const char *expected, int ret) { assert_se(unit_name_template(name, &f) == ret); printf("got: %s, expected: %s\n", strna(f), strna(expected)); - assert_se(streq_ptr(f, expected)); + ASSERT_STREQ(f, expected); } TEST(unit_name_template) { @@ -653,7 +653,7 @@ static void test_unit_name_path_unescape_one(const char *name, const char *path, _cleanup_free_ char *p = NULL; assert_se(unit_name_path_unescape(name, &p) == ret); - assert_se(streq_ptr(path, p)); + ASSERT_STREQ(path, p); } TEST(unit_name_path_unescape) { @@ -675,7 +675,7 @@ static void test_unit_name_to_prefix_one(const char *input, int ret, const char _cleanup_free_ char *k = NULL; assert_se(unit_name_to_prefix(input, &k) == ret); - assert_se(streq_ptr(k, output)); + ASSERT_STREQ(k, output); } TEST(unit_name_to_prefix) { @@ -695,7 +695,7 @@ static void test_unit_name_from_dbus_path_one(const char *input, int ret, const _cleanup_free_ char *k = NULL; assert_se(unit_name_from_dbus_path(input, &k) == ret); - assert_se(streq_ptr(k, output)); + ASSERT_STREQ(k, output); } TEST(unit_name_from_dbus_path) { diff --git a/src/test/test-user-util.c b/src/test/test-user-util.c index db76cde..e21d8da 100644 --- a/src/test/test-user-util.c +++ b/src/test/test-user-util.c @@ -21,7 +21,7 @@ static void test_uid_to_name_one(uid_t uid, const char *name) { log_info("(skipping detailed tests because nobody is not synthesized)"); return; } - assert_se(streq_ptr(t, name)); + ASSERT_STREQ(t, name); } TEST(uid_to_name) { @@ -41,7 +41,7 @@ static void test_gid_to_name_one(gid_t gid, const char *name) { log_info("(skipping detailed tests because nobody is not synthesized)"); return; } - assert_se(streq_ptr(t, name)); + ASSERT_STREQ(t, name); } TEST(gid_to_name) { @@ -137,8 +137,8 @@ TEST(parse_uid) { } TEST(uid_ptr) { - assert_se(UID_TO_PTR(0) != NULL); - assert_se(UID_TO_PTR(1000) != NULL); + ASSERT_NOT_NULL(UID_TO_PTR(0)); + ASSERT_NOT_NULL(UID_TO_PTR(1000)); assert_se(PTR_TO_UID(UID_TO_PTR(0)) == 0); assert_se(PTR_TO_UID(UID_TO_PTR(1000)) == 1000); @@ -338,7 +338,7 @@ static void test_get_user_creds_one(const char *id, const char *name, uid_t uid, return; } assert_se(r == 0); - assert_se(streq_ptr(id, name)); + ASSERT_STREQ(id, name); assert_se(ruid == uid); assert_se(rgid == gid); assert_se(path_equal(rhome, home)); @@ -364,7 +364,7 @@ static void test_get_group_creds_one(const char *id, const char *name, gid_t gid return; } assert_se(r == 0); - assert_se(streq_ptr(id, name)); + ASSERT_STREQ(id, name); assert_se(rgid == gid); } @@ -466,7 +466,7 @@ static void test_mangle_gecos_one(const char *input, const char *expected) { _cleanup_free_ char *p = NULL; assert_se(p = mangle_gecos(input)); - assert_se(streq(p, expected)); + ASSERT_STREQ(p, expected); assert_se(valid_gecos(p)); } diff --git a/src/test/test-utf8.c b/src/test/test-utf8.c index a0d7dc1..d60cf00 100644 --- a/src/test/test-utf8.c +++ b/src/test/test-utf8.c @@ -62,7 +62,7 @@ static void test_utf8_to_ascii_one(const char *s, int r_expected, const char *ex r = utf8_to_ascii(s, '*', &ans); log_debug("\"%s\" → %d/\"%s\" (expected %d/\"%s\")", s, r, strnull(ans), r_expected, strnull(expected)); assert_se(r == r_expected); - assert_se(streq_ptr(ans, expected)); + ASSERT_STREQ(ans, expected); } TEST(utf8_to_ascii) { @@ -223,7 +223,7 @@ TEST(utf8_to_utf16) { b = utf16_to_utf8(a, SIZE_MAX); assert_se(b); - assert_se(streq(p, b)); + ASSERT_STREQ(p, b); } } diff --git a/src/test/test-varlink-idl.c b/src/test/test-varlink-idl.c index cbdb9c6..86dbcc9 100644 --- a/src/test/test-varlink-idl.c +++ b/src/test/test-varlink-idl.c @@ -8,11 +8,17 @@ #include "varlink.h" #include "varlink-idl.h" #include "varlink-io.systemd.h" +#include "varlink-io.systemd.BootControl.h" +#include "varlink-io.systemd.Credentials.h" #include "varlink-io.systemd.Journal.h" #include "varlink-io.systemd.ManagedOOM.h" +#include "varlink-io.systemd.MountFileSystem.h" +#include "varlink-io.systemd.NamespaceResource.h" +#include "varlink-io.systemd.Network.h" #include "varlink-io.systemd.PCRExtend.h" -#include "varlink-io.systemd.Resolve.Monitor.h" +#include "varlink-io.systemd.PCRLock.h" #include "varlink-io.systemd.Resolve.h" +#include "varlink-io.systemd.Resolve.Monitor.h" #include "varlink-io.systemd.UserDatabase.h" #include "varlink-io.systemd.oom.h" #include "varlink-io.systemd.service.h" @@ -117,7 +123,7 @@ static void test_parse_format_one(const VarlinkInterface *iface) { assert_se(varlink_idl_parse(text, NULL, NULL, &parsed) >= 0); assert_se(varlink_idl_consistent(parsed, LOG_ERR) >= 0); assert_se(varlink_idl_format(parsed, &text2) >= 0); - assert_se(streq(text, text2)); + ASSERT_STREQ(text, text2); } TEST(parse_format) { @@ -125,6 +131,8 @@ TEST(parse_format) { print_separator(); test_parse_format_one(&vl_interface_io_systemd_UserDatabase); print_separator(); + test_parse_format_one(&vl_interface_io_systemd_NamespaceResource); + print_separator(); test_parse_format_one(&vl_interface_io_systemd_Journal); print_separator(); test_parse_format_one(&vl_interface_io_systemd_Resolve); @@ -133,16 +141,26 @@ TEST(parse_format) { print_separator(); test_parse_format_one(&vl_interface_io_systemd_ManagedOOM); print_separator(); + test_parse_format_one(&vl_interface_io_systemd_MountFileSystem); + print_separator(); + test_parse_format_one(&vl_interface_io_systemd_Network); + print_separator(); test_parse_format_one(&vl_interface_io_systemd_oom); print_separator(); test_parse_format_one(&vl_interface_io_systemd); print_separator(); test_parse_format_one(&vl_interface_io_systemd_PCRExtend); print_separator(); + test_parse_format_one(&vl_interface_io_systemd_PCRLock); + print_separator(); test_parse_format_one(&vl_interface_io_systemd_service); print_separator(); test_parse_format_one(&vl_interface_io_systemd_sysext); print_separator(); + test_parse_format_one(&vl_interface_io_systemd_Credentials); + print_separator(); + test_parse_format_one(&vl_interface_io_systemd_BootControl); + print_separator(); test_parse_format_one(&vl_interface_xyz_test); } @@ -338,7 +356,7 @@ TEST(validate_method_call) { JsonVariant *reply = NULL; const char *error_id = NULL; - assert_se(varlink_callb(v, "xyz.TestMethod", &reply, &error_id, NULL, + assert_se(varlink_callb(v, "xyz.TestMethod", &reply, &error_id, JSON_BUILD_OBJECT( JSON_BUILD_PAIR_UNSIGNED("foo", 8), JSON_BUILD_PAIR_UNSIGNED("bar", 9))) >= 0); @@ -355,7 +373,7 @@ TEST(validate_method_call) { json_variant_dump(expected_reply, JSON_FORMAT_PRETTY_AUTO|JSON_FORMAT_COLOR_AUTO, NULL, NULL); assert_se(json_variant_equal(reply, expected_reply)); - assert_se(varlink_callb(v, "xyz.TestMethod", &reply, &error_id, NULL, + assert_se(varlink_callb(v, "xyz.TestMethod", &reply, &error_id, JSON_BUILD_OBJECT( JSON_BUILD_PAIR_UNSIGNED("foo", 9), JSON_BUILD_PAIR_UNSIGNED("bar", 8), @@ -364,18 +382,18 @@ TEST(validate_method_call) { assert_se(!error_id); assert_se(json_variant_equal(reply, expected_reply)); - assert_se(varlink_callb(v, "xyz.TestMethod", &reply, &error_id, NULL, + assert_se(varlink_callb(v, "xyz.TestMethod", &reply, &error_id, JSON_BUILD_OBJECT( JSON_BUILD_PAIR_UNSIGNED("foo", 8), JSON_BUILD_PAIR_UNSIGNED("bar", 9), JSON_BUILD_PAIR_STRING("zzz", "pfft"))) >= 0); - assert_se(streq_ptr(error_id, VARLINK_ERROR_INVALID_PARAMETER)); + ASSERT_STREQ(error_id, VARLINK_ERROR_INVALID_PARAMETER); - assert_se(varlink_callb(v, "xyz.TestMethod", &reply, &error_id, NULL, + assert_se(varlink_callb(v, "xyz.TestMethod", &reply, &error_id, JSON_BUILD_OBJECT( - JSON_BUILD_PAIR_STRING("foo", "wuff"), + JSON_BUILD_PAIR_BOOLEAN("foo", true), JSON_BUILD_PAIR_UNSIGNED("bar", 9))) >= 0); - assert_se(streq_ptr(error_id, VARLINK_ERROR_INVALID_PARAMETER)); + ASSERT_STREQ(error_id, VARLINK_ERROR_INVALID_PARAMETER); assert_se(varlink_send(v, "xyz.Done", NULL) >= 0); assert_se(varlink_flush(v) >= 0); diff --git a/src/test/test-varlink.c b/src/test/test-varlink.c index 2617ed0..8ad5757 100644 --- a/src/test/test-varlink.c +++ b/src/test/test-varlink.c @@ -107,7 +107,7 @@ static int method_passfd(Varlink *link, JsonVariant *parameters, VarlinkMethodFl if (!a) return varlink_error(link, "io.test.BadParameters", NULL); - assert_se(streq_ptr(json_variant_string(a), "whoop")); + ASSERT_STREQ(json_variant_string(a), "whoop"); int xx = varlink_peek_fd(link, 0), yy = varlink_peek_fd(link, 1), @@ -123,8 +123,8 @@ static int method_passfd(Varlink *link, JsonVariant *parameters, VarlinkMethodFl test_fd(yy, "bar", 3); test_fd(zz, "quux", 4); - _cleanup_close_ int vv = acquire_data_fd("miau", 4, 0); - _cleanup_close_ int ww = acquire_data_fd("wuff", 4, 0); + _cleanup_close_ int vv = acquire_data_fd("miau"); + _cleanup_close_ int ww = acquire_data_fd("wuff"); assert_se(vv >= 0); assert_se(ww >= 0); @@ -183,7 +183,7 @@ static int overload_reply(Varlink *link, JsonVariant *parameters, const char *er * be talking to an overloaded server */ log_debug("Over reply triggered with error: %s", strna(error_id)); - assert_se(streq(error_id, VARLINK_ERROR_DISCONNECTED)); + ASSERT_STREQ(error_id, VARLINK_ERROR_DISCONNECTED); sd_event_exit(varlink_get_event(link), 0); return 0; @@ -238,10 +238,10 @@ static void flood_test(const char *address) { static void *thread(void *arg) { _cleanup_(varlink_flush_close_unrefp) Varlink *c = NULL; - _cleanup_(json_variant_unrefp) JsonVariant *i = NULL, *j = NULL; - JsonVariant *o = NULL, *k = NULL; + _cleanup_(json_variant_unrefp) JsonVariant *i = NULL; + _cleanup_(json_variant_unrefp) JsonVariant *wrong = NULL; + JsonVariant *o = NULL, *k = NULL, *j = NULL; const char *error_id; - VarlinkReplyFlags flags = 0; const char *e; int x = 0; @@ -253,10 +253,16 @@ static void *thread(void *arg) { assert_se(varlink_set_allow_fd_passing_input(c, true) >= 0); assert_se(varlink_set_allow_fd_passing_output(c, true) >= 0); - assert_se(varlink_collect(c, "io.test.DoSomethingMore", i, &j, &error_id, &flags) >= 0); + /* Test that client is able to perform two sequential varlink_collect calls if first resulted in an error */ + assert_se(json_build(&wrong, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("a", JSON_BUILD_INTEGER(88)), + JSON_BUILD_PAIR("c", JSON_BUILD_INTEGER(99)))) >= 0); + assert_se(varlink_collect(c, "io.test.DoSomethingMore", wrong, &j, &error_id) >= 0); + assert_se(strcmp_ptr(error_id, "org.varlink.service.InvalidParameter") == 0); + + + assert_se(varlink_collect(c, "io.test.DoSomethingMore", i, &j, &error_id) >= 0); assert_se(!error_id); - assert_se(!flags); assert_se(json_variant_is_array(j) && !json_variant_is_blank_array(j)); JSON_VARIANT_ARRAY_FOREACH(k, j) { @@ -265,13 +271,13 @@ static void *thread(void *arg) { } assert_se(x == 6); - assert_se(varlink_call(c, "io.test.DoSomething", i, &o, &e, NULL) >= 0); + assert_se(varlink_call(c, "io.test.DoSomething", i, &o, &e) >= 0); assert_se(json_variant_integer(json_variant_by_key(o, "sum")) == 88 + 99); assert_se(!e); - int fd1 = acquire_data_fd("foo", 3, 0); - int fd2 = acquire_data_fd("bar", 3, 0); - int fd3 = acquire_data_fd("quux", 4, 0); + int fd1 = acquire_data_fd("foo"); + int fd2 = acquire_data_fd("bar"); + int fd3 = acquire_data_fd("quux"); assert_se(fd1 >= 0); assert_se(fd2 >= 0); @@ -281,7 +287,7 @@ static void *thread(void *arg) { assert_se(varlink_push_fd(c, fd2) == 1); assert_se(varlink_push_fd(c, fd3) == 2); - assert_se(varlink_callb(c, "io.test.PassFD", &o, &e, NULL, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("fd", JSON_BUILD_STRING("whoop")))) >= 0); + assert_se(varlink_callb(c, "io.test.PassFD", &o, &e, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("fd", JSON_BUILD_STRING("whoop")))) >= 0); int fd4 = varlink_peek_fd(c, 0); int fd5 = varlink_peek_fd(c, 1); @@ -292,9 +298,9 @@ static void *thread(void *arg) { test_fd(fd4, "miau", 4); test_fd(fd5, "wuff", 4); - assert_se(varlink_callb(c, "io.test.IDontExist", &o, &e, NULL, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("x", JSON_BUILD_REAL(5.5)))) >= 0); - assert_se(streq_ptr(json_variant_string(json_variant_by_key(o, "method")), "io.test.IDontExist")); - assert_se(streq(e, VARLINK_ERROR_METHOD_NOT_FOUND)); + assert_se(varlink_callb(c, "io.test.IDontExist", &o, &e, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("x", JSON_BUILD_REAL(5.5)))) >= 0); + ASSERT_STREQ(json_variant_string(json_variant_by_key(o, "method")), "io.test.IDontExist"); + ASSERT_STREQ(e, VARLINK_ERROR_METHOD_NOT_FOUND); flood_test(arg); diff --git a/src/test/test-vpick.c b/src/test/test-vpick.c new file mode 100644 index 0000000..88646ec --- /dev/null +++ b/src/test/test-vpick.c @@ -0,0 +1,171 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include "fd-util.h" +#include "fileio.h" +#include "fs-util.h" +#include "mkdir.h" +#include "path-util.h" +#include "rm-rf.h" +#include "tests.h" +#include "tmpfile-util.h" +#include "vpick.h" + +TEST(path_pick) { + _cleanup_(rm_rf_physical_and_freep) char *p = NULL; + _cleanup_close_ int dfd = -EBADF, sub_dfd = -EBADF; + + dfd = mkdtemp_open(NULL, O_DIRECTORY|O_CLOEXEC, &p); + assert(dfd >= 0); + + sub_dfd = open_mkdir_at(dfd, "foo.v", O_CLOEXEC, 0777); + assert(sub_dfd >= 0); + + assert_se(write_string_file_at(sub_dfd, "foo_5.5.raw", "5.5", WRITE_STRING_FILE_CREATE) >= 0); + assert_se(write_string_file_at(sub_dfd, "foo_55.raw", "55", WRITE_STRING_FILE_CREATE) >= 0); + assert_se(write_string_file_at(sub_dfd, "foo_5.raw", "5", WRITE_STRING_FILE_CREATE) >= 0); + assert_se(write_string_file_at(sub_dfd, "foo_5_ia64.raw", "5", WRITE_STRING_FILE_CREATE) >= 0); + assert_se(write_string_file_at(sub_dfd, "foo_7.raw", "7", WRITE_STRING_FILE_CREATE) >= 0); + assert_se(write_string_file_at(sub_dfd, "foo_7_x86-64.raw", "7 64bit", WRITE_STRING_FILE_CREATE) >= 0); + assert_se(write_string_file_at(sub_dfd, "foo_55_x86-64.raw", "55 64bit", WRITE_STRING_FILE_CREATE) >= 0); + assert_se(write_string_file_at(sub_dfd, "foo_55_x86.raw", "55 32bit", WRITE_STRING_FILE_CREATE) >= 0); + assert_se(write_string_file_at(sub_dfd, "foo_99_x86.raw", "99 32bit", WRITE_STRING_FILE_CREATE) >= 0); + + /* Let's add an entry for sparc (which is a valid arch, but almost certainly not what we test + * on). This entry should hence always be ignored */ + if (native_architecture() != ARCHITECTURE_SPARC) + assert_se(write_string_file_at(sub_dfd, "foo_100_sparc.raw", "100 sparc", WRITE_STRING_FILE_CREATE) >= 0); + + assert_se(write_string_file_at(sub_dfd, "quux_1_s390.raw", "waldo1", WRITE_STRING_FILE_CREATE) >= 0); + assert_se(write_string_file_at(sub_dfd, "quux_2_s390+4-6.raw", "waldo2", WRITE_STRING_FILE_CREATE) >= 0); + assert_se(write_string_file_at(sub_dfd, "quux_3_s390+0-10.raw", "waldo3", WRITE_STRING_FILE_CREATE) >= 0); + + _cleanup_free_ char *pp = NULL; + pp = path_join(p, "foo.v"); + assert_se(pp); + + _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL; + + PickFilter filter = { + .architecture = _ARCHITECTURE_INVALID, + .suffix = STRV_MAKE(".raw"), + }; + + if (IN_SET(native_architecture(), ARCHITECTURE_X86, ARCHITECTURE_X86_64)) { + assert_se(path_pick(NULL, AT_FDCWD, pp, &filter, PICK_ARCHITECTURE|PICK_TRIES, &result) > 0); + assert_se(S_ISREG(result.st.st_mode)); + ASSERT_STREQ(result.version, "99"); + assert_se(result.architecture == ARCHITECTURE_X86); + assert_se(endswith(result.path, "/foo_99_x86.raw")); + + pick_result_done(&result); + } + + filter.architecture = ARCHITECTURE_X86_64; + assert_se(path_pick(NULL, AT_FDCWD, pp, &filter, PICK_ARCHITECTURE|PICK_TRIES, &result) > 0); + assert_se(S_ISREG(result.st.st_mode)); + ASSERT_STREQ(result.version, "55"); + assert_se(result.architecture == ARCHITECTURE_X86_64); + assert_se(endswith(result.path, "/foo_55_x86-64.raw")); + pick_result_done(&result); + + filter.architecture = ARCHITECTURE_IA64; + assert_se(path_pick(NULL, AT_FDCWD, pp, &filter, PICK_ARCHITECTURE|PICK_TRIES, &result) > 0); + assert_se(S_ISREG(result.st.st_mode)); + ASSERT_STREQ(result.version, "5"); + assert_se(result.architecture == ARCHITECTURE_IA64); + assert_se(endswith(result.path, "/foo_5_ia64.raw")); + pick_result_done(&result); + + filter.architecture = _ARCHITECTURE_INVALID; + filter.version = "5"; + assert_se(path_pick(NULL, AT_FDCWD, pp, &filter, PICK_ARCHITECTURE|PICK_TRIES, &result) > 0); + assert_se(S_ISREG(result.st.st_mode)); + ASSERT_STREQ(result.version, "5"); + if (native_architecture() != ARCHITECTURE_IA64) { + assert_se(result.architecture == _ARCHITECTURE_INVALID); + assert_se(endswith(result.path, "/foo_5.raw")); + } + pick_result_done(&result); + + filter.architecture = ARCHITECTURE_IA64; + assert_se(path_pick(NULL, AT_FDCWD, pp, &filter, PICK_ARCHITECTURE|PICK_TRIES, &result) > 0); + assert_se(S_ISREG(result.st.st_mode)); + ASSERT_STREQ(result.version, "5"); + assert_se(result.architecture == ARCHITECTURE_IA64); + assert_se(endswith(result.path, "/foo_5_ia64.raw")); + pick_result_done(&result); + + filter.architecture = ARCHITECTURE_CRIS; + assert_se(path_pick(NULL, AT_FDCWD, pp, &filter, PICK_ARCHITECTURE|PICK_TRIES, &result) == 0); + assert_se(result.st.st_mode == MODE_INVALID); + assert_se(!result.version); + assert_se(result.architecture < 0); + assert_se(!result.path); + + assert_se(unlinkat(sub_dfd, "foo_99_x86.raw", 0) >= 0); + + filter.architecture = _ARCHITECTURE_INVALID; + filter.version = NULL; + if (IN_SET(native_architecture(), ARCHITECTURE_X86_64, ARCHITECTURE_X86)) { + assert_se(path_pick(NULL, AT_FDCWD, pp, &filter, PICK_ARCHITECTURE|PICK_TRIES, &result) > 0); + assert_se(S_ISREG(result.st.st_mode)); + ASSERT_STREQ(result.version, "55"); + + if (native_architecture() == ARCHITECTURE_X86_64) { + assert_se(result.architecture == ARCHITECTURE_X86_64); + assert_se(endswith(result.path, "/foo_55_x86-64.raw")); + } else { + assert_se(result.architecture == ARCHITECTURE_X86); + assert_se(endswith(result.path, "/foo_55_x86.raw")); + } + pick_result_done(&result); + } + + /* Test explicit patterns in last component of path not being .v */ + free(pp); + pp = path_join(p, "foo.v/foo___.raw"); + assert_se(pp); + + if (IN_SET(native_architecture(), ARCHITECTURE_X86, ARCHITECTURE_X86_64)) { + assert_se(path_pick(NULL, AT_FDCWD, pp, &filter, PICK_ARCHITECTURE|PICK_TRIES, &result) > 0); + assert_se(S_ISREG(result.st.st_mode)); + ASSERT_STREQ(result.version, "55"); + assert_se(result.architecture == native_architecture()); + assert_se(endswith(result.path, ".raw")); + assert_se(strrstr(result.path, "/foo_55_x86")); + pick_result_done(&result); + } + + /* Specify an explicit path */ + free(pp); + pp = path_join(p, "foo.v/foo_5.raw"); + assert_se(pp); + + filter.type_mask = UINT32_C(1) << DT_DIR; + assert_se(path_pick(NULL, AT_FDCWD, pp, &filter, PICK_ARCHITECTURE|PICK_TRIES, &result) == -ENOTDIR); + + filter.type_mask = UINT32_C(1) << DT_REG; + assert_se(path_pick(NULL, AT_FDCWD, pp, &filter, PICK_ARCHITECTURE|PICK_TRIES, &result) > 0); + assert_se(S_ISREG(result.st.st_mode)); + assert_se(!result.version); + assert_se(result.architecture == _ARCHITECTURE_INVALID); + assert_se(path_equal(result.path, pp)); + pick_result_done(&result); + + free(pp); + pp = path_join(p, "foo.v"); + assert_se(pp); + + filter.architecture = ARCHITECTURE_S390; + filter.basename = "quux"; + + assert_se(path_pick(NULL, AT_FDCWD, pp, &filter, PICK_ARCHITECTURE|PICK_TRIES, &result) > 0); + assert_se(S_ISREG(result.st.st_mode)); + ASSERT_STREQ(result.version, "2"); + assert_se(result.tries_left == 4); + assert_se(result.tries_done == 6); + assert_se(endswith(result.path, "quux_2_s390+4-6.raw")); + assert_se(result.architecture == ARCHITECTURE_S390); +} + +DEFINE_TEST_MAIN(LOG_DEBUG); diff --git a/src/test/test-watch-pid.c b/src/test/test-watch-pid.c index b0c2c06..423a9be 100644 --- a/src/test/test-watch-pid.c +++ b/src/test/test-watch-pid.c @@ -18,7 +18,7 @@ int main(int argc, char *argv[]) { if (getuid() != 0) return log_tests_skipped("not root"); r = enter_cgroup_subroot(NULL); - if (r == -ENOMEDIUM) + if (r < 0) return log_tests_skipped("cgroupfs not available"); _cleanup_free_ char *unit_dir = NULL; @@ -54,7 +54,7 @@ int main(int argc, char *argv[]) { assert_se(pid >= 0); assert_se(hashmap_isempty(m->watch_pids)); - assert_se(manager_get_unit_by_pid(m, pid) == NULL); + ASSERT_NULL(manager_get_unit_by_pid(m, pid)); assert_se(unit_watch_pid(a, pid, false) >= 0); assert_se(manager_get_unit_by_pid(m, pid) == a); @@ -93,10 +93,10 @@ int main(int argc, char *argv[]) { assert_se(manager_get_unit_by_pid(m, pid) == c); unit_unwatch_pid(c, pid); - assert_se(manager_get_unit_by_pid(m, pid) == NULL); + ASSERT_NULL(manager_get_unit_by_pid(m, pid)); unit_unwatch_pid(c, pid); - assert_se(manager_get_unit_by_pid(m, pid) == NULL); + ASSERT_NULL(manager_get_unit_by_pid(m, pid)); return 0; } diff --git a/src/test/test-xattr-util.c b/src/test/test-xattr-util.c index 85901c9..c754ac5 100644 --- a/src/test/test-xattr-util.c +++ b/src/test/test-xattr-util.c @@ -45,13 +45,13 @@ TEST(getxattr_at_malloc) { fd = open("/", O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOCTTY); assert_se(fd >= 0); r = getxattr_at_malloc(fd, "usr", "user.idontexist", 0, &value); - assert_se(r < 0 && ERRNO_IS_XATTR_ABSENT(r)); + assert_se(ERRNO_IS_NEG_XATTR_ABSENT(r)); safe_close(fd); fd = open(x, O_PATH|O_CLOEXEC); assert_se(fd >= 0); assert_se(getxattr_at_malloc(fd, NULL, "user.foo", 0, &value) == 3); - assert_se(streq(value, "bar")); + ASSERT_STREQ(value, "bar"); } TEST(getcrtime) { @@ -83,7 +83,7 @@ static void verify_xattr(int dfd, const char *expected) { _cleanup_free_ char *value = NULL; assert_se(getxattr_at_malloc(dfd, "test", "user.foo", 0, &value) == (int) strlen(expected)); - assert_se(streq(value, expected)); + ASSERT_STREQ(value, expected); } TEST(xsetxattr) { @@ -99,7 +99,7 @@ TEST(xsetxattr) { /* by full path */ r = xsetxattr(AT_FDCWD, x, "user.foo", "fullpath", SIZE_MAX, 0); - if (r < 0 && ERRNO_IS_NOT_SUPPORTED(r)) + if (ERRNO_IS_NEG_NOT_SUPPORTED(r)) return (void) log_tests_skipped_errno(r, "no xattrs supported on /var/tmp"); assert_se(r >= 0); verify_xattr(dfd, "fullpath"); diff --git a/src/test/test-xml.c b/src/test/test-xml.c index a8cb635..6367f27 100644 --- a/src/test/test-xml.c +++ b/src/test/test-xml.c @@ -29,7 +29,7 @@ static void test_one(const char *data, ...) { break; nn = va_arg(ap, const char *); - assert_se(streq_ptr(nn, name)); + ASSERT_STREQ(nn, name); } va_end(ap); |