From 25769288f62816d733004c9e8347c35dd0e4ce2a Mon Sep 17 00:00:00 2001 From: Tavian Barnes Date: Wed, 27 Mar 2024 11:20:20 -0400 Subject: tests: New bfs_pcheck() macro to report xstrerror(errno) --- tests/main.c | 6 ++++++ tests/tests.h | 16 ++++++++++++++++ tests/xtime.c | 6 +++--- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/tests/main.c b/tests/main.c index 8849e8c..7dec320 100644 --- a/tests/main.c +++ b/tests/main.c @@ -6,8 +6,10 @@ */ #include "tests.h" +#include "../src/bfstd.h" #include "../src/color.h" #include "../src/config.h" +#include #include #include #include @@ -88,6 +90,10 @@ static void run_test(struct test_ctx *ctx, const char *test, test_fn *fn) { } } +const char *bfs_errstr(void) { + return xstrerror(errno); +} + int main(int argc, char *argv[]) { // Try to set a UTF-8 locale if (!setlocale(LC_ALL, "C.UTF-8")) { diff --git a/tests/tests.h b/tests/tests.h index 6629dcf..b644450 100644 --- a/tests/tests.h +++ b/tests/tests.h @@ -51,4 +51,20 @@ static inline bool bfs_check(bool ret) { : "Check failed: `%s`%s", \ str, __VA_ARGS__), false)) +/** Get a string description of the last error. */ +const char *bfs_errstr(void); + +/** + * Check a condition, logging the current error string on failure. + */ +#define bfs_pcheck(...) \ + bfs_pcheck_(#__VA_ARGS__, __VA_ARGS__, "", "") + +#define bfs_pcheck_(str, cond, format, ...) \ + ((cond) ? true : (bfs_diag( \ + sizeof(format) > 1 \ + ? "%.0s" format "%s%s: %s" \ + : "Check failed: `%s`%s: %s", \ + str, __VA_ARGS__, bfs_errstr()), false)) + #endif // BFS_TESTS_H diff --git a/tests/xtime.c b/tests/xtime.c index ec499d8..f85402e 100644 --- a/tests/xtime.c +++ b/tests/xtime.c @@ -29,9 +29,9 @@ static bool check_one_xgetdate(const char *str, int error, time_t expected) { int ret = xgetdate(str, &ts); if (error) { - return bfs_check(ret == -1 && errno == error, "xgetdate('%s'): %s", str, xstrerror(errno)); + return bfs_pcheck(ret == -1 && errno == error, "xgetdate('%s')", str); } else { - return bfs_check(ret == 0, "xgetdate('%s'): %s", str, xstrerror(errno)) + return bfs_pcheck(ret == 0, "xgetdate('%s')", str) && bfs_check(ts.tv_sec == expected && ts.tv_nsec == 0, "xgetdate('%s'): %jd.%09jd != %jd", str, (intmax_t)ts.tv_sec, (intmax_t)ts.tv_nsec, (intmax_t)expected); @@ -87,7 +87,7 @@ static bool check_one_xmktime(time_t expected) { } time_t actual; - return bfs_check(xmktime(&tm, &actual) == 0, "xmktime(" TM_FORMAT "): %s", TM_PRINTF(tm), xstrerror(errno)) + return bfs_pcheck(xmktime(&tm, &actual) == 0, "xmktime(" TM_FORMAT ")", TM_PRINTF(tm)) && bfs_check(actual == expected, "xmktime(" TM_FORMAT "): %jd != %jd", TM_PRINTF(tm), (intmax_t)actual, (intmax_t)expected); } -- cgit v1.2.3