Login
1 branch 0 tags
Ben (T14/NixOS) Minor Makefile cleanup 7080bfb 28 days ago 85 Commits
moon / tests / test_harness.c
#include "test_harness.h"

#include <stdarg.h>
#include <stdio.h>

#include <string.h>

typedef struct {
	const char* name;
	test_fn_t fn;
} test_case_t;

static test_case_t test_cases[TEST_MAX_CASES];
static int test_case_count = 0;
static const char* current_test_name = NULL;

void test_register(const char* name, test_fn_t fn) {
	if (!name || !fn || test_case_count >= TEST_MAX_CASES) {
		return;
	}

	test_cases[test_case_count].name = name;
	test_cases[test_case_count].fn = fn;
	test_case_count++;
}

bool test_fail_impl(const char* file, int line, const char* fmt, ...) {
	va_list args;
	fprintf(stderr, "[FAIL] %s (%s:%d): ",
	        current_test_name ? current_test_name : "<unknown>", file, line);
	va_start(args, fmt);
	vfprintf(stderr, fmt, args);
	va_end(args);
	fputc('\n', stderr);
	return false;
}

int test_run_all(bool verbose) {
	int passed = 0;
	int failed = 0;

	for (int i = 0; i < test_case_count; i++) {
		current_test_name = test_cases[i].name;
		bool ok = test_cases[i].fn();
		if (ok) {
			passed++;
			if (verbose) {
				printf("[PASS] %s\n", test_cases[i].name);
			}
		} else {
			failed++;
		}
	}

	printf("Ran %d tests: %d passed, %d failed\n", test_case_count, passed,
	       failed);
	return failed;
}