// single-header unit test framework. // if you want to keep your sanity, do not use this. #include #include #include // globals. struct tests_state { int passed_tests; int run_tests; int total_tests; char *current_label; }; struct tests_state tests_state = { 0, 0, 0, NULL }; /* Basic idea: TEST("...", { ASSERT(...) ASSERT(...) ... }) TEST("...", { ASSERT(...) ASSERT(...) ... }) DONE */ #define TEST(LABEL, BLOCK) \ tests_state.current_label = LABEL; \ tests_state.run_tests++; \ tests_state.total_tests = __COUNTER__; \ BLOCK; \ fprintf(stderr, "[%3d] \x1b[32m%s ✓\x1b[0m\n", tests_state.run_tests, tests_state.current_label); \ tests_state.passed_tests++; #define ASSERT(EXPR) \ if (!(EXPR)) { \ fprintf(stderr, "[%3d] \x1b[31m%s ❌\x1b[0m\n", tests_state.run_tests, tests_state.current_label); \ fprintf(stderr, " Assertion failed in %s:%d:\n", __FILE__, __LINE__); \ fprintf(stderr, " " #EXPR "\n"); \ goto tests_bail; \ } #define DONE \ tests_bail: { \ tests_state.total_tests = __COUNTER__; \ fprintf(stderr, "[\x1b[%dm***\x1b[0m] %d/%d tests passed", tests_state.passed_tests == tests_state.total_tests ? 32 : 31, tests_state.passed_tests, tests_state.total_tests); \ if (tests_state.total_tests > tests_state.run_tests) { \ fprintf(stderr, ", %d skipped", tests_state.total_tests - tests_state.run_tests); \ } \ fprintf(stderr, ".\n"); \ if (tests_state.passed_tests != tests_state.total_tests) exit(1); \ }