From f7994b7d50cd4d7994df07f7e19b9bad173cfb8d Mon Sep 17 00:00:00 2001 From: Quinn Date: Tue, 22 Apr 2025 11:59:51 +0200 Subject: [PATCH] add testing code --- test/src/main.c | 18 ++++++++++++++++++ test/src/test.h | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 test/src/main.c create mode 100644 test/src/test.h diff --git a/test/src/main.c b/test/src/main.c new file mode 100644 index 0000000..ebd09e8 --- /dev/null +++ b/test/src/main.c @@ -0,0 +1,18 @@ +#include +#include + +#include "test.h" + +int main(void) { + /* + // tests that should be performed + testdat tests[] = { + }; + + // get test count + size_t n = sizeof(tests) / sizeof(tests[0]); + */ + + return exec_tests(NULL, 0); + // return exec_tests(tests, n); +} diff --git a/test/src/test.h b/test/src/test.h new file mode 100644 index 0000000..ad9381c --- /dev/null +++ b/test/src/test.h @@ -0,0 +1,39 @@ +#pragma once +#include + +// evaluates the test +// returns 1 upon error +static inline int assert_helper(int cond, char const* restrict fname, unsigned ln, char const* restrict fnname, char const* restrict expr) { + if (cond) + printf("[\033[32;1m OK \033[0m] %s -> %s:%u (%s)\n", fnname, fname, ln, expr); + else + printf("[\033[31;1m FAIL \033[0m] %s -> %s:%u (%s)\n", fnname, fname, ln, expr); + return !cond; +} + +#define assert_true(expr) assert_helper(!!(expr), __FILE_NAME__, __LINE__, __func__, #expr) // evaluation expected to be true +#define assert_false(expr) assert_helper(!(expr), __FILE_NAME__, __LINE__, __func__, #expr) // evaluation expected to be false + +// contains the data for executing a single test +struct testdat { + int (*test)(void*); // test, returns 0 upon success, non-zero upon failure + void* args; // arguments to the test +}; +typedef struct testdat testdat; + +// executes the tests, returns the amount of failed tests; >0: failure +static inline size_t exec_tests(testdat* dat, size_t ntests) { + size_t i; + size_t err = 0; + + // perform tests and count the error state + for (i = 0; i < ntests; i++) + err += !!(dat[i].test(dat[i].args)); + + // give final score + if (!err) + fprintf(stdout, "tests completed! (%zu/%zu)\n", ntests - err, ntests); + else + fprintf(stderr, " tests failed! (%zu/%zu)\n", ntests - err, ntests); + return err; +}