Skip to content

Commit

Permalink
unit tests: add TAP unit test framework
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
phillipwood authored and gitster committed Nov 9, 2023
1 parent 581790e commit e137fe3
Show file tree
Hide file tree
Showing 8 changed files with 792 additions and 4 deletions.
28 changes: 25 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,9 @@ TEST_BUILTINS_OBJS =
TEST_OBJS =
TEST_PROGRAMS_NEED_X =
THIRD_PARTY_SOURCES =
UNIT_TEST_PROGRAMS =
UNIT_TEST_DIR = t/unit-tests
UNIT_TEST_BIN = $(UNIT_TEST_DIR)/bin

# Having this variable in your environment would break pipelines because
# you cause "cd" to echo its destination to stdout. It can also take
Expand Down Expand Up @@ -1331,6 +1334,12 @@ THIRD_PARTY_SOURCES += compat/regex/%
THIRD_PARTY_SOURCES += sha1collisiondetection/%
THIRD_PARTY_SOURCES += sha1dc/%

UNIT_TEST_PROGRAMS += t-basic
UNIT_TEST_PROGRAMS += t-strbuf
UNIT_TEST_PROGS = $(patsubst %,$(UNIT_TEST_BIN)/%$X,$(UNIT_TEST_PROGRAMS))
UNIT_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(UNIT_TEST_PROGRAMS))
UNIT_TEST_OBJS += $(UNIT_TEST_DIR)/test-lib.o

# xdiff and reftable libs may in turn depend on what is in libgit.a
GITLIBS = common-main.o $(LIB_FILE) $(XDIFF_LIB) $(REFTABLE_LIB) $(LIB_FILE)
EXTLIBS =
Expand Down Expand Up @@ -2672,6 +2681,7 @@ OBJECTS += $(TEST_OBJS)
OBJECTS += $(XDIFF_OBJS)
OBJECTS += $(FUZZ_OBJS)
OBJECTS += $(REFTABLE_OBJS) $(REFTABLE_TEST_OBJS)
OBJECTS += $(UNIT_TEST_OBJS)

ifndef NO_CURL
OBJECTS += http.o http-walker.o remote-curl.o
Expand Down Expand Up @@ -3167,7 +3177,7 @@ endif

test_bindir_programs := $(patsubst %,bin-wrappers/%,$(BINDIR_PROGRAMS_NEED_X) $(BINDIR_PROGRAMS_NO_X) $(TEST_PROGRAMS_NEED_X))

all:: $(TEST_PROGRAMS) $(test_bindir_programs)
all:: $(TEST_PROGRAMS) $(test_bindir_programs) $(UNIT_TEST_PROGS)

bin-wrappers/%: wrap-for-bin.sh
$(call mkdir_p_parent_template)
Expand Down Expand Up @@ -3592,7 +3602,7 @@ endif

artifacts-tar:: $(ALL_COMMANDS_TO_INSTALL) $(SCRIPT_LIB) $(OTHER_PROGRAMS) \
GIT-BUILD-OPTIONS $(TEST_PROGRAMS) $(test_bindir_programs) \
$(MOFILES)
$(UNIT_TEST_PROGS) $(MOFILES)
$(QUIET_SUBDIR0)templates $(QUIET_SUBDIR1) \
SHELL_PATH='$(SHELL_PATH_SQ)' PERL_PATH='$(PERL_PATH_SQ)'
test -n "$(ARTIFACTS_DIRECTORY)"
Expand Down Expand Up @@ -3653,7 +3663,7 @@ clean: profile-clean coverage-clean cocciclean
$(RM) $(OBJECTS)
$(RM) $(LIB_FILE) $(XDIFF_LIB) $(REFTABLE_LIB) $(REFTABLE_TEST_LIB)
$(RM) $(ALL_PROGRAMS) $(SCRIPT_LIB) $(BUILT_INS) $(OTHER_PROGRAMS)
$(RM) $(TEST_PROGRAMS)
$(RM) $(TEST_PROGRAMS) $(UNIT_TEST_PROGS)
$(RM) $(FUZZ_PROGRAMS)
$(RM) $(SP_OBJ)
$(RM) $(HCC)
Expand Down Expand Up @@ -3831,3 +3841,15 @@ $(FUZZ_PROGRAMS): all
$(XDIFF_OBJS) $(EXTLIBS) git.o $@.o $(LIB_FUZZING_ENGINE) -o $@

