2 * Copyright (c) 2003-2007 Tim Kientzle
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 * Various utility routines useful for test programs.
28 * Each test program is linked against this file.
38 * This same file is used pretty much verbatim for all test harnesses.
40 * The next few lines are the only differences.
42 #undef PROGRAM /* Testing a library, not a program. */
43 #define ENVBASE "LIBARCHIVE" /* Prefix for environment variables. */
44 #define EXTRA_DUMP(x) archive_error_string((struct archive *)(x))
45 #define EXTRA_VERSION archive_version()
46 __FBSDID("$FreeBSD$");
49 * "list.h" is simply created by "grep DEFINE_TEST"; it has
51 * DEFINE_TEST(test_function)
53 * Include it here with a suitable DEFINE_TEST to declare all of the
57 #define DEFINE_TEST(name) void name(void);
60 /* Interix doesn't define these in a standard header. */
66 /* Enable core dump on failure. */
67 static int dump_on_failure = 0;
68 /* Default is to remove temp dirs for successful tests. */
69 static int keep_temp_files = 0;
70 /* Default is to print some basic information about each test. */
71 static int quiet_flag = 0;
72 /* Default is to summarize repeated failures. */
73 static int verbose = 0;
74 /* Cumulative count of component failures. */
75 static int failures = 0;
76 /* Cumulative count of skipped component tests. */
78 /* Cumulative count of assertions. */
79 static int assertions = 0;
81 /* Directory where uuencoded reference files can be found. */
85 * My own implementation of the standard assert() macro emits the
86 * message in the same format as GCC (file:line: message).
87 * It also includes some additional useful information.
88 * This makes it a lot easier to skim through test failures in
91 * It also supports a few special features specifically to simplify
93 * failure(fmt, args) -- Stores a text string that gets
94 * printed if the following assertion fails, good for
95 * explaining subtle tests.
97 static char msg[4096];
100 * For each test source file, we remember how many times each
101 * failure was reported.
103 static const char *failed_filename = NULL;
107 } failed_lines[1000];
110 * Count this failure; return the number of previous failures.
113 previous_failures(const char *filename, int line)
118 if (failed_filename == NULL || strcmp(failed_filename, filename) != 0)
119 memset(failed_lines, 0, sizeof(failed_lines));
120 failed_filename = filename;
122 for (i = 0; i < sizeof(failed_lines)/sizeof(failed_lines[0]); i++) {
123 if (failed_lines[i].line == line) {
124 count = failed_lines[i].count;
125 failed_lines[i].count++;
128 if (failed_lines[i].line == 0) {
129 failed_lines[i].line = line;
130 failed_lines[i].count = 1;
138 * Copy arguments into file-local variables.
140 static const char *test_filename;
141 static int test_line;
142 static void *test_extra;
143 void test_setup(const char *filename, int line)
145 test_filename = filename;
150 * Inform user that we're skipping a test.
153 test_skipping(const char *fmt, ...)
157 if (previous_failures(test_filename, test_line))
161 fprintf(stderr, " *** SKIPPING: ");
162 vfprintf(stderr, fmt, ap);
163 fprintf(stderr, "\n");
168 /* Common handling of failed tests. */
170 report_failure(void *extra)
172 if (msg[0] != '\0') {
173 fprintf(stderr, " Description: %s\n", msg);
179 fprintf(stderr, " detail: %s\n", EXTRA_DUMP(extra));
181 (void)extra; /* UNUSED */
184 if (dump_on_failure) {
186 " *** forcing core dump so failure can be debugged ***\n");
193 * Summarize repeated failures in the just-completed test file.
194 * The reports above suppress multiple failures from the same source
195 * line; this reports on any tests that did fail multiple times.
198 summarize_comparator(const void *a0, const void *b0)
200 const struct line *a = a0, *b = b0;
201 if (a->line == 0 && b->line == 0)
207 return (a->line - b->line);
215 qsort(failed_lines, sizeof(failed_lines)/sizeof(failed_lines[0]),
216 sizeof(failed_lines[0]), summarize_comparator);
217 for (i = 0; i < sizeof(failed_lines)/sizeof(failed_lines[0]); i++) {
218 if (failed_lines[i].line == 0)
220 if (failed_lines[i].count > 1)
221 fprintf(stderr, "%s:%d: Failed %d times\n",
222 failed_filename, failed_lines[i].line,
223 failed_lines[i].count);
225 /* Clear the failure history for the next file. */
226 memset(failed_lines, 0, sizeof(failed_lines));
229 /* Set up a message to display only after a test fails. */
231 failure(const char *fmt, ...)
235 vsprintf(msg, fmt, ap);
239 /* Generic assert() just displays the failed condition. */
241 test_assert(const char *file, int line, int value, const char *condition, void *extra)
249 if (!verbose && previous_failures(file, line))
251 fprintf(stderr, "%s:%d: Assertion failed\n", file, line);
252 fprintf(stderr, " Condition: %s\n", condition);
253 report_failure(extra);
257 /* assertEqualInt() displays the values of the two integers. */
259 test_assert_equal_int(const char *file, int line,
260 int v1, const char *e1, int v2, const char *e2, void *extra)
268 if (!verbose && previous_failures(file, line))
270 fprintf(stderr, "%s:%d: Assertion failed: Ints not equal\n",
272 fprintf(stderr, " %s=%d\n", e1, v1);
273 fprintf(stderr, " %s=%d\n", e2, v2);
274 report_failure(extra);
278 static void strdump(const char *p)
281 fprintf(stderr, "(null)");
284 fprintf(stderr, "\"");
286 unsigned int c = 0xff & *p++;
288 case '\a': fprintf(stderr, "\a"); break;
289 case '\b': fprintf(stderr, "\b"); break;
290 case '\n': fprintf(stderr, "\n"); break;
291 case '\r': fprintf(stderr, "\r"); break;
293 if (c >= 32 && c < 127)
294 fprintf(stderr, "%c", c);
296 fprintf(stderr, "\\x%02X", c);
299 fprintf(stderr, "\"");
302 /* assertEqualString() displays the values of the two strings. */
304 test_assert_equal_string(const char *file, int line,
305 const char *v1, const char *e1,
306 const char *v2, const char *e2,
310 if (v1 == NULL || v2 == NULL) {
315 } else if (strcmp(v1, v2) == 0) {
320 if (!verbose && previous_failures(file, line))
322 fprintf(stderr, "%s:%d: Assertion failed: Strings not equal\n",
324 fprintf(stderr, " %s = ", e1);
326 fprintf(stderr, " (length %d)\n", v1 == NULL ? 0 : strlen(v1));
327 fprintf(stderr, " %s = ", e2);
329 fprintf(stderr, " (length %d)\n", v2 == NULL ? 0 : strlen(v2));
330 report_failure(extra);
334 static void wcsdump(const wchar_t *w)
337 fprintf(stderr, "(null)");
340 fprintf(stderr, "\"");
341 while (*w != L'\0') {
342 unsigned int c = *w++;
343 if (c >= 32 && c < 127)
344 fprintf(stderr, "%c", c);
346 fprintf(stderr, "\\x%02X", c);
347 else if (c < 0x10000)
348 fprintf(stderr, "\\u%04X", c);
350 fprintf(stderr, "\\U%08X", c);
352 fprintf(stderr, "\"");
355 /* assertEqualWString() displays the values of the two strings. */
357 test_assert_equal_wstring(const char *file, int line,
358 const wchar_t *v1, const char *e1,
359 const wchar_t *v2, const char *e2,
368 } else if (v2 == NULL) {
373 } else if (wcscmp(v1, v2) == 0) {
378 if (!verbose && previous_failures(file, line))
380 fprintf(stderr, "%s:%d: Assertion failed: Unicode strings not equal\n",
382 fprintf(stderr, " %s = ", e1);
384 fprintf(stderr, "\n");
385 fprintf(stderr, " %s = ", e2);
387 fprintf(stderr, "\n");
388 report_failure(extra);
393 * Pretty standard hexdump routine. As a bonus, if ref != NULL, then
394 * any bytes in p that differ from ref will be highlighted with '_'
395 * before and after the hex value.
398 hexdump(const char *p, const char *ref, size_t l, size_t offset)
403 for(i=0; i < l; i+=16) {
404 fprintf(stderr, "%04x", i + offset);
406 for (j = 0; j < 16 && i + j < l; j++) {
407 if (ref != NULL && p[i + j] != ref[i + j])
409 fprintf(stderr, "%c%02x", sep, 0xff & (int)p[i+j]);
410 if (ref != NULL && p[i + j] == ref[i + j])
413 for (; j < 16; j++) {
414 fprintf(stderr, "%c ", sep);
417 fprintf(stderr, "%c", sep);
418 for (j=0; j < 16 && i + j < l; j++) {
420 if (c >= ' ' && c <= 126)
421 fprintf(stderr, "%c", c);
423 fprintf(stderr, ".");
425 fprintf(stderr, "\n");
429 /* assertEqualMem() displays the values of the two memory blocks. */
430 /* TODO: For long blocks, hexdump the first bytes that actually differ. */
432 test_assert_equal_mem(const char *file, int line,
433 const char *v1, const char *e1,
434 const char *v2, const char *e2,
435 size_t l, const char *ld, void *extra)
438 if (v1 == NULL || v2 == NULL) {
443 } else if (memcmp(v1, v2, l) == 0) {
448 if (!verbose && previous_failures(file, line))
450 fprintf(stderr, "%s:%d: Assertion failed: memory not equal\n",
452 fprintf(stderr, " size %s = %d\n", ld, (int)l);
453 fprintf(stderr, " Dump of %s\n", e1);
454 hexdump(v1, v2, l < 32 ? l : 32, 0);
455 fprintf(stderr, " Dump of %s\n", e2);
456 hexdump(v2, v1, l < 32 ? l : 32, 0);
457 fprintf(stderr, "\n");
458 report_failure(extra);
463 test_assert_empty_file(const char *f1fmt, ...)
474 vsprintf(f1, f1fmt, ap);
477 if (stat(f1, &st) != 0) {
478 fprintf(stderr, "%s:%d: Could not stat: %s\n", test_filename, test_line, f1);
479 report_failure(NULL);
486 if (!verbose && previous_failures(test_filename, test_line))
489 fprintf(stderr, "%s:%d: File not empty: %s\n", test_filename, test_line, f1);
490 fprintf(stderr, " File size: %d\n", (int)st.st_size);
491 fprintf(stderr, " Contents:\n");
492 fd = open(f1, O_RDONLY);
494 fprintf(stderr, " Unable to open %s\n", f1);
496 s = sizeof(buff) < st.st_size ? sizeof(buff) : st.st_size;
497 s = read(fd, buff, s);
498 hexdump(buff, NULL, s, 0);
500 report_failure(NULL);
504 /* assertEqualFile() asserts that two files have the same contents. */
505 /* TODO: hexdump the first bytes that actually differ. */
507 test_assert_equal_file(const char *f1, const char *f2pattern, ...)
516 va_start(ap, f2pattern);
517 vsprintf(f2, f2pattern, ap);
520 fd1 = open(f1, O_RDONLY);
521 fd2 = open(f2, O_RDONLY);
523 n1 = read(fd1, buff1, sizeof(buff1));
524 n2 = read(fd2, buff2, sizeof(buff2));
527 if (n1 == 0 && n2 == 0)
529 if (memcmp(buff1, buff2, n1) != 0)
533 if (!verbose && previous_failures(test_filename, test_line))
535 fprintf(stderr, "%s:%d: Files are not identical\n",
536 test_filename, test_line);
537 fprintf(stderr, " file1=\"%s\"\n", f1);
538 fprintf(stderr, " file2=\"%s\"\n", f2);
539 report_failure(test_extra);
544 test_assert_file_exists(const char *fpattern, ...)
549 va_start(ap, fpattern);
550 vsprintf(f, fpattern, ap);
553 if (!access(f, F_OK))
555 if (!previous_failures(test_filename, test_line)) {
556 fprintf(stderr, "%s:%d: File doesn't exist\n",
557 test_filename, test_line);
558 fprintf(stderr, " file=\"%s\"\n", f);
559 report_failure(test_extra);
565 test_assert_file_not_exists(const char *fpattern, ...)
570 va_start(ap, fpattern);
571 vsprintf(f, fpattern, ap);
576 if (!previous_failures(test_filename, test_line)) {
577 fprintf(stderr, "%s:%d: File exists and shouldn't\n",
578 test_filename, test_line);
579 fprintf(stderr, " file=\"%s\"\n", f);
580 report_failure(test_extra);
585 /* assertFileContents() asserts the contents of a file. */
587 test_assert_file_contents(const void *buff, int s, const char *fpattern, ...)
595 va_start(ap, fpattern);
596 vsprintf(f, fpattern, ap);
599 fd = open(f, O_RDONLY);
600 contents = malloc(s * 2);
601 n = read(fd, contents, s * 2);
602 if (n == s && memcmp(buff, contents, s) == 0) {
607 if (!previous_failures(test_filename, test_line)) {
608 fprintf(stderr, "%s:%d: File contents don't match\n",
609 test_filename, test_line);
610 fprintf(stderr, " file=\"%s\"\n", f);
612 hexdump(contents, buff, n, 0);
614 fprintf(stderr, " File empty, contents should be:\n");
615 hexdump(buff, NULL, s, 0);
617 report_failure(test_extra);
624 * Call standard system() call, but build up the command line using
625 * sprintf() conventions.
628 systemf(const char *fmt, ...)
635 vsprintf(buff, fmt, ap);
642 * Slurp a file into memory for ease of comparison and testing.
643 * Returns size of file in 'sizep' if non-NULL, null-terminates
644 * data in memory for ease of use.
647 slurpfile(size_t * sizep, const char *fmt, ...)
658 vsprintf(filename, fmt, ap);
661 fd = open(filename, O_RDONLY);
663 /* Note: No error; non-existent file is okay here. */
668 fprintf(stderr, "Can't stat file %s\n", filename);
672 p = malloc(st.st_size + 1);
674 fprintf(stderr, "Can't allocate %ld bytes of memory to read file %s\n", (long int)st.st_size, filename);
678 bytes_read = read(fd, p, st.st_size);
679 if (bytes_read < st.st_size) {
680 fprintf(stderr, "Can't read file %s\n", filename);
685 p[st.st_size] = '\0';
687 *sizep = (size_t)st.st_size;
693 * "list.h" is automatically generated; it just has a lot of lines like:
694 * DEFINE_TEST(function_name)
695 * It's used above to declare all of the test functions.
696 * We reuse it here to define a list of all tests (functions and names).
699 #define DEFINE_TEST(n) { n, #n },
700 struct { void (*func)(void); const char *name; } tests[] = {
705 * Each test is run in a private work dir. Those work dirs
706 * do have consistent and predictable names, in case a group
707 * of tests need to collaborate. However, there is no provision
708 * for requiring that tests run in a certain order.
710 static int test_run(int i, const char *tmpdir)
712 int failures_before = failures;
715 printf("%d: %s\n", i, tests[i].name);
720 * Always explicitly chdir() in case the last test moved us to
725 "ERROR: Couldn't chdir to temp dir %s\n",
729 /* Create a temp directory for this specific test. */
730 if (mkdir(tests[i].name, 0755)) {
732 "ERROR: Couldn't create temp dir ``%s''\n",
736 /* Chdir() to that work directory. */
737 if (chdir(tests[i].name)) {
739 "ERROR: Couldn't chdir to temp dir ``%s''\n",
743 /* Explicitly reset the locale before each test. */
744 setlocale(LC_ALL, "C");
745 /* Run the actual test. */
747 /* Summarize the results of this test. */
749 /* If there were no failures, we can remove the work dir. */
750 if (failures == failures_before) {
751 if (!keep_temp_files && chdir(tmpdir) == 0) {
752 systemf("rm -rf %s", tests[i].name);
755 /* Return appropriate status. */
756 return (failures == failures_before ? 0 : 1);
759 static void usage(const char *program)
761 static const int limit = sizeof(tests) / sizeof(tests[0]);
764 printf("Usage: %s [options] <test> <test> ...\n", program);
765 printf("Default is to run all tests.\n");
766 printf("Otherwise, specify the numbers of the tests you wish to run.\n");
767 printf("Options:\n");
768 printf(" -d Dump core after any failure, for debugging.\n");
769 printf(" -k Keep all temp files.\n");
770 printf(" Default: temp files for successful tests deleted.\n");
772 printf(" -p <path> Path to executable to be tested.\n");
773 printf(" Default: path taken from " ENVBASE " environment variable.\n");
775 printf(" -q Quiet.\n");
776 printf(" -r <dir> Path to dir containing reference files.\n");
777 printf(" Default: Current directory.\n");
778 printf(" -v Verbose.\n");
779 printf("Available tests:\n");
780 for (i = 0; i < limit; i++)
781 printf(" %d: %s\n", i, tests[i].name);
785 #define UUDECODE(c) (((c) - 0x20) & 0x3f)
788 extract_reference_file(const char *name)
793 sprintf(buff, "%s/%s.uu", refdir, name);
794 in = fopen(buff, "r");
795 failure("Couldn't open reference file %s", buff);
799 /* Read up to and including the 'begin' line. */
801 if (fgets(buff, sizeof(buff), in) == NULL) {
802 /* TODO: This is a failure. */
805 if (memcmp(buff, "begin ", 6) == 0)
808 /* Now, decode the rest and write it. */
809 /* Not a lot of error checking here; the input better be right. */
810 out = fopen(name, "w");
811 while (fgets(buff, sizeof(buff), in) != NULL) {
815 if (memcmp(buff, "end", 3) == 0)
818 bytes = UUDECODE(*p++);
821 /* Write out 1-3 bytes from that. */
823 n = UUDECODE(*p++) << 18;
824 n |= UUDECODE(*p++) << 12;
829 n |= UUDECODE(*p++) << 6;
830 fputc((n >> 8) & 0xFF, out);
835 fputc(n & 0xFF, out);
845 int main(int argc, char **argv)
847 static const int limit = sizeof(tests) / sizeof(tests[0]);
848 int i, tests_run = 0, tests_failed = 0, opt;
850 char *refdir_alloc = NULL;
853 char tmpdir_timestamp[256];
856 * Name of this program, used to build root of our temp directory
859 progname = p = argv[0];
867 /* Get the target program from environment, if available. */
868 testprog = getenv(ENVBASE);
871 /* Allow -d to be controlled through the environment. */
872 if (getenv(ENVBASE "_DEBUG") != NULL)
875 /* Get the directory holding test files from environment. */
876 refdir = getenv(ENVBASE "_TEST_FILES");
881 while ((opt = getopt(argc, argv, "dkp:qr:v")) != -1) {
914 * Sanity-check that our options make sense.
917 if (testprog == NULL)
922 * Create a temp directory for the following tests.
923 * Include the time the tests started as part of the name,
924 * to make it easier to track the results of multiple tests.
927 for (i = 0; i < 1000; i++) {
928 strftime(tmpdir_timestamp, sizeof(tmpdir_timestamp),
931 sprintf(tmpdir, "/tmp/%s.%s-%03d", progname, tmpdir_timestamp, i);
932 if (mkdir(tmpdir,0755) == 0)
936 fprintf(stderr, "ERROR: Unable to create temp directory %s\n",
942 * If the user didn't specify a directory for locating
943 * reference files, use the current directory for that.
945 if (refdir == NULL) {
946 systemf("/bin/pwd > %s/refdir", tmpdir);
947 refdir = refdir_alloc = slurpfile(NULL, "%s/refdir", tmpdir);
948 p = refdir + strlen(refdir);
949 while (p[-1] == '\n') {
953 systemf("rm %s/refdir", tmpdir);
957 * Banner with basic information.
960 printf("Running tests in: %s\n", tmpdir);
961 printf("Reference files will be read from: %s\n", refdir);
963 printf("Running tests on: %s\n", testprog);
965 printf("Exercising: ");
967 printf("%s\n", EXTRA_VERSION);
971 * Run some or all of the individual tests.
974 /* Default: Run all tests. */
975 for (i = 0; i < limit; i++) {
976 if (test_run(i, tmpdir))
981 while (*(argv) != NULL) {
983 if (**argv < '0' || **argv > '9' || i < 0 || i >= limit) {
984 printf("*** INVALID Test %s\n", *argv);
987 if (test_run(i, tmpdir))
996 * Report summary statistics.
1000 printf("%d of %d tests reported failures\n",
1001 tests_failed, tests_run);
1002 printf(" Total of %d assertions checked.\n", assertions);
1003 printf(" Total of %d assertions failed.\n", failures);
1004 printf(" Total of %d assertions skipped.\n", skips);
1009 /* If the final tmpdir is empty, we can remove it. */
1010 /* This should be the usual case when all tests succeed. */
1013 return (tests_failed);