git/t/unit-tests/unit-test.c
Patrick Steinhardt 3d5d4c876a t/unit-tests: implement test driver
The test driver in "unit-test.c" is responsible for setting up our unit
tests and eventually running them. As such, it is also responsible for
parsing the command line arguments.

The clar unit testing framework provides function `clar_test()` that
parses command line arguments and then executes the tests for us. In
theory that would already be sufficient. We have the special requirement
to always generate TAP-formatted output though, so we'd have to always
pass the "-t" argument to clar. Furthermore, some of the options exposed
by clar are ineffective when "-t" is used, but they would still be shown
when the user passes the "-h" parameter to have the clar show its usage.

Implement our own option handling instead of using the one provided by
clar, which gives us greater flexibility in how exactly we set things
up.

We would ideally not use any "normal" code of ours for this such that
the unit testing framework doesn't depend on it working correctly. But
it is somewhat dubious whether we really want to reimplement all of the
option parsing. So for now, let's be pragmatic and reuse it until we
find a good reason in the future why we'd really want to avoid it.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
2024-09-04 08:41:37 -07:00

47 lines
1.3 KiB
C

#include "unit-test.h"
#include "parse-options.h"
#include "string-list.h"
#include "strvec.h"
static const char * const unit_test_usage[] = {
N_("unit-test [<options>]"),
NULL,
};
int cmd_main(int argc, const char **argv)
{
struct string_list run_args = STRING_LIST_INIT_NODUP;
struct string_list exclude_args = STRING_LIST_INIT_NODUP;
int immediate = 0;
struct option options[] = {
OPT_BOOL('i', "immediate", &immediate,
N_("immediately exit upon the first failed test")),
OPT_STRING_LIST('r', "run", &run_args, N_("suite[::test]"),
N_("run only test suite or individual test <suite[::test]>")),
OPT_STRING_LIST('x', "exclude", &exclude_args, N_("suite"),
N_("exclude test suite <suite>")),
OPT_END(),
};
struct strvec args = STRVEC_INIT;
int ret;
argc = parse_options(argc, argv, NULL, options,
unit_test_usage, PARSE_OPT_KEEP_ARGV0);
if (argc > 1)
usagef(_("extra command line parameter '%s'"), argv[0]);
strvec_push(&args, argv[0]);
strvec_push(&args, "-t");
if (immediate)
strvec_push(&args, "-Q");
for (size_t i = 0; i < run_args.nr; i++)
strvec_pushf(&args, "-s%s", run_args.items[i].string);
for (size_t i = 0; i < exclude_args.nr; i++)
strvec_pushf(&args, "-x%s", exclude_args.items[i].string);
ret = clar_test(args.nr, (char **) args.v);
string_list_clear(&run_args, 0);
strvec_clear(&args);
return ret;
}