Skip to content

Instantly share code, notes, and snippets.

@erdeszt
Created February 8, 2020 16:02
Show Gist options
  • Save erdeszt/0641bdb3367893ea0b23c4072bc4c2df to your computer and use it in GitHub Desktop.
Save erdeszt/0641bdb3367893ea0b23c4072bc4c2df to your computer and use it in GitHub Desktop.
Single header C test framework
#ifndef _E_TEST_H_
#define _E_TEST_H_
#include <stdint.h>
#include <stdio.h>
#define TEST(suite, name) \
if (_etest_is_test_included_in_run(#suite, #name, test_context)) { \
_etest_register_running_test(#suite, #name, test_context); \
} \
if (_etest_is_test_included_in_run(#suite, #name, test_context))
#define ASSERT(assertion, message) \
_etest_assert(assertion, message, __FILE__, __LINE__, test_context)
typedef struct {
uint32_t tests_run;
uint32_t test_failures;
} etest_context_t;
etest_context_t etest_create_context(void) {
etest_context_t test_context = {.tests_run = 0u, .test_failures = 0u};
return test_context;
}
void etest_report(const etest_context_t *test_context) {
printf(
"%d Tests, %d Failures\n",
test_context->tests_run,
test_context->test_failures);
}
uint8_t _etest_is_test_included_in_run(
const char const *suite,
const char const *name,
etest_context_t * test_context) {
return (uint8_t)1u;
}
void _etest_register_running_test(
const char const *suite,
const char const *name,
etest_context_t * test_context) {
printf("[%s] %s\n", suite, name);
test_context->tests_run++;
}
void _etest_assert(
const int32_t assertion,
const char const *message,
const char const *file,
const int32_t line,
etest_context_t * test_context) {
if (!assertion) {
printf("Assertion failed in %s line %d: \"%s\"\n", file, line, message);
test_context->test_failures++;
}
}
#endif // _E_TEST_H_
#include "etest.h"
void test_suite(etest_context_t *test_context) {
TEST(DemoSuite, PassingTrivial) {
ASSERT(1, "1 is always true");
}
TEST(DemoSuite, FailingTrivial) {
ASSERT(0, "0 is always false");
}
}
int main(int argc, char *argv[]) {
etest_context_t test_context = etest_create_context();
test_suite(&test_context);
etest_report(&test_context);
return 0;
}
$ gcc -O2 -g -o example_test example_test.c
$ ./example_test
[DemoSuite] PassingTrivial
[DemoSuite] FailingTrivial
Assertion failed in test/test_suite.c line 11: "0 is always false"
2 Tests, 1 Failures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment