2 * Some utility routines for writing tests.
4 * Here are a variety of utility routines for writing tests compatible with
5 * the TAP protocol. All routines of the form ok() or is*() take a test
6 * number and some number of appropriate arguments, check to be sure the
7 * results match the expected output using the arguments, and print out
8 * something appropriate for that test number. Other utility routines help in
9 * constructing more complex tests, skipping tests, reporting errors, setting
10 * up the TAP output format, or finding things in the test environment.
12 * This file is part of C TAP Harness. The current version plus supporting
13 * documentation is at <http://www.eyrie.org/~eagle/software/c-tap-harness/>.
15 * Copyright 2009, 2010, 2011, 2012, 2013 Russ Allbery <eagle@eyrie.org>
16 * Copyright 2001, 2002, 2004, 2005, 2006, 2007, 2008, 2011, 2012, 2013
17 * The Board of Trustees of the Leland Stanford Junior University
19 * Permission is hereby granted, free of charge, to any person obtaining a
20 * copy of this software and associated documentation files (the "Software"),
21 * to deal in the Software without restriction, including without limitation
22 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
23 * and/or sell copies of the Software, and to permit persons to whom the
24 * Software is furnished to do so, subject to the following conditions:
26 * The above copyright notice and this permission notice shall be included in
27 * all copies or substantial portions of the Software.
29 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
32 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
34 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
35 * DEALINGS IN THE SOFTWARE.
46 # include <sys/stat.h>
48 #include <sys/types.h>
51 #include <tests/tap/basic.h>
53 /* Windows provides mkdir and rmdir under different names. */
55 # define mkdir(p, m) _mkdir(p)
56 # define rmdir(p) _rmdir(p)
60 * The test count. Always contains the number that will be used for the next
61 * test status. This is exported to callers of the library.
63 unsigned long testnum = 1;
66 * Status information stored so that we can give a test summary at the end of
67 * the test case. We store the planned final test and the count of failures.
68 * We can get the highest test count from testnum.
70 static unsigned long _planned = 0;
71 static unsigned long _failed = 0;
74 * Store the PID of the process that called plan() and only summarize
75 * results when that process exits, so as to not misreport results in forked
78 static pid_t _process = 0;
81 * If true, we're doing lazy planning and will print out the plan based on the
82 * last test number at the end of testing.
87 * If true, the test was aborted by calling bail(). Currently, this is only
88 * used to ensure that we pass a false value to any cleanup functions even if
89 * all tests to that point have passed.
91 static int _aborted = 0;
94 * Registered cleanup functions. These are stored as a linked list and run in
95 * registered order by finish when the test program exits. Each function is
96 * passed a boolean value indicating whether all tests were successful.
99 test_cleanup_func func;
100 struct cleanup_func *next;
102 static struct cleanup_func *cleanup_funcs = NULL;
105 * Print a specified prefix and then the test description. Handles turning
106 * the argument list into a va_args structure suitable for passing to
107 * print_desc, which has to be done in a macro. Assumes that format is the
108 * argument immediately before the variadic arguments.
110 #define PRINT_DESC(prefix, format) \
112 if (format != NULL) { \
114 if (prefix != NULL) \
115 printf("%s", prefix); \
116 va_start(args, format); \
117 vprintf(format, args); \
124 * Our exit handler. Called on completion of the test to report a summary of
125 * results provided we're still in the original process. This also handles
126 * printing out the plan if we used plan_lazy(), although that's suppressed if
127 * we never ran a test (due to an early bail, for example), and running any
128 * registered cleanup functions.
134 struct cleanup_func *current;
135 unsigned long highest = testnum - 1;
138 * Don't do anything except free the cleanup functions if we aren't the
139 * primary process (the process in which plan or plan_lazy was called).
141 if (_process != 0 && getpid() != _process) {
142 while (cleanup_funcs != NULL) {
143 current = cleanup_funcs;
144 cleanup_funcs = cleanup_funcs->next;
151 * Determine whether all tests were successful, which is needed before
152 * calling cleanup functions since we pass that fact to the functions.
154 if (_planned == 0 && _lazy)
156 success = (!_aborted && _planned == highest && _failed == 0);
159 * If there are any registered cleanup functions, we run those first. We
160 * always run them, even if we didn't run a test.
162 while (cleanup_funcs != NULL) {
163 cleanup_funcs->func(success);
164 current = cleanup_funcs;
165 cleanup_funcs = cleanup_funcs->next;
169 /* Don't do anything further if we never planned a test. */
173 /* If we're aborting due to bail, don't print summaries. */
177 /* Print out the lazy plan if needed. */
179 if (_lazy && _planned > 0)
180 printf("1..%lu\n", _planned);
182 /* Print out a summary of the results. */
183 if (_planned > highest)
184 diag("Looks like you planned %lu test%s but only ran %lu", _planned,
185 (_planned > 1 ? "s" : ""), highest);
186 else if (_planned < highest)
187 diag("Looks like you planned %lu test%s but ran %lu extra", _planned,
188 (_planned > 1 ? "s" : ""), highest - _planned);
189 else if (_failed > 0)
190 diag("Looks like you failed %lu test%s of %lu", _failed,
191 (_failed > 1 ? "s" : ""), _planned);
192 else if (_planned != 1)
193 diag("All %lu tests successful or skipped", _planned);
195 diag("%lu test successful or skipped", _planned);
200 * Initialize things. Turns on line buffering on stdout and then prints out
201 * the number of tests in the test suite.
204 plan(unsigned long count)
206 if (setvbuf(stdout, NULL, _IOLBF, BUFSIZ) != 0)
207 sysdiag("cannot set stdout to line buffered");
209 printf("1..%lu\n", count);
213 if (atexit(finish) != 0) {
214 sysdiag("cannot register exit handler");
215 diag("cleanups will not be run");
221 * Initialize things for lazy planning, where we'll automatically print out a
222 * plan at the end of the program. Turns on line buffering on stdout as well.
227 if (setvbuf(stdout, NULL, _IOLBF, BUFSIZ) != 0)
228 sysdiag("cannot set stdout to line buffered");
232 if (atexit(finish) != 0)
233 sysbail("cannot register exit handler to display plan");
238 * Skip the entire test suite and exits. Should be called instead of plan(),
239 * not after it, since it prints out a special plan line.
242 skip_all(const char *format, ...)
245 printf("1..0 # skip");
246 PRINT_DESC(" ", format);
253 * Takes a boolean success value and assumes the test passes if that value
254 * is true and fails if that value is false.
257 ok(int success, const char *format, ...)
260 printf("%sok %lu", success ? "" : "not ", testnum++);
263 PRINT_DESC(" - ", format);
269 * Same as ok(), but takes the format arguments as a va_list.
272 okv(int success, const char *format, va_list args)
275 printf("%sok %lu", success ? "" : "not ", testnum++);
278 if (format != NULL) {
280 vprintf(format, args);
290 skip(const char *reason, ...)
293 printf("ok %lu # skip", testnum++);
294 PRINT_DESC(" ", reason);
300 * Report the same status on the next count tests.
303 ok_block(unsigned long count, int status, const char *format, ...)
308 for (i = 0; i < count; i++) {
309 printf("%sok %lu", status ? "" : "not ", testnum++);
312 PRINT_DESC(" - ", format);
319 * Skip the next count tests.
322 skip_block(unsigned long count, const char *reason, ...)
327 for (i = 0; i < count; i++) {
328 printf("ok %lu # skip", testnum++);
329 PRINT_DESC(" ", reason);
336 * Takes an expected integer and a seen integer and assumes the test passes
337 * if those two numbers match.
340 is_int(long wanted, long seen, const char *format, ...)
344 printf("ok %lu", testnum++);
346 diag("wanted: %ld", wanted);
347 diag(" seen: %ld", seen);
348 printf("not ok %lu", testnum++);
351 PRINT_DESC(" - ", format);
357 * Takes a string and what the string should be, and assumes the test passes
358 * if those strings match (using strcmp).
361 is_string(const char *wanted, const char *seen, const char *format, ...)
368 if (strcmp(wanted, seen) == 0)
369 printf("ok %lu", testnum++);
371 diag("wanted: %s", wanted);
372 diag(" seen: %s", seen);
373 printf("not ok %lu", testnum++);
376 PRINT_DESC(" - ", format);
382 * Takes an expected unsigned long and a seen unsigned long and assumes the
383 * test passes if the two numbers match. Otherwise, reports them in hex.
386 is_hex(unsigned long wanted, unsigned long seen, const char *format, ...)
390 printf("ok %lu", testnum++);
392 diag("wanted: %lx", (unsigned long) wanted);
393 diag(" seen: %lx", (unsigned long) seen);
394 printf("not ok %lu", testnum++);
397 PRINT_DESC(" - ", format);
403 * Bail out with an error.
406 bail(const char *format, ...)
413 printf("Bail out! ");
414 va_start(args, format);
415 vprintf(format, args);
423 * Bail out with an error, appending strerror(errno).
426 sysbail(const char *format, ...)
434 printf("Bail out! ");
435 va_start(args, format);
436 vprintf(format, args);
438 printf(": %s\n", strerror(oerrno));
444 * Report a diagnostic to stderr.
447 diag(const char *format, ...)
454 va_start(args, format);
455 vprintf(format, args);
462 * Report a diagnostic to stderr, appending strerror(errno).
465 sysdiag(const char *format, ...)
473 va_start(args, format);
474 vprintf(format, args);
476 printf(": %s\n", strerror(oerrno));
481 * Allocate cleared memory, reporting a fatal error with bail on failure.
484 bcalloc(size_t n, size_t size)
490 sysbail("failed to calloc %lu", (unsigned long)(n * size));
496 * Allocate memory, reporting a fatal error with bail on failure.
505 sysbail("failed to malloc %lu", (unsigned long) size);
511 * Reallocate memory, reporting a fatal error with bail on failure.
514 brealloc(void *p, size_t size)
516 p = realloc(p, size);
518 sysbail("failed to realloc %lu bytes", (unsigned long) size);
524 * Copy a string, reporting a fatal error with bail on failure.
527 bstrdup(const char *s)
535 sysbail("failed to strdup %lu bytes", (unsigned long) len);
542 * Copy up to n characters of a string, reporting a fatal error with bail on
543 * failure. Don't use the system strndup function, since it may not exist and
544 * the TAP library doesn't assume any portability support.
547 bstrndup(const char *s, size_t n)
553 /* Don't assume that the source string is nul-terminated. */
554 for (p = s; (size_t) (p - s) < n && *p != '\0'; p++)
557 copy = malloc(length + 1);
559 sysbail("failed to strndup %lu bytes", (unsigned long) length);
560 memcpy(copy, s, length);
567 * Locate a test file. Given the partial path to a file, look under BUILD and
568 * then SOURCE for the file and return the full path to the file. Returns
569 * NULL if the file doesn't exist. A non-NULL return should be freed with
570 * test_file_path_free().
572 * This function uses sprintf because it attempts to be independent of all
573 * other portability layers. The use immediately after a memory allocation
574 * should be safe without using snprintf or strlcpy/strlcat.
577 test_file_path(const char *file)
582 const char *envs[] = { "BUILD", "SOURCE", NULL };
585 for (i = 0; envs[i] != NULL; i++) {
586 base = getenv(envs[i]);
589 length = strlen(base) + 1 + strlen(file) + 1;
590 path = bmalloc(length);
591 sprintf(path, "%s/%s", base, file);
592 if (access(path, R_OK) == 0)
602 * Free a path returned from test_file_path(). This function exists primarily
603 * for Windows, where memory must be freed from the same library domain that
604 * it was allocated from.
607 test_file_path_free(char *path)
615 * Create a temporary directory, tmp, under BUILD if set and the current
616 * directory if it does not. Returns the path to the temporary directory in
617 * newly allocated memory, and calls bail on any failure. The return value
618 * should be freed with test_tmpdir_free.
620 * This function uses sprintf because it attempts to be independent of all
621 * other portability layers. The use immediately after a memory allocation
622 * should be safe without using snprintf or strlcpy/strlcat.
631 build = getenv("BUILD");
634 length = strlen(build) + strlen("/tmp") + 1;
635 path = bmalloc(length);
636 sprintf(path, "%s/tmp", build);
637 if (access(path, X_OK) < 0)
638 if (mkdir(path, 0777) < 0)
639 sysbail("error creating temporary directory %s", path);
645 * Free a path returned from test_tmpdir() and attempt to remove the
646 * directory. If we can't delete the directory, don't worry; something else
647 * that hasn't yet cleaned up may still be using it.
650 test_tmpdir_free(char *path)
659 * Register a cleanup function that is called when testing ends. All such
660 * registered functions will be run by finish.
663 test_cleanup_register(test_cleanup_func func)
665 struct cleanup_func *cleanup, **last;
667 cleanup = bmalloc(sizeof(struct cleanup_func));
668 cleanup->func = func;
669 cleanup->next = NULL;
670 last = &cleanup_funcs;
671 while (*last != NULL)
672 last = &(*last)->next;