From: Daan De Meyer Date: Sun, 21 Apr 2024 12:16:08 +0000 (+0200) Subject: test: Add ASSERT_ERROR() and ASSERT_ERROR_ERRNO() X-Git-Tag: v256-rc1~87^2~3 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=dd8e82f0d6aa0283b372e599791d17cbd8c18220;p=thirdparty%2Fsystemd.git test: Add ASSERT_ERROR() and ASSERT_ERROR_ERRNO() For when we expect something to fail with a specific error. --- diff --git a/src/shared/tests.h b/src/shared/tests.h index 784748545c2..09fdfd6b75c 100644 --- a/src/shared/tests.h +++ b/src/shared/tests.h @@ -8,6 +8,7 @@ #include "sd-daemon.h" #include "argv-util.h" +#include "errno-util.h" #include "macro.h" #include "process-util.h" #include "rlimit-util.h" @@ -226,6 +227,36 @@ static inline int run_test_table(void) { } \ }) +#define ASSERT_ERROR(expr1, expr2) \ + ({ \ + int _expr1 = (expr1); \ + int _expr2 = (expr2); \ + if (_expr1 >= 0) { \ + log_error("%s:%i: Assertion failed: expected \"%s\" to fail with error \"%s\", but it succeeded", \ + PROJECT_FILE, __LINE__, #expr1, STRERROR(_expr2)); \ + abort(); \ + } else if (-_expr1 != _expr2) { \ + log_error_errno(_expr1, "%s:%i: Assertion failed: expected \"%s\" to fail with error \"%s\", but got the following error: %m", \ + PROJECT_FILE, __LINE__, #expr1, STRERROR(_expr2)); \ + abort(); \ + } \ + }) + +#define ASSERT_ERROR_ERRNO(expr1, expr2) \ + ({ \ + int _expr1 = (expr1); \ + int _expr2 = (expr2); \ + if (_expr1 >= 0) { \ + log_error("%s:%i: Assertion failed: expected \"%s\" to fail with error \"%s\", but it succeeded", \ + PROJECT_FILE, __LINE__, #expr1, STRERROR(_expr2)); \ + abort(); \ + } else if (errno != _expr2) { \ + log_error_errno(errno, "%s:%i: Assertion failed: expected \"%s\" to fail with error \"%s\", but got the following error: %m", \ + PROJECT_FILE, __LINE__, #expr1, STRERROR(errno)); \ + abort(); \ + } \ + }) + #define ASSERT_TRUE(expr) \ ({ \ if (!(expr)) { \ diff --git a/src/test/test-macro.c b/src/test/test-macro.c index 05e15c8bdcf..9e2875d8a71 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 +#include +#include "errno-util.h" #include "log.h" #include "macro.h" #include "tests.h" @@ -1120,6 +1122,19 @@ TEST(ASSERT) { 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());