diff options
author | Luke T. Shumaker <lukeshu@lukeshu.com> | 2024-11-15 15:12:08 -0700 |
---|---|---|
committer | Luke T. Shumaker <lukeshu@lukeshu.com> | 2024-11-15 21:40:37 -0700 |
commit | 5704de985cff1d40359ecd15211cece0fbe79067 (patch) | |
tree | 5c172a6ea91716f4f8023e58d580e4b08fbd7fc1 /libmisc/tests/test_assert.c | |
parent | f753128b22b61d4f85a74ba2694b8f9a576fc238 (diff) |
Add tests to libmisc
Diffstat (limited to 'libmisc/tests/test_assert.c')
-rw-r--r-- | libmisc/tests/test_assert.c | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/libmisc/tests/test_assert.c b/libmisc/tests/test_assert.c new file mode 100644 index 0000000..949b4f9 --- /dev/null +++ b/libmisc/tests/test_assert.c @@ -0,0 +1,65 @@ +/* libmisc/tests/test_assert.c - Tests for <libmisc/assert.h> + * + * Copyright (C) 2024 Luke T. Shumaker <lukeshu@lukeshu.com> + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +#include <stdbool.h> + +#include <libmisc/assert.h> + +#include "test.h" + +/* Intercept failures *********************************************************/ + +bool global_failed = false; +bool global_unreachable = false; + +void __assert_msg_fail(const char *expr, + const char *file, unsigned int line, const char *func, + const char *msg) { + static bool in_fail = false; + if (!in_fail) { + in_fail = true; + printf("error: %s:%u:%s(): assertion \"%s\" failed%s%s\n", + file, line, func, + expr, + msg ? ": " : "", msg); + } + global_failed = true; +} + +#define __builtin_unreachable() do { global_unreachable = true; } while (0) + +/* Utilities ******************************************************************/ + +#define test_should_succeed(test) do { \ + global_failed = false; \ + test; \ + test_assert(global_failed == false); \ + } while (0) + +#define test_should_fail(test) do { \ + global_failed = false; \ + test; \ + test_assert(global_failed == true); \ + } while (0) + +/* Actual tests ***************************************************************/ + +static_assert(sizeof(char) == 1); + +int main() { + test_should_succeed(assert(true)); + test_should_fail(assert(false)); + + test_should_succeed(assert_msg(true, "foo")); + test_should_fail(assert_msg(false, "foo")); + test_should_succeed(assert_msg(true, NULL)); + test_should_fail(assert_msg(false, NULL)); + + test_should_fail(assert_notreached("")); + test_assert(global_unreachable == true); + + return 0; +} |