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

#include <stdbool.h>
#include <string.h>

#define TEST_MAX_CASES 256

typedef bool (*test_fn_t)(void);

void test_register(const char* name, test_fn_t fn);
int test_run_all(bool verbose);
bool test_fail_impl(const char* file, int line, const char* fmt, ...);

#define ASSERT_TRUE(expr)                                                      \
	do {                                                                     \
		if (!(expr)) {                                                     \
			return test_fail_impl(__FILE__, __LINE__,                    \
			                      "Assertion failed: %s", #expr);       \
		}                                                                \
	} while (0)

#define ASSERT_FALSE(expr) ASSERT_TRUE(!(expr))

#define ASSERT_EQ_INT(expected, actual)                                        \
	do {                                                                     \
		int _expected = (expected);                                        \
		int _actual = (actual);                                            \
		if (_expected != _actual) {                                        \
			return test_fail_impl(__FILE__, __LINE__,                    \
			                      "Expected %d, got %d", _expected,    \
			                      _actual);                              \
		}                                                                \
	} while (0)

#define ASSERT_EQ_STR(expected, actual)                                        \
	do {                                                                     \
		const char* _expected = (expected);                                \
		const char* _actual = (actual);                                    \
		bool _same = false;                                                \
		if (!_expected && !_actual) {                                      \
			_same = true;                                                \
		} else if (_expected && _actual && strcmp(_expected, _actual) == 0) { \
			_same = true;                                                \
		}                                                                \
		if (!_same) {                                                     \
			return test_fail_impl(__FILE__, __LINE__,                    \
			                      "Expected \"%s\", got \"%s\"",   \
			                      _expected ? _expected : "(null)",     \
			                      _actual ? _actual : "(null)");        \
		}                                                                \
	} while (0)