I have rolled this simple unit test library for C:
com_github_coderodde_my_assert.h
:
#ifndef COM_GITHUB_CODERODDE_MY_ASSERT_H#define COM_GITHUB_CODERODDE_MY_ASSERT_H#include <stdbool.h>#include <stdio.h>extern size_t passes;extern size_t failed;void print_test_statistics();#define ASSERT_IMPL(COND, LINE) assert_impl(COND, #COND, __LINE__);#define ASSERT(COND) ASSERT_IMPL(COND, __LINE__)#endif
com_github_coderodde_my_assert.c
:
#include "com_github_coderodde_my_assert.h"#include <stdlib.h>static size_t passes = 0;static size_t failed = 0;void assert_impl(bool passed, const char* condition_text, size_t line_number) { if (passed) { passes++; } else { failed++; printf("Failed condition \"%s\" at line %zu.\n", condition_text, line_number); }}static void print_bar(size_t passes, size_t failed) { size_t total_assertions = passes + failed; char bar[81]; bar[0] = '['; bar[79] = ']'; bar[80] = '\0'; float ratio = (float)(passes) / (float)(total_assertions); size_t hash_symbols = (size_t)(78 * ratio); for (size_t i = 0; i < hash_symbols; i++) { bar[i + 1] = '#'; } for (size_t i = 0; i < 78 - hash_symbols; i++) { bar[i + 1 + hash_symbols] = ''; } if (failed != 0) { printf("\033[0;31m"); printf("%s: %.2f%%.\n", bar, 100.0f * ratio); } else { printf("\033[0;32m"); printf("%s: %.2F%%.\n", bar, 100.0f * ratio); } printf("\033[0m");}void print_test_statistics() { printf("Passes: %zu, failures: %zu, total assertions: %zu.\n", passes, failed, passes + failed); print_bar(passes, failed);}
main.c
:
#include "com_github_coderodde_my_assert.h"#include <stdbool.h>int main() { ASSERT(true); ASSERT(false); ASSERT(1 + 1 == 3); print_test_statistics(); return 0;}
Critique request
As always, I would love to hear any comments on how to improve my result.