test: Add ASSERT_ERROR() and ASSERT_ERROR_ERRNO()

For when we expect something to fail with a specific error.
This commit is contained in:
Daan De Meyer
2024-04-22 09:42:29 +02:00
parent 949d967964
commit dd8e82f0d6
2 changed files with 46 additions and 0 deletions
+31
View File
@@ -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)) { \
+15
View File
@@ -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"
@@ -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());