unit tests: add TAP unit test framework

This patch contains an implementation for writing unit tests with TAP output. Each test is a function that contains one or more checks. The test is run with the TEST() macro and if any of the checks fail then the test will fail. A complete program that tests STRBUF_INIT would look like #include "test-lib.h" #include "strbuf.h" static void t_static_init(void) { struct strbuf buf = STRBUF_INIT; check_uint(buf.len, ==, 0); check_uint(buf.alloc, ==, 0); check_char(buf.buf[0], ==, '\0'); } int main(void) { TEST(t_static_init(), "static initialization works); return test_done(); } The output of this program would be ok 1 - static initialization works 1..1 If any of the checks in a test fail then they print a diagnostic message to aid debugging and the test will be reported as failing. For example a failing integer check would look like # check "x >= 3" failed at my-test.c:102 # left: 2 # right: 3 not ok 1 - x is greater than or equal to three There are a number of check functions implemented so far. check() checks a boolean condition, check_int(), check_uint() and check_char() take two values to compare and a comparison operator. check_str() will check if two strings are equal. Custom checks are simple to implement as shown in the comments above test_assert() in test-lib.h. Tests can be skipped with test_skip() which can be supplied with a reason for skipping which it will print. Tests can print diagnostic messages with test_msg(). Checks that are known to fail can be wrapped in TEST_TODO(). There are a couple of example test programs included in this patch. t-basic.c implements some self-tests and demonstrates the diagnostic output for failing test. The output of this program is checked by t0080-unit-test-output.sh. t-strbuf.c shows some example unit tests for strbuf.c The unit tests will be built as part of the default "make all" target, to avoid bitrot. If you wish to build just the unit tests, you can run "make build-unit-tests". To run the tests, you can use "make unit-tests" or run the test binaries directly, as in "./t/unit-tests/bin/t-strbuf". Signed-off-by: Phillip Wood <phillip.wood@dunelm.org.uk> Signed-off-by: Josh Steadmon <steadmon@google.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Phillip Wood committed Nov 9, 2023 at 10:50 UTC e137fe3b2913898ebc9fac0cef8bfe402686d9b1
8 files changed +792 -4
Makefile
+25 -3
@@ -682,6 +682,9 @@ TEST_BUILTINS_OBJS =
682 TEST_OBJS =
683 TEST_PROGRAMS_NEED_X =
684 THIRD_PARTY_SOURCES =
685 +UNIT_TEST_PROGRAMS =
686 +UNIT_TEST_DIR = t/unit-tests
687 +UNIT_TEST_BIN = $(UNIT_TEST_DIR)/bin
688
689 # Having this variable in your environment would break pipelines because
690 # you cause "cd" to echo its destination to stdout. It can also take
@@ -1331,6 +1334,12 @@ THIRD_PARTY_SOURCES += compat/regex/%
1334 THIRD_PARTY_SOURCES += sha1collisiondetection/%
1335 THIRD_PARTY_SOURCES += sha1dc/%
1336
1337 +UNIT_TEST_PROGRAMS += t-basic
1338 +UNIT_TEST_PROGRAMS += t-strbuf
1339 +UNIT_TEST_PROGS = $(patsubst %,$(UNIT_TEST_BIN)/%$X,$(UNIT_TEST_PROGRAMS))
1340 +UNIT_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(UNIT_TEST_PROGRAMS))
1341 +UNIT_TEST_OBJS += $(UNIT_TEST_DIR)/test-lib.o
1342 +
1343 # xdiff and reftable libs may in turn depend on what is in libgit.a
1344 GITLIBS = common-main.o $(LIB_FILE) $(XDIFF_LIB) $(REFTABLE_LIB) $(LIB_FILE)
1345 EXTLIBS =
@@ -2672,6 +2681,7 @@ OBJECTS += $(TEST_OBJS)
2681 OBJECTS += $(XDIFF_OBJS)
2682 OBJECTS += $(FUZZ_OBJS)
2683 OBJECTS += $(REFTABLE_OBJS) $(REFTABLE_TEST_OBJS)
2684 +OBJECTS += $(UNIT_TEST_OBJS)
2685
2686 ifndef NO_CURL
2687 OBJECTS += http.o http-walker.o remote-curl.o
@@ -3167,7 +3177,7 @@ endif
3177
3178 test_bindir_programs := $(patsubst %,bin-wrappers/%,$(BINDIR_PROGRAMS_NEED_X) $(BINDIR_PROGRAMS_NO_X) $(TEST_PROGRAMS_NEED_X))
3179
3170 -all:: $(TEST_PROGRAMS) $(test_bindir_programs)
3180 +all:: $(TEST_PROGRAMS) $(test_bindir_programs) $(UNIT_TEST_PROGS)
3181
3182 bin-wrappers/%: wrap-for-bin.sh
3183 $(call mkdir_p_parent_template)
@@ -3592,7 +3602,7 @@ endif
3602
3603 artifacts-tar:: $(ALL_COMMANDS_TO_INSTALL) $(SCRIPT_LIB) $(OTHER_PROGRAMS) \
3604 GIT-BUILD-OPTIONS $(TEST_PROGRAMS) $(test_bindir_programs) \
3595 - $(MOFILES)
3605 + $(UNIT_TEST_PROGS) $(MOFILES)
3606 $(QUIET_SUBDIR0)templates $(QUIET_SUBDIR1) \
3607 SHELL_PATH='$(SHELL_PATH_SQ)' PERL_PATH='$(PERL_PATH_SQ)'
3608 test -n "$(ARTIFACTS_DIRECTORY)"
@@ -3653,7 +3663,7 @@ clean: profile-clean coverage-clean cocciclean
3663 $(RM) $(OBJECTS)
3664 $(RM) $(LIB_FILE) $(XDIFF_LIB) $(REFTABLE_LIB) $(REFTABLE_TEST_LIB)
3665 $(RM) $(ALL_PROGRAMS) $(SCRIPT_LIB) $(BUILT_INS) $(OTHER_PROGRAMS)
3656 - $(RM) $(TEST_PROGRAMS)
3666 + $(RM) $(TEST_PROGRAMS) $(UNIT_TEST_PROGS)
3667 $(RM) $(FUZZ_PROGRAMS)
3668 $(RM) $(SP_OBJ)
3669 $(RM) $(HCC)
@@ -3831,3 +3841,15 @@ $(FUZZ_PROGRAMS): all
3841 $(XDIFF_OBJS) $(EXTLIBS) git.o $@.o $(LIB_FUZZING_ENGINE) -o $@
3842
3843 fuzz-all: $(FUZZ_PROGRAMS)
3844 +
3845 +$(UNIT_TEST_BIN):
3846 + @mkdir -p $(UNIT_TEST_BIN)
3847 +
3848 +$(UNIT_TEST_PROGS): $(UNIT_TEST_BIN)/%$X: $(UNIT_TEST_DIR)/%.o $(UNIT_TEST_DIR)/test-lib.o $(GITLIBS) GIT-LDFLAGS $(UNIT_TEST_BIN)
3849 + $(QUIET_LINK)$(CC) $(ALL_CFLAGS) -o $@ $(ALL_LDFLAGS) \
3850 + $(filter %.o,$^) $(filter %.a,$^) $(LIBS)
3851 +
3852 +.PHONY: build-unit-tests unit-tests
3853 +build-unit-tests: $(UNIT_TEST_PROGS)
3854 +unit-tests: $(UNIT_TEST_PROGS)
3855 + $(MAKE) -C t/ unit-tests
t/Makefile
+14 -1
@@ -17,6 +17,7 @@ TAR ?= $(TAR)
17 RM ?= rm -f
18 PROVE ?= prove
19 DEFAULT_TEST_TARGET ?= test
20 +DEFAULT_UNIT_TEST_TARGET ?= unit-tests-raw
21 TEST_LINT ?= test-lint
22
23 ifdef TEST_OUTPUT_DIRECTORY
@@ -41,6 +42,7 @@ TPERF = $(sort $(wildcard perf/p[0-9][0-9][0-9][0-9]-*.sh))
42 TINTEROP = $(sort $(wildcard interop/i[0-9][0-9][0-9][0-9]-*.sh))
43 CHAINLINTTESTS = $(sort $(patsubst chainlint/%.test,%,$(wildcard chainlint/*.test)))
44 CHAINLINT = '$(PERL_PATH_SQ)' chainlint.pl
45 +UNIT_TESTS = $(sort $(filter-out unit-tests/bin/t-basic%,$(wildcard unit-tests/bin/t-*)))
46
47 # `test-chainlint` (which is a dependency of `test-lint`, `test` and `prove`)
48 # checks all tests in all scripts via a single invocation, so tell individual
@@ -65,6 +67,17 @@ prove: pre-clean check-chainlint $(TEST_LINT)
67 $(T):
68 @echo "*** $@ ***"; '$(TEST_SHELL_PATH_SQ)' $@ $(GIT_TEST_OPTS)
69
70 +$(UNIT_TESTS):
71 + @echo "*** $@ ***"; $@
72 +
73 +.PHONY: unit-tests unit-tests-raw unit-tests-prove
74 +unit-tests: $(DEFAULT_UNIT_TEST_TARGET)
75 +
76 +unit-tests-raw: $(UNIT_TESTS)
77 +
78 +unit-tests-prove:
79 + @echo "*** prove - unit tests ***"; $(PROVE) $(GIT_PROVE_OPTS) $(UNIT_TESTS)
80 +
81 pre-clean:
82 $(RM) -r '$(TEST_RESULTS_DIRECTORY_SQ)'
83
@@ -149,4 +162,4 @@ perf:
162 $(MAKE) -C perf/ all
163
164 .PHONY: pre-clean $(T) aggregate-results clean valgrind perf \
152 - check-chainlint clean-chainlint test-chainlint
165 + check-chainlint clean-chainlint test-chainlint $(UNIT_TESTS)
t/t0080-unit-test-output.sh new
+58
@@ -0,0 +1,58 @@
1 +#!/bin/sh
2 +
3 +test_description='Test the output of the unit test framework'
4 +
5 +. ./test-lib.sh
6 +
7 +test_expect_success 'TAP output from unit tests' '
8 + cat >expect <<-EOF &&
9 + ok 1 - passing test
10 + ok 2 - passing test and assertion return 1
11 + # check "1 == 2" failed at t/unit-tests/t-basic.c:76
12 + # left: 1
13 + # right: 2
14 + not ok 3 - failing test
15 + ok 4 - failing test and assertion return 0
16 + not ok 5 - passing TEST_TODO() # TODO
17 + ok 6 - passing TEST_TODO() returns 1
18 + # todo check ${SQ}check(x)${SQ} succeeded at t/unit-tests/t-basic.c:25
19 + not ok 7 - failing TEST_TODO()
20 + ok 8 - failing TEST_TODO() returns 0
21 + # check "0" failed at t/unit-tests/t-basic.c:30
22 + # skipping test - missing prerequisite
23 + # skipping check ${SQ}1${SQ} at t/unit-tests/t-basic.c:32
24 + ok 9 - test_skip() # SKIP
25 + ok 10 - skipped test returns 1
26 + # skipping test - missing prerequisite
27 + ok 11 - test_skip() inside TEST_TODO() # SKIP
28 + ok 12 - test_skip() inside TEST_TODO() returns 1
29 + # check "0" failed at t/unit-tests/t-basic.c:48
30 + not ok 13 - TEST_TODO() after failing check
31 + ok 14 - TEST_TODO() after failing check returns 0
32 + # check "0" failed at t/unit-tests/t-basic.c:56
33 + not ok 15 - failing check after TEST_TODO()
34 + ok 16 - failing check after TEST_TODO() returns 0
35 + # check "!strcmp("\thello\\\\", "there\"\n")" failed at t/unit-tests/t-basic.c:61
36 + # left: "\011hello\\\\"
37 + # right: "there\"\012"
38 + # check "!strcmp("NULL", NULL)" failed at t/unit-tests/t-basic.c:62
39 + # left: "NULL"
40 + # right: NULL
41 + # check "${SQ}a${SQ} == ${SQ}\n${SQ}" failed at t/unit-tests/t-basic.c:63
42 + # left: ${SQ}a${SQ}
43 + # right: ${SQ}\012${SQ}
44 + # check "${SQ}\\\\${SQ} == ${SQ}\\${SQ}${SQ}" failed at t/unit-tests/t-basic.c:64
45 + # left: ${SQ}\\\\${SQ}
46 + # right: ${SQ}\\${SQ}${SQ}
47 + not ok 17 - messages from failing string and char comparison
48 + # BUG: test has no checks at t/unit-tests/t-basic.c:91
49 + not ok 18 - test with no checks
50 + ok 19 - test with no checks returns 0
51 + 1..19
52 + EOF
53 +
54 + ! "$GIT_BUILD_DIR"/t/unit-tests/bin/t-basic >actual &&
55 + test_cmp expect actual
56 +'
57 +
58 +test_done
t/unit-tests/.gitignore new
+1
@@ -0,0 +1 @@
1 +/bin
t/unit-tests/t-basic.c new
+95
@@ -0,0 +1,95 @@
1 +#include "test-lib.h"
2 +
3 +/*
4 + * The purpose of this "unit test" is to verify a few invariants of the unit
5 + * test framework itself, as well as to provide examples of output from actually
6 + * failing tests. As such, it is intended that this test fails, and thus it
7 + * should not be run as part of `make unit-tests`. Instead, we verify it behaves
8 + * as expected in the integration test t0080-unit-test-output.sh
9 + */
10 +
11 +/* Used to store the return value of check_int(). */
12 +static int check_res;
13 +
14 +/* Used to store the return value of TEST(). */
15 +static int test_res;
16 +
17 +static void t_res(int expect)
18 +{
19 + check_int(check_res, ==, expect);
20 + check_int(test_res, ==, expect);
21 +}
22 +
23 +static void t_todo(int x)
24 +{
25 + check_res = TEST_TODO(check(x));
26 +}
27 +
28 +static void t_skip(void)
29 +{
30 + check(0);
31 + test_skip("missing prerequisite");
32 + check(1);
33 +}
34 +
35 +static int do_skip(void)
36 +{
37 + test_skip("missing prerequisite");
38 + return 1;
39 +}
40 +
41 +static void t_skip_todo(void)
42 +{
43 + check_res = TEST_TODO(do_skip());
44 +}
45 +
46 +static void t_todo_after_fail(void)
47 +{
48 + check(0);
49 + TEST_TODO(check(0));
50 +}
51 +
52 +static void t_fail_after_todo(void)
53 +{
54 + check(1);
55 + TEST_TODO(check(0));
56 + check(0);
57 +}
58 +
59 +static void t_messages(void)
60 +{
61 + check_str("\thello\\", "there\"\n");
62 + check_str("NULL", NULL);
63 + check_char('a', ==, '\n');
64 + check_char('\\', ==, '\'');
65 +}
66 +
67 +static void t_empty(void)
68 +{
69 + ; /* empty */
70 +}
71 +
72 +int cmd_main(int argc, const char **argv)
73 +{
74 + test_res = TEST(check_res = check_int(1, ==, 1), "passing test");
75 + TEST(t_res(1), "passing test and assertion return 1");
76 + test_res = TEST(check_res = check_int(1, ==, 2), "failing test");
77 + TEST(t_res(0), "failing test and assertion return 0");
78 + test_res = TEST(t_todo(0), "passing TEST_TODO()");
79 + TEST(t_res(1), "passing TEST_TODO() returns 1");
80 + test_res = TEST(t_todo(1), "failing TEST_TODO()");
81 + TEST(t_res(0), "failing TEST_TODO() returns 0");
82 + test_res = TEST(t_skip(), "test_skip()");
83 + TEST(check_int(test_res, ==, 1), "skipped test returns 1");
84 + test_res = TEST(t_skip_todo(), "test_skip() inside TEST_TODO()");
85 + TEST(t_res(1), "test_skip() inside TEST_TODO() returns 1");
86 + test_res = TEST(t_todo_after_fail(), "TEST_TODO() after failing check");
87 + TEST(check_int(test_res, ==, 0), "TEST_TODO() after failing check returns 0");
88 + test_res = TEST(t_fail_after_todo(), "failing check after TEST_TODO()");
89 + TEST(check_int(test_res, ==, 0), "failing check after TEST_TODO() returns 0");
90 + TEST(t_messages(), "messages from failing string and char comparison");
91 + test_res = TEST(t_empty(), "test with no checks");
92 + TEST(check_int(test_res, ==, 0), "test with no checks returns 0");
93 +
94 + return test_done();
95 +}
t/unit-tests/t-strbuf.c new
+120
@@ -0,0 +1,120 @@
1 +#include "test-lib.h"
2 +#include "strbuf.h"
3 +
4 +/* wrapper that supplies tests with an empty, initialized strbuf */
5 +static void setup(void (*f)(struct strbuf*, void*), void *data)
6 +{
7 + struct strbuf buf = STRBUF_INIT;
8 +
9 + f(&buf, data);
10 + strbuf_release(&buf);
11 + check_uint(buf.len, ==, 0);
12 + check_uint(buf.alloc, ==, 0);
13 +}
14 +
15 +/* wrapper that supplies tests with a populated, initialized strbuf */
16 +static void setup_populated(void (*f)(struct strbuf*, void*), char *init_str, void *data)
17 +{
18 + struct strbuf buf = STRBUF_INIT;
19 +
20 + strbuf_addstr(&buf, init_str);
21 + check_uint(buf.len, ==, strlen(init_str));
22 + f(&buf, data);
23 + strbuf_release(&buf);
24 + check_uint(buf.len, ==, 0);
25 + check_uint(buf.alloc, ==, 0);
26 +}
27 +
28 +static int assert_sane_strbuf(struct strbuf *buf)
29 +{
30 + /* Initialized strbufs should always have a non-NULL buffer */
31 + if (!check(!!buf->buf))
32 + return 0;
33 + /* Buffers should always be NUL-terminated */
34 + if (!check_char(buf->buf[buf->len], ==, '\0'))
35 + return 0;
36 + /*
37 + * Freshly-initialized strbufs may not have a dynamically allocated
38 + * buffer
39 + */
40 + if (buf->len == 0 && buf->alloc == 0)
41 + return 1;
42 + /* alloc must be at least one byte larger than len */
43 + return check_uint(buf->len, <, buf->alloc);
44 +}
45 +
46 +static void t_static_init(void)
47 +{
48 + struct strbuf buf = STRBUF_INIT;
49 +
50 + check_uint(buf.len, ==, 0);
51 + check_uint(buf.alloc, ==, 0);
52 + check_char(buf.buf[0], ==, '\0');
53 +}
54 +
55 +static void t_dynamic_init(void)
56 +{
57 + struct strbuf buf;
58 +
59 + strbuf_init(&buf, 1024);
60 + check(assert_sane_strbuf(&buf));
61 + check_uint(buf.len, ==, 0);
62 + check_uint(buf.alloc, >=, 1024);
63 + check_char(buf.buf[0], ==, '\0');
64 + strbuf_release(&buf);
65 +}
66 +
67 +static void t_addch(struct strbuf *buf, void *data)
68 +{
69 + const char *p_ch = data;
70 + const char ch = *p_ch;
71 + size_t orig_alloc = buf->alloc;
72 + size_t orig_len = buf->len;
73 +
74 + if (!check(assert_sane_strbuf(buf)))
75 + return;
76 + strbuf_addch(buf, ch);
77 + if (!check(assert_sane_strbuf(buf)))
78 + return;
79 + if (!(check_uint(buf->len, ==, orig_len + 1) &&
80 + check_uint(buf->alloc, >=, orig_alloc)))
81 + return; /* avoid de-referencing buf->buf */
82 + check_char(buf->buf[buf->len - 1], ==, ch);
83 + check_char(buf->buf[buf->len], ==, '\0');
84 +}
85 +
86 +static void t_addstr(struct strbuf *buf, void *data)
87 +{
88 + const char *text = data;
89 + size_t len = strlen(text);
90 + size_t orig_alloc = buf->alloc;
91 + size_t orig_len = buf->len;
92 +
93 + if (!check(assert_sane_strbuf(buf)))
94 + return;
95 + strbuf_addstr(buf, text);
96 + if (!check(assert_sane_strbuf(buf)))
97 + return;
98 + if (!(check_uint(buf->len, ==, orig_len + len) &&
99 + check_uint(buf->alloc, >=, orig_alloc) &&
100 + check_uint(buf->alloc, >, orig_len + len) &&
101 + check_char(buf->buf[orig_len + len], ==, '\0')))
102 + return;
103 + check_str(buf->buf + orig_len, text);
104 +}
105 +
106 +int cmd_main(int argc, const char **argv)
107 +{
108 + if (!TEST(t_static_init(), "static initialization works"))
109 + test_skip_all("STRBUF_INIT is broken");
110 + TEST(t_dynamic_init(), "dynamic initialization works");
111 + TEST(setup(t_addch, "a"), "strbuf_addch adds char");
112 + TEST(setup(t_addch, ""), "strbuf_addch adds NUL char");
113 + TEST(setup_populated(t_addch, "initial value", "a"),
114 + "strbuf_addch appends to initial value");
115 + TEST(setup(t_addstr, "hello there"), "strbuf_addstr adds string");
116 + TEST(setup_populated(t_addstr, "initial value", "hello there"),
117 + "strbuf_addstr appends string to initial value");
118 +
119 + return test_done();
120 +}
t/unit-tests/test-lib.c new
+330
@@ -0,0 +1,330 @@
1 +#include "test-lib.h"
2 +
3 +enum result {
4 + RESULT_NONE,
5 + RESULT_FAILURE,
6 + RESULT_SKIP,
7 + RESULT_SUCCESS,
8 + RESULT_TODO
9 +};
10 +
11 +static struct {
12 + enum result result;
13 + int count;
14 + unsigned failed :1;
15 + unsigned lazy_plan :1;
16 + unsigned running :1;
17 + unsigned skip_all :1;
18 + unsigned todo :1;
19 +} ctx = {
20 + .lazy_plan = 1,
21 + .result = RESULT_NONE,
22 +};
23 +
24 +static void msg_with_prefix(const char *prefix, const char *format, va_list ap)
25 +{
26 + fflush(stderr);
27 + if (prefix)
28 + fprintf(stdout, "%s", prefix);
29 + vprintf(format, ap); /* TODO: handle newlines */
30 + putc('\n', stdout);
31 + fflush(stdout);
32 +}
33 +
34 +void test_msg(const char *format, ...)
35 +{
36 + va_list ap;
37 +
38 + va_start(ap, format);
39 + msg_with_prefix("# ", format, ap);
40 + va_end(ap);
41 +}
42 +
43 +void test_plan(int count)
44 +{
45 + assert(!ctx.running);
46 +
47 + fflush(stderr);
48 + printf("1..%d\n", count);
49 + fflush(stdout);
50 + ctx.lazy_plan = 0;
51 +}
52 +
53 +int test_done(void)
54 +{
55 + assert(!ctx.running);
56 +
57 + if (ctx.lazy_plan)
58 + test_plan(ctx.count);
59 +
60 + return ctx.failed;
61 +}
62 +
63 +void test_skip(const char *format, ...)
64 +{
65 + va_list ap;
66 +
67 + assert(ctx.running);
68 +
69 + ctx.result = RESULT_SKIP;
70 + va_start(ap, format);
71 + if (format)
72 + msg_with_prefix("# skipping test - ", format, ap);
73 + va_end(ap);
74 +}
75 +
76 +void test_skip_all(const char *format, ...)
77 +{
78 + va_list ap;
79 + const char *prefix;
80 +
81 + if (!ctx.count && ctx.lazy_plan) {
82 + /* We have not printed a test plan yet */
83 + prefix = "1..0 # SKIP ";
84 + ctx.lazy_plan = 0;
85 + } else {
86 + /* We have already printed a test plan */
87 + prefix = "Bail out! # ";
88 + ctx.failed = 1;
89 + }
90 + ctx.skip_all = 1;
91 + ctx.result = RESULT_SKIP;
92 + va_start(ap, format);
93 + msg_with_prefix(prefix, format, ap);
94 + va_end(ap);
95 +}
96 +
97 +int test__run_begin(void)
98 +{
99 + assert(!ctx.running);
100 +
101 + ctx.count++;
102 + ctx.result = RESULT_NONE;
103 + ctx.running = 1;
104 +
105 + return ctx.skip_all;
106 +}
107 +
108 +static void print_description(const char *format, va_list ap)
109 +{
110 + if (format) {
111 + fputs(" - ", stdout);
112 + vprintf(format, ap);
113 + }
114 +}
115 +
116 +int test__run_end(int was_run UNUSED, const char *location, const char *format, ...)
117 +{
118 + va_list ap;
119 +
120 + assert(ctx.running);
121 + assert(!ctx.todo);
122 +
123 + fflush(stderr);
124 + va_start(ap, format);
125 + if (!ctx.skip_all) {
126 + switch (ctx.result) {
127 + case RESULT_SUCCESS:
128 + printf("ok %d", ctx.count);
129 + print_description(format, ap);
130 + break;
131 +
132 + case RESULT_FAILURE:
133 + printf("not ok %d", ctx.count);
134 + print_description(format, ap);
135 + break;
136 +
137 + case RESULT_TODO:
138 + printf("not ok %d", ctx.count);
139 + print_description(format, ap);
140 + printf(" # TODO");
141 + break;
142 +
143 + case RESULT_SKIP:
144 + printf("ok %d", ctx.count);
145 + print_description(format, ap);
146 + printf(" # SKIP");
147 + break;
148 +
149 + case RESULT_NONE:
150 + test_msg("BUG: test has no checks at %s", location);
151 + printf("not ok %d", ctx.count);
152 + print_description(format, ap);
153 + ctx.result = RESULT_FAILURE;
154 + break;
155 + }
156 + }
157 + va_end(ap);
158 + ctx.running = 0;
159 + if (ctx.skip_all)
160 + return 1;
161 + putc('\n', stdout);
162 + fflush(stdout);
163 + ctx.failed |= ctx.result == RESULT_FAILURE;
164 +
165 + return ctx.result != RESULT_FAILURE;
166 +}
167 +
168 +static void test_fail(void)
169 +{
170 + assert(ctx.result != RESULT_SKIP);
171 +
172 + ctx.result = RESULT_FAILURE;
173 +}
174 +
175 +static void test_pass(void)
176 +{
177 + assert(ctx.result != RESULT_SKIP);
178 +
179 + if (ctx.result == RESULT_NONE)
180 + ctx.result = RESULT_SUCCESS;
181 +}
182 +
183 +static void test_todo(void)
184 +{
185 + assert(ctx.result != RESULT_SKIP);
186 +
187 + if (ctx.result != RESULT_FAILURE)
188 + ctx.result = RESULT_TODO;
189 +}
190 +
191 +int test_assert(const char *location, const char *check, int ok)
192 +{
193 + assert(ctx.running);
194 +
195 + if (ctx.result == RESULT_SKIP) {
196 + test_msg("skipping check '%s' at %s", check, location);
197 + return 1;
198 + }
199 + if (!ctx.todo) {
200 + if (ok) {
201 + test_pass();
202 + } else {
203 + test_msg("check \"%s\" failed at %s", check, location);
204 + test_fail();
205 + }
206 + }
207 +
208 + return !!ok;
209 +}
210 +
211 +void test__todo_begin(void)
212 +{
213 + assert(ctx.running);
214 + assert(!ctx.todo);
215 +
216 + ctx.todo = 1;
217 +}
218 +
219 +int test__todo_end(const char *location, const char *check, int res)
220 +{
221 + assert(ctx.running);
222 + assert(ctx.todo);
223 +
224 + ctx.todo = 0;
225 + if (ctx.result == RESULT_SKIP)
226 + return 1;
227 + if (res) {
228 + test_msg("todo check '%s' succeeded at %s", check, location);
229 + test_fail();
230 + } else {
231 + test_todo();
232 + }
233 +
234 + return !res;
235 +}
236 +
237 +int check_bool_loc(const char *loc, const char *check, int ok)
238 +{
239 + return test_assert(loc, check, ok);
240 +}
241 +
242 +union test__tmp test__tmp[2];
243 +
244 +int check_int_loc(const char *loc, const char *check, int ok,
245 + intmax_t a, intmax_t b)
246 +{
247 + int ret = test_assert(loc, check, ok);
248 +
249 + if (!ret) {
250 + test_msg(" left: %"PRIdMAX, a);
251 + test_msg(" right: %"PRIdMAX, b);
252 + }
253 +
254 + return ret;
255 +}
256 +
257 +int check_uint_loc(const char *loc, const char *check, int ok,
258 + uintmax_t a, uintmax_t b)
259 +{
260 + int ret = test_assert(loc, check, ok);
261 +
262 + if (!ret) {
263 + test_msg(" left: %"PRIuMAX, a);
264 + test_msg(" right: %"PRIuMAX, b);
265 + }
266 +
267 + return ret;
268 +}
269 +
270 +static void print_one_char(char ch, char quote)
271 +{
272 + if ((unsigned char)ch < 0x20u || ch == 0x7f) {
273 + /* TODO: improve handling of \a, \b, \f ... */
274 + printf("\\%03o", (unsigned char)ch);
275 + } else {
276 + if (ch == '\\' || ch == quote)
277 + putc('\\', stdout);
278 + putc(ch, stdout);
279 + }
280 +}
281 +
282 +static void print_char(const char *prefix, char ch)
283 +{
284 + printf("# %s: '", prefix);
285 + print_one_char(ch, '\'');
286 + fputs("'\n", stdout);
287 +}
288 +
289 +int check_char_loc(const char *loc, const char *check, int ok, char a, char b)
290 +{
291 + int ret = test_assert(loc, check, ok);
292 +
293 + if (!ret) {
294 + fflush(stderr);
295 + print_char(" left", a);
296 + print_char(" right", b);
297 + fflush(stdout);
298 + }
299 +
300 + return ret;
301 +}
302 +
303 +static void print_str(const char *prefix, const char *str)
304 +{
305 + printf("# %s: ", prefix);
306 + if (!str) {
307 + fputs("NULL\n", stdout);
308 + } else {
309 + putc('"', stdout);
310 + while (*str)
311 + print_one_char(*str++, '"');
312 + fputs("\"\n", stdout);
313 + }
314 +}
315 +
316 +int check_str_loc(const char *loc, const char *check,
317 + const char *a, const char *b)
318 +{
319 + int ok = (!a && !b) || (a && b && !strcmp(a, b));
320 + int ret = test_assert(loc, check, ok);
321 +
322 + if (!ret) {
323 + fflush(stderr);
324 + print_str(" left", a);
325 + print_str(" right", b);
326 + fflush(stdout);
327 + }
328 +
329 + return ret;
330 +}
t/unit-tests/test-lib.h new
+149
@@ -0,0 +1,149 @@
1 +#ifndef TEST_LIB_H
2 +#define TEST_LIB_H
3 +
4 +#include "git-compat-util.h"
5 +
6 +/*
7 + * Run a test function, returns 1 if the test succeeds, 0 if it
8 + * fails. If test_skip_all() has been called then the test will not be
9 + * run. The description for each test should be unique. For example:
10 + *
11 + * TEST(test_something(arg1, arg2), "something %d %d", arg1, arg2)
12 + */
13 +#define TEST(t, ...) \
14 + test__run_end(test__run_begin() ? 0 : (t, 1), \
15 + TEST_LOCATION(), __VA_ARGS__)
16 +
17 +/*
18 + * Print a test plan, should be called before any tests. If the number
19 + * of tests is not known in advance test_done() will automatically
20 + * print a plan at the end of the test program.
21 + */
22 +void test_plan(int count);
23 +
24 +/*
25 + * test_done() must be called at the end of main(). It will print the
26 + * plan if plan() was not called at the beginning of the test program
27 + * and returns the exit code for the test program.
28 + */
29 +int test_done(void);
30 +
31 +/* Skip the current test. */
32 +__attribute__((format (printf, 1, 2)))
33 +void test_skip(const char *format, ...);
34 +
35 +/* Skip all remaining tests. */
36 +__attribute__((format (printf, 1, 2)))
37 +void test_skip_all(const char *format, ...);
38 +
39 +/* Print a diagnostic message to stdout. */
40 +__attribute__((format (printf, 1, 2)))
41 +void test_msg(const char *format, ...);
42 +
43 +/*
44 + * Test checks are built around test_assert(). checks return 1 on
45 + * success, 0 on failure. If any check fails then the test will fail. To
46 + * create a custom check define a function that wraps test_assert() and
47 + * a macro to wrap that function to provide a source location and
48 + * stringified arguments. Custom checks that take pointer arguments
49 + * should be careful to check that they are non-NULL before
50 + * dereferencing them. For example:
51 + *
52 + * static int check_oid_loc(const char *loc, const char *check,
53 + * struct object_id *a, struct object_id *b)
54 + * {
55 + * int res = test_assert(loc, check, a && b && oideq(a, b));
56 + *
57 + * if (!res) {
58 + * test_msg(" left: %s", a ? oid_to_hex(a) : "NULL";
59 + * test_msg(" right: %s", b ? oid_to_hex(a) : "NULL";
60 + *
61 + * }
62 + * return res;
63 + * }
64 + *
65 + * #define check_oid(a, b) \
66 + * check_oid_loc(TEST_LOCATION(), "oideq("#a", "#b")", a, b)
67 + */
68 +int test_assert(const char *location, const char *check, int ok);
69 +
70 +/* Helper macro to pass the location to checks */
71 +#define TEST_LOCATION() TEST__MAKE_LOCATION(__LINE__)
72 +
73 +/* Check a boolean condition. */
74 +#define check(x) \
75 + check_bool_loc(TEST_LOCATION(), #x, x)
76 +int check_bool_loc(const char *loc, const char *check, int ok);
77 +
78 +/*
79 + * Compare two integers. Prints a message with the two values if the
80 + * comparison fails. NB this is not thread safe.
81 + */
82 +#define check_int(a, op, b) \
83 + (test__tmp[0].i = (a), test__tmp[1].i = (b), \
84 + check_int_loc(TEST_LOCATION(), #a" "#op" "#b, \
85 + test__tmp[0].i op test__tmp[1].i, \
86 + test__tmp[0].i, test__tmp[1].i))
87 +int check_int_loc(const char *loc, const char *check, int ok,
88 + intmax_t a, intmax_t b);
89 +
90 +/*
91 + * Compare two unsigned integers. Prints a message with the two values
92 + * if the comparison fails. NB this is not thread safe.
93 + */
94 +#define check_uint(a, op, b) \
95 + (test__tmp[0].u = (a), test__tmp[1].u = (b), \
96 + check_uint_loc(TEST_LOCATION(), #a" "#op" "#b, \
97 + test__tmp[0].u op test__tmp[1].u, \
98 + test__tmp[0].u, test__tmp[1].u))
99 +int check_uint_loc(const char *loc, const char *check, int ok,
100 + uintmax_t a, uintmax_t b);
101 +
102 +/*
103 + * Compare two chars. Prints a message with the two values if the
104 + * comparison fails. NB this is not thread safe.
105 + */
106 +#define check_char(a, op, b) \
107 + (test__tmp[0].c = (a), test__tmp[1].c = (b), \
108 + check_char_loc(TEST_LOCATION(), #a" "#op" "#b, \
109 + test__tmp[0].c op test__tmp[1].c, \
110 + test__tmp[0].c, test__tmp[1].c))
111 +int check_char_loc(const char *loc, const char *check, int ok,
112 + char a, char b);
113 +
114 +/* Check whether two strings are equal. */
115 +#define check_str(a, b) \
116 + check_str_loc(TEST_LOCATION(), "!strcmp("#a", "#b")", a, b)
117 +int check_str_loc(const char *loc, const char *check,
118 + const char *a, const char *b);
119 +
120 +/*
121 + * Wrap a check that is known to fail. If the check succeeds then the
122 + * test will fail. Returns 1 if the check fails, 0 if it
123 + * succeeds. For example:
124 + *
125 + * TEST_TODO(check(0));
126 + */
127 +#define TEST_TODO(check) \
128 + (test__todo_begin(), test__todo_end(TEST_LOCATION(), #check, check))
129 +
130 +/* Private helpers */
131 +
132 +#define TEST__STR(x) #x
133 +#define TEST__MAKE_LOCATION(line) __FILE__ ":" TEST__STR(line)
134 +
135 +union test__tmp {
136 + intmax_t i;
137 + uintmax_t u;
138 + char c;
139 +};
140 +
141 +extern union test__tmp test__tmp[2];
142 +
143 +int test__run_begin(void);
144 +__attribute__((format (printf, 3, 4)))
145 +int test__run_end(int, const char *, const char *, ...);
146 +void test__todo_begin(void);
147 +int test__todo_end(const char *, const char *, int);
148 +
149 +#endif /* TEST_LIB_H */