/* SIMPLE_TEST_PRINT_FUN may be redefined like so. default is `printf` */ #define stderr_redirect(...) fprintf(stderr, __VA_ARGS__) #define SIMPLE_TEST_PRINT_FUN stderr_redirect /* colour output is on by default, but can be disabled */ /* #define SIMPLE_TEST_USE_COLOUR false */ #include "../simple-test.h" /* global variables, functions, and includes must come before BEGIN_TEST */ char *global_s; /* a teardown function is called by TESTs which include USE_TEARDOWN. the call * occurs either after an ASSERT fails or after the TEST is finished. * * defining one is optional, but, if used, REGISTER_TEARDOWN must appear * between BEGIN_TEST and the first TEST statement. * * here i'm using it to free memory that's alloced inside tests below */ void teardown(void) { free(global_s); } /* must appear before an (optional) REGISTER_TEARDOWN and all TESTs */ BEGIN_TEST /* if used, must appear before first TEST and after BEGIN_TEST */ REGISTER_TEARDOWN(teardown); /* run a test. provided description must be a string literal */ TEST("basic assertion") { /* ASSERT fails if passed some sort of non-true value (0, false, NULL) */ ASSERT(1); } TEST("basic not assertion") { bool b = false; ASSERT_NOT(b); } TEST("boolean comparison") { bool a = false, b = true; /* fail if parameters are not equal */ ASSERT_EQ(a, b); } TEST("type mismatch") { char a = 'a'; int i = 97; char *b = NULL; /* for convenience's sake, when presented with mismatched types, assertions * try to resolve them in a way that's most likely to match the * programmer's intentions. here 'i' is interpreted as a char */ ASSERT_EQ(a, i); /* if there isn't a straightforward comparison to make, though (as is the * case here, with a 'char' and 'char *'), a type mismatch error occurs */ ASSERT_EQ(a, b); } TEST("ECHO example") { int i; /* ECHO can be used to neatly report information during a run */ if (true) ECHO("loop until i not less than 1"); for (i = 0; i < 2; i++) { /* it takes printf format strings and variable args as well */ ECHO("i == %d", i); ASSERT_LT(i, 1); } } TEST("string comparison") { char *s = "test"; global_s = strdup("test"); /* USE_TEARDOWN; tells this test to call the previously defined teardown * function on exiting (successfully or otherwise) */ USE_TEARDOWN; /* strings are compared by content, so this assertion succeeds */ ASSERT_EQ(s, global_s); } TEST("pointer comparison") { char *s = "test"; global_s = strdup("test"); USE_TEARDOWN; /* you can cast parameters in order to use a different type of comparison. * here i'm casting the 'char *' to 'void *' so assertion performs a * pointer comparison, which fails */ ASSERT_EQ((void*)s, (void*)global_s); } /* must come after all TESTs */ END_TEST