fuzz-all: $(FUZZ_PROGRAMS)

$(UNIT_TEST_BIN):
@mkdir -p $(UNIT_TEST_BIN)

$(UNIT_TEST_PROGS): $(UNIT_TEST_BIN)/%$X: $(UNIT_TEST_DIR)/%.o $(UNIT_TEST_DIR)/test-lib.o $(GITLIBS) GIT-LDFLAGS $(UNIT_TEST_BIN)
$(QUIET_LINK)$(CC) $(ALL_CFLAGS) -o $@ $(ALL_LDFLAGS) \
$(filter %.o,$^) $(filter %.a,$^) $(LIBS)

.PHONY: build-unit-tests unit-tests
build-unit-tests: $(UNIT_TEST_PROGS)
unit-tests: $(UNIT_TEST_PROGS)
$(MAKE) -C t/ unit-tests
15 changes: 14 additions & 1 deletion t/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ TAR ?= $(TAR)
RM ?= rm -f
PROVE ?= prove
DEFAULT_TEST_TARGET ?= test
DEFAULT_UNIT_TEST_TARGET ?= unit-tests-raw
TEST_LINT ?= test-lint

ifdef TEST_OUTPUT_DIRECTORY
Expand All @@ -41,6 +42,7 @@ TPERF = $(sort $(wildcard perf/p[0-9][0-9][0-9][0-9]-*.sh))
TINTEROP = $(sort $(wildcard interop/i[0-9][0-9][0-9][0-9]-*.sh))
CHAINLINTTESTS = $(sort $(patsubst chainlint/%.test,%,$(wildcard chainlint/*.test)))
CHAINLINT = '$(PERL_PATH_SQ)' chainlint.pl
UNIT_TESTS = $(sort $(filter-out unit-tests/bin/t-basic%,$(wildcard unit-tests/bin/t-*)))

# `test-chainlint` (which is a dependency of `test-lint`, `test` and `prove`)
# checks all tests in all scripts via a single invocation, so tell individual
Expand All @@ -65,6 +67,17 @@ prove: pre-clean check-chainlint $(TEST_LINT)
$(T):
@echo "*** $@ ***"; '$(TEST_SHELL_PATH_SQ)' $@ $(GIT_TEST_OPTS)

$(UNIT_TESTS):
@echo "*** $@ ***"; $@

.PHONY: unit-tests unit-tests-raw unit-tests-prove
unit-tests: $(DEFAULT_UNIT_TEST_TARGET)

unit-tests-raw: $(UNIT_TESTS)

unit-tests-prove:
@echo "*** prove - unit tests ***"; $(PROVE) $(GIT_PROVE_OPTS) $(UNIT_TESTS)

pre-clean:
$(RM) -r '$(TEST_RESULTS_DIRECTORY_SQ)'

Expand Down Expand Up @@ -149,4 +162,4 @@ perf:
$(MAKE) -C perf/ all

.PHONY: pre-clean $(T) aggregate-results clean valgrind perf \
check-chainlint clean-chainlint test-chainlint
check-chainlint clean-chainlint test-chainlint $(UNIT_TESTS)
58 changes: 58 additions & 0 deletions t/t0080-unit-test-output.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#!/bin/sh

test_description='Test the output of the unit test framework'

. ./test-lib.sh

test_expect_success 'TAP output from unit tests' '
cat >expect <<-EOF &&
ok 1 - passing test
ok 2 - passing test and assertion return 1
# check "1 == 2" failed at t/unit-tests/t-basic.c:76
# left: 1
# right: 2
not ok 3 - failing test
ok 4 - failing test and assertion return 0
not ok 5 - passing TEST_TODO() # TODO
ok 6 - passing TEST_TODO() returns 1
# todo check ${SQ}check(x)${SQ} succeeded at t/unit-tests/t-basic.c:25
not ok 7 - failing TEST_TODO()
ok 8 - failing TEST_TODO() returns 0
# check "0" failed at t/unit-tests/t-basic.c:30
# skipping test - missing prerequisite
# skipping check ${SQ}1${SQ} at t/unit-tests/t-basic.c:32
ok 9 - test_skip() # SKIP
ok 10 - skipped test returns 1
# skipping test - missing prerequisite
ok 11 - test_skip() inside TEST_TODO() # SKIP
ok 12 - test_skip() inside TEST_TODO() returns 1
# check "0" failed at t/unit-tests/t-basic.c:48
not ok 13 - TEST_TODO() after failing check
ok 14 - TEST_TODO() after failing check returns 0
# check "0" failed at t/unit-tests/t-basic.c:56
not ok 15 - failing check after TEST_TODO()
ok 16 - failing check after TEST_TODO() returns 0
# check "!strcmp("\thello\\\\", "there\"\n")" failed at t/unit-tests/t-basic.c:61
# left: "\011hello\\\\"
# right: "there\"\012"
# check "!strcmp("NULL", NULL)" failed at t/unit-tests/t-basic.c:62
# left: "NULL"
# right: NULL
# check "${SQ}a${SQ} == ${SQ}\n${SQ}" failed at t/unit-tests/t-basic.c:63
# left: ${SQ}a${SQ}
# right: ${SQ}\012${SQ}
# check "${SQ}\\\\${SQ} == ${SQ}\\${SQ}${SQ}" failed at t/unit-tests/t-basic.c:64
# left: ${SQ}\\\\${SQ}
# right: ${SQ}\\${SQ}${SQ}
not ok 17 - messages from failing string and char comparison
# BUG: test has no checks at t/unit-tests/t-basic.c:91
not ok 18 - test with no checks
ok 19 - test with no checks returns 0
1..19
EOF
! "$GIT_BUILD_DIR"/t/unit-tests/bin/t-basic >actual &&
test_cmp expect actual
'

test_done
1 change: 1 addition & 0 deletions t/unit-tests/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/bin
95 changes: 95 additions & 0 deletions t/unit-tests/t-basic.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#include "test-lib.h"

/*
* The purpose of this "unit test" is to verify a few invariants of the unit
* test framework itself, as well as to provide examples of output from actually
* failing tests. As such, it is intended that this test fails, and thus it
* should not be run as part of `make unit-tests`. Instead, we verify it behaves
* as expected in the integration test t0080-unit-test-output.sh
*/

/* Used to store the return value of check_int(). */
static int check_res;

/* Used to store the return value of TEST(). */
static int test_res;

static void t_res(int expect)
{
check_int(check_res, ==, expect);
check_int(test_res, ==, expect);
}

static void t_todo(int x)
{
check_res = TEST_TODO(check(x));
}

static void t_skip(void)
{
check(0);
test_skip("missing prerequisite");
check(1);
}

static int do_skip(void)
{
test_skip("missing prerequisite");
return 1;
}

static void t_skip_todo(void)
{
check_res = TEST_TODO(do_skip());
}

static void t_todo_after_fail(void)
{
check(0);
TEST_TODO(check(0));
}

static void t_fail_after_todo(void)
{
check(1);
TEST_TODO(check(0));
check(0);
}

static void t_messages(void)
{
check_str("\thello\\", "there\"\n");
check_str("NULL", NULL);
check_char('a', ==, '\n');
check_char('\\', ==, '\'');
}

static void t_empty(void)
{
; /* empty */
}

int cmd_main(int argc, const char **argv)
{
test_res = TEST(check_res = check_int(1, ==, 1), "passing test");
TEST(t_res(1), "passing test and assertion return 1");
test_res = TEST(check_res = check_int(1, ==, 2), "failing test");
TEST(t_res(0), "failing test and assertion return 0");
test_res = TEST(t_todo(0), "passing TEST_TODO()");
TEST(t_res(1), "passing TEST_TODO() returns 1");
test_res = TEST(t_todo(1), "failing TEST_TODO()");
TEST(t_res(0), "failing TEST_TODO() returns 0");
test_res = TEST(t_skip(), "test_skip()");
TEST(check_int(test_res, ==, 1), "skipped test returns 1");
test_res = TEST(t_skip_todo(), "test_skip() inside TEST_TODO()");
TEST(t_res(1), "test_skip() inside TEST_TODO() returns 1");
test_res = TEST(t_todo_after_fail(), "TEST_TODO() after failing check");
TEST(check_int(test_res, ==, 0), "TEST_TODO() after failing check returns 0");
test_res = TEST(t_fail_after_todo(), "failing check after TEST_TODO()");
TEST(check_int(test_res, ==, 0), "failing check after TEST_TODO() returns 0");
TEST(t_messages(), "messages from failing string and char comparison");
test_res = TEST(t_empty(), "test with no checks");
TEST(check_int(test_res, ==, 0), "test with no checks returns 0");

return test_done();
}
120 changes: 120 additions & 0 deletions t/unit-tests/t-strbuf.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
#include "test-lib.h"
#include "strbuf.h"

/* wrapper that supplies tests with an empty, initialized strbuf */
static void setup(void (*f)(struct strbuf*, void*), void *data)
{
struct strbuf buf = STRBUF_INIT;

f(&buf, data);
strbuf_release(&buf);
check_uint(buf.len, ==, 0);
check_uint(buf.alloc, ==, 0);
}

/* wrapper that supplies tests with a populated, initialized strbuf */
static void setup_populated(void (*f)(struct strbuf*, void*), char *init_str, void *data)
{
struct strbuf buf = STRBUF_INIT;

strbuf_addstr(&buf, init_str);
check_uint(buf.len, ==, strlen(init_str));
f(&buf, data);
strbuf_release(&buf);
check_uint(buf.len, ==, 0);
check_uint(buf.alloc, ==, 0);
}

static int assert_sane_strbuf(struct strbuf *buf)
{
/* Initialized strbufs should always have a non-NULL buffer */
if (!check(!!buf->buf))
return 0;
/* Buffers should always be NUL-terminated */
if (!check_char(buf->buf[buf->len], ==, '\0'))
return 0;
/*
* Freshly-initialized strbufs may not have a dynamically allocated
* buffer
*/
if (buf->len == 0 && buf->alloc == 0)
return 1;
/* alloc must be at least one byte larger than len */
return check_uint(buf->len, <, buf->alloc);
}

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');
}

static void t_dynamic_init(void)
{
struct strbuf buf;

strbuf_init(&buf, 1024);
check(assert_sane_strbuf(&buf));
check_uint(buf.len, ==, 0);
check_uint(buf.alloc, >=, 1024);
check_char(buf.buf[0], ==, '\0');
strbuf_release(&buf);
}

static void t_addch(struct strbuf *buf, void *data)
{
const char *p_ch = data;
const char ch = *p_ch;
size_t orig_alloc = buf->alloc;
size_t orig_len = buf->len;

if (!check(assert_sane_strbuf(buf)))
return;
strbuf_addch(buf, ch);
if (!check(assert_sane_strbuf(buf)))
return;
if (!(check_uint(buf->len, ==, orig_len + 1) &&
check_uint(buf->alloc, >=, orig_alloc)))
return; /* avoid de-referencing buf->buf */
check_char(buf->buf[buf->len - 1], ==, ch);
check_char(buf->buf[buf->len], ==, '\0');
}

static void t_addstr(struct strbuf *buf, void *data)
{
const char *text = data;
size_t len = strlen(text);
size_t orig_alloc = buf->alloc;
size_t orig_len = buf->len;

if (!check(assert_sane_strbuf(buf)))
return;
strbuf_addstr(buf, text);
if (!check(assert_sane_strbuf(buf)))
return;
if (!(check_uint(buf->len, ==, orig_len + len) &&
check_uint(buf->alloc, >=, orig_alloc) &&
check_uint(buf->alloc, >, orig_len + len) &&
check_char(buf->buf[orig_len + len], ==, '\0')))
return;
check_str(buf->buf + orig_len, text);
}

int cmd_main(int argc, const char **argv)
{
if (!TEST(t_static_init(), "static initialization works"))
test_skip_all("STRBUF_INIT is broken");
TEST(t_dynamic_init(), "dynamic initialization works");
TEST(setup(t_addch, "a"), "strbuf_addch adds char");
TEST(setup(t_addch, ""), "strbuf_addch adds NUL char");
TEST(setup_populated(t_addch, "initial value", "a"),
"strbuf_addch appends to initial value");
TEST(setup(t_addstr, "hello there"), "strbuf_addstr adds string");
TEST(setup_populated(t_addstr, "initial value", "hello there"),
"strbuf_addstr appends string to initial value");

return test_done();
}
Loading

0 comments on commit e137fe3

Please sign in to comment.