aboutsummaryrefslogtreecommitdiffhomepage
path: root/src-common/unittest/unittest.c
blob: c866007b634aeb6cf9e9eb50a48f1f0f1ffd6968 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222

/*

  unittest.c -- Simple "library" for unit tests

  Copyright © 2016-2024 Samuel Lidén Borell <samuel@kodafritt.se>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

#include <stdlib.h>
#include <stdarg.h>
#include <setjmp.h>
#include <string.h>

#include "unittest.h"

#define MAX_FUNCTION_ERRORS 100

const char *current_file;
const char *current_function;
static const TestFunctionInfo *fi;
static jmp_buf failjump;

static int test_errors = 0;
int errors_testcase = 0;
int testcase_aborted = 0;

int quiet = 0;
int verbose = 0;
int crash_test_only = 0;

char before_test_ptrval[] = { 'A', '\0' };
char after_test_ptrval[] = { 'B', '\0' };

static void (*beforetest_func)(void);
static void (*aftertest_func)(void);

/** If non-NULL, run only the named tests */
static char **named = NULL;
static int tests_run = 0;

/**
 * Determines if the gives test case should run (1) or not (0).
 */
static int filter(const char *name)
{
    char **np;
    if (!named) return 1;
    for (np = named; *np; np++) { if (!strcmp(name, *np)) return 1; }
    return 0;
}

void run_test(void)
{
    testcase_aborted = 0;
    if (setjmp(failjump) == 0) {
        if (beforetest_func) beforetest_func();
        fi->function();
        if (aftertest_func && !crash_test_only) aftertest_func();
    } else {
        testcase_aborted = 1;
    }
}

/** Runs all tests in a given file/list.
    The list must end with TEST_END. */
void test_file(const char *filename, const TestFunctionInfo *tests)
{
    current_file = filename;
    beforetest_func = NULL;
    aftertest_func = NULL;
    for (fi = tests; fi->name != NULL; fi++) {
        if (fi->name == before_test_ptrval) {
            beforetest_func = fi->function;
            continue;
        }
        if (fi->name == after_test_ptrval) {
            aftertest_func = fi->function;
            continue;
        }
        if (!filter(fi->name)) continue;
        tests_run++;
        current_function = fi->name;
        errors_testcase = 0;
        if (verbose) {
            const char *extra = verbose_extra_text();
            fprintf(stderr, "======== %s#%3d [%s] %s ========\n",
                    extra?extra:"", tests_run, filename, current_function);
        }
        test_handler();
    }
}

void tprintf(const char *format, ...)
{
    if (!quiet && !crash_test_only) {
        va_list ap;
        va_start(ap, format);
        vfprintf(stderr, format, ap);
        va_end(ap);
    }
}

UNITTEST_NORETURN void tfail_(const char *filename, int line, const char *msg)
{
    tsoftfail_(filename, line, msg, 0);
    longjmp(failjump, 1);
}

int tsoftfail_(const char *filename, int line, const char *msg, int ok)
{
    if (ok) return 1;
    test_errors++;
    errors_testcase++;
    if (!crash_test_only) {
        if (!quiet) {
            fprintf(stderr, "TEST FAILURE: %s:%d: %s:%s %s\n",
                    filename, line, current_function,
                    error_extra_text(), msg);
        }
        if (errors_testcase >= MAX_FUNCTION_ERRORS) {
            if (!quiet) {
                fprintf(stderr, "Too many errors. Aborting test case '%s'.\n",
                        current_function);
            }
            longjmp(failjump, 1);
        }
    }
    return 0;
}

static const char usage_text[] =
    "usage: %s [-q] [-v] [TEST NAME...]\n"
    "\n"
    "%s%s"
    "Run it without parameters to run all tests, or specify one or more\n"
    "test function names to only run those functions.\n"
    "\n"
    "Options:\n"
    "    -q  Quiet mode. Do not print test failures.\n"
    "    -v  Verbose mode. Print name of tests being run.\n"
    "\n"
    "If all tests are successful, it will not output anything. On error it\n"
    "prints failed tests to standard error (or crashes) and exits with\n"
    "failure status.\n"
    "\n";

static void show_help(const char *progname)
{
    const char *helpextra = help_extra_text();
    fprintf(stderr, usage_text, progname,
            helpextra?helpextra:"", helpextra?"\n":"");
}

int test_main(int argc, char **argv)
{
    int tests_specified = 0;
    if (argc > 1) {
        char **argp = &argv[1];
        int argsleft = argc-1;
        named = argp;
        for (; *argp; argp++) {
            const char *arg = *argp;
            argsleft--;
            if (arg[0] == '-') {
                if (arg[1] == '-') {
                    if (!arg[2]) {
                        tests_specified += argsleft;
                        break;
                    } else if (!strcmp(arg+2, "help")) {
                        show_help(argv[0]);
                        return 0;
                    } else goto bad_usage;
                } else if (arg[1] == '\0') goto bad_usage;
                arg++;
                for (; *arg; arg++) {
                    if (*arg == 'q') {
                        if (++quiet > 1) goto bad_usage;
                    }
                    else if (*arg == 'v') {
                        if (++verbose > 2) goto bad_usage;
                    } else if (*arg == 'h') {
                        show_help(argv[0]);
                        return 0;
                    } else goto bad_usage;
                }
                continue;
              bad_usage:
                show_help(argv[0]);
                return 2;
            } else tests_specified++;
        }
        if (!tests_specified) named = NULL;
    } else {
        named = NULL;
    }
    test_all();
    if (named && tests_run != tests_specified) {
        fprintf(stderr, "ERROR: %d tests were specified, "
                "but %d were found\n", tests_specified, tests_run);
        return 2;
    }
    /* In crash test, we can only success or fail with segfault etc. */
    return test_errors && !crash_test_only ? EXIT_FAILURE : EXIT_SUCCESS;
}