Build system: implement REUSE with SPDX identifiers
[lttng-ust.git] / tests / utils / tap-driver.sh
1 #! /bin/sh
2
3 # Copyright (C) 2011-2018 Free Software Foundation, Inc.
4 #
5 # SPDX-License-Identifier: GPL-2.0-or-later
6
7 # As a special exception to the GNU General Public License, if you
8 # distribute this file as part of a program that contains a
9 # configuration script generated by Autoconf, you may include it under
10 # the same distribution terms that you use for the rest of that program.
11
12 # This file is maintained in Automake, please report
13 # bugs to <bug-automake@gnu.org> or send patches to
14 # <automake-patches@gnu.org>.
15
16 scriptversion=2013-12-23.17; # UTC
17
18 # Make unconditional expansion of undefined variables an error. This
19 # helps a lot in preventing typo-related bugs.
20 set -u
21
22 me=tap-driver.sh
23
24 fatal ()
25 {
26 echo "$me: fatal: $*" >&2
27 exit 1
28 }
29
30 usage_error ()
31 {
32 echo "$me: $*" >&2
33 print_usage >&2
34 exit 2
35 }
36
37 print_usage ()
38 {
39 cat <<END
40 Usage:
41 tap-driver.sh --test-name=NAME --log-file=PATH --trs-file=PATH
42 [--expect-failure={yes|no}] [--color-tests={yes|no}]
43 [--enable-hard-errors={yes|no}] [--ignore-exit]
44 [--diagnostic-string=STRING] [--merge|--no-merge]
45 [--comments|--no-comments] [--] TEST-COMMAND
46 The '--test-name', '-log-file' and '--trs-file' options are mandatory.
47 END
48 }
49
50 # TODO: better error handling in option parsing (in particular, ensure
51 # TODO: $log_file, $trs_file and $test_name are defined).
52 test_name= # Used for reporting.
53 log_file= # Where to save the result and output of the test script.
54 trs_file= # Where to save the metadata of the test run.
55 expect_failure=0
56 color_tests=0
57 merge=0
58 ignore_exit=0
59 comments=0
60 diag_string='#'
61 while test $# -gt 0; do
62 case $1 in
63 --help) print_usage; exit $?;;
64 --version) echo "$me $scriptversion"; exit $?;;
65 --test-name) test_name=$2; shift;;
66 --log-file) log_file=$2; shift;;
67 --trs-file) trs_file=$2; shift;;
68 --color-tests) color_tests=$2; shift;;
69 --expect-failure) expect_failure=$2; shift;;
70 --enable-hard-errors) shift;; # No-op.
71 --merge) merge=1;;
72 --no-merge) merge=0;;
73 --ignore-exit) ignore_exit=1;;
74 --comments) comments=1;;
75 --no-comments) comments=0;;
76 --diagnostic-string) diag_string=$2; shift;;
77 --) shift; break;;
78 -*) usage_error "invalid option: '$1'";;
79 esac
80 shift
81 done
82
83 test $# -gt 0 || usage_error "missing test command"
84
85 case $expect_failure in
86 yes) expect_failure=1;;
87 *) expect_failure=0;;
88 esac
89
90 if test $color_tests = yes; then
91 init_colors='
92 color_map["red"]="\e[0;31m" # Red.
93 color_map["grn"]="\e[0;32m" # Green.
94 color_map["lgn"]="\e[1;32m" # Light green.
95 color_map["blu"]="\e[1;34m" # Blue.
96 color_map["mgn"]="\e[0;35m" # Magenta.
97 color_map["std"]="\e[m" # No color.
98 color_for_result["ERROR"] = "mgn"
99 color_for_result["PASS"] = "grn"
100 color_for_result["XPASS"] = "red"
101 color_for_result["FAIL"] = "red"
102 color_for_result["XFAIL"] = "lgn"
103 color_for_result["SKIP"] = "blu"'
104 else
105 init_colors=''
106 fi
107
108 # :; is there to work around a bug in bash 3.2 (and earlier) which
109 # does not always set '$?' properly on redirection failure.
110 # See the Autoconf manual for more details.
111 :;{
112 (
113 # Ignore common signals (in this subshell only!), to avoid potential
114 # problems with Korn shells. Some Korn shells are known to propagate
115 # to themselves signals that have killed a child process they were
116 # waiting for; this is done at least for SIGINT (and usually only for
117 # it, in truth). Without the `trap' below, such a behaviour could
118 # cause a premature exit in the current subshell, e.g., in case the
119 # test command it runs gets terminated by a SIGINT. Thus, the awk
120 # script we are piping into would never seen the exit status it
121 # expects on its last input line (which is displayed below by the
122 # last `echo $?' statement), and would thus die reporting an internal
123 # error.
124 # For more information, see the Autoconf manual and the threads:
125 # <https://lists.gnu.org/archive/html/bug-autoconf/2011-09/msg00004.html>
126 # <http://mail.opensolaris.org/pipermail/ksh93-integration-discuss/2009-February/004121.html>
127 trap : 1 3 2 13 15
128 if test $merge -gt 0; then
129 exec 2>&1
130 else
131 exec 2>&3
132 fi
133 "$@"
134 echo $?
135 ) | LC_ALL=C ${AM_TAP_AWK-awk} \
136 -v me="$me" \
137 -v test_script_name="$test_name" \
138 -v log_file="$log_file" \
139 -v trs_file="$trs_file" \
140 -v expect_failure="$expect_failure" \
141 -v merge="$merge" \
142 -v ignore_exit="$ignore_exit" \
143 -v comments="$comments" \
144 -v diag_string="$diag_string" \
145 '
146 # TODO: the usages of "cat >&3" below could be optimized when using
147 # GNU awk, and/on on systems that supports /dev/fd/.
148
149 # Implementation note: in what follows, `result_obj` will be an
150 # associative array that (partly) simulates a TAP result object
151 # from the `TAP::Parser` perl module.
152
153 ## ----------- ##
154 ## FUNCTIONS ##
155 ## ----------- ##
156
157 function fatal(msg)
158 {
159 print me ": " msg | "cat >&2"
160 exit 1
161 }
162
163 function abort(where)
164 {
165 fatal("internal error " where)
166 }
167
168 # Convert a boolean to a "yes"/"no" string.
169 function yn(bool)
170 {
171 return bool ? "yes" : "no";
172 }
173
174 function add_test_result(result)
175 {
176 if (!test_results_index)
177 test_results_index = 0
178 test_results_list[test_results_index] = result
179 test_results_index += 1
180 test_results_seen[result] = 1;
181 }
182
183 # Whether the test script should be re-run by "make recheck".
184 function must_recheck()
185 {
186 for (k in test_results_seen)
187 if (k != "XFAIL" && k != "PASS" && k != "SKIP")
188 return 1
189 return 0
190 }
191
192 # Whether the content of the log file associated to this test should
193 # be copied into the "global" test-suite.log.
194 function copy_in_global_log()
195 {
196 for (k in test_results_seen)
197 if (k != "PASS")
198 return 1
199 return 0
200 }
201
202 function get_global_test_result()
203 {
204 if ("ERROR" in test_results_seen)
205 return "ERROR"
206 if ("FAIL" in test_results_seen || "XPASS" in test_results_seen)
207 return "FAIL"
208 all_skipped = 1
209 for (k in test_results_seen)
210 if (k != "SKIP")
211 all_skipped = 0
212 if (all_skipped)
213 return "SKIP"
214 return "PASS";
215 }
216
217 function stringify_result_obj(result_obj)
218 {
219 if (result_obj["is_unplanned"] || result_obj["number"] != testno)
220 return "ERROR"
221
222 if (plan_seen == LATE_PLAN)
223 return "ERROR"
224
225 if (result_obj["directive"] == "TODO")
226 return result_obj["is_ok"] ? "XPASS" : "XFAIL"
227
228 if (result_obj["directive"] == "SKIP")
229 return result_obj["is_ok"] ? "SKIP" : COOKED_FAIL;
230
231 if (length(result_obj["directive"]))
232 abort("in function stringify_result_obj()")
233
234 return result_obj["is_ok"] ? COOKED_PASS : COOKED_FAIL
235 }
236
237 function decorate_result(result)
238 {
239 color_name = color_for_result[result]
240 if (color_name)
241 return color_map[color_name] "" result "" color_map["std"]
242 # If we are not using colorized output, or if we do not know how
243 # to colorize the given result, we should return it unchanged.
244 return result
245 }
246
247 function report(result, details)
248 {
249 if (result ~ /^(X?(PASS|FAIL)|SKIP|ERROR)/)
250 {
251 msg = ": " test_script_name
252 add_test_result(result)
253 }
254 else if (result == "#")
255 {
256 msg = " " test_script_name ":"
257 }
258 else
259 {
260 abort("in function report()")
261 }
262 if (length(details))
263 msg = msg " " details
264 # Output on console might be colorized.
265 print decorate_result(result) msg
266 # Flush stdout after each test result, this is useful when stdout
267 # is buffered, for example in a CI system.
268 fflush()
269 # Log the result in the log file too, to help debugging (this is
270 # especially true when said result is a TAP error or "Bail out!").
271 print result msg | "cat >&3";
272 }
273
274 function testsuite_error(error_message)
275 {
276 report("ERROR", "- " error_message)
277 }
278
279 function handle_tap_result()
280 {
281 details = result_obj["number"];
282 if (length(result_obj["description"]))
283 details = details " " result_obj["description"]
284
285 if (plan_seen == LATE_PLAN)
286 {
287 details = details " # AFTER LATE PLAN";
288 }
289 else if (result_obj["is_unplanned"])
290 {
291 details = details " # UNPLANNED";
292 }
293 else if (result_obj["number"] != testno)
294 {
295 details = sprintf("%s # OUT-OF-ORDER (expecting %d)",
296 details, testno);
297 }
298 else if (result_obj["directive"])
299 {
300 details = details " # " result_obj["directive"];
301 if (length(result_obj["explanation"]))
302 details = details " " result_obj["explanation"]
303 }
304
305 report(stringify_result_obj(result_obj), details)
306 }
307
308 # `skip_reason` should be empty whenever planned > 0.
309 function handle_tap_plan(planned, skip_reason)
310 {
311 planned += 0 # Avoid getting confused if, say, `planned` is "00"
312 if (length(skip_reason) && planned > 0)
313 abort("in function handle_tap_plan()")
314 if (plan_seen)
315 {
316 # Error, only one plan per stream is acceptable.
317 testsuite_error("multiple test plans")
318 return;
319 }
320 planned_tests = planned
321 # The TAP plan can come before or after *all* the TAP results; we speak
322 # respectively of an "early" or a "late" plan. If we see the plan line
323 # after at least one TAP result has been seen, assume we have a late
324 # plan; in this case, any further test result seen after the plan will
325 # be flagged as an error.
326 plan_seen = (testno >= 1 ? LATE_PLAN : EARLY_PLAN)
327 # If testno > 0, we have an error ("too many tests run") that will be
328 # automatically dealt with later, so do not worry about it here. If
329 # $plan_seen is true, we have an error due to a repeated plan, and that
330 # has already been dealt with above. Otherwise, we have a valid "plan
331 # with SKIP" specification, and should report it as a particular kind
332 # of SKIP result.
333 if (planned == 0 && testno == 0)
334 {
335 if (length(skip_reason))
336 skip_reason = "- " skip_reason;
337 report("SKIP", skip_reason);
338 }
339 }
340
341 function extract_tap_comment(line)
342 {
343 if (index(line, diag_string) == 1)
344 {
345 # Strip leading `diag_string` from `line`.
346 line = substr(line, length(diag_string) + 1)
347 # And strip any leading and trailing whitespace left.
348 sub("^[ \t]*", "", line)
349 sub("[ \t]*$", "", line)
350 # Return what is left (if any).
351 return line;
352 }
353 return "";
354 }
355
356 # When this function is called, we know that line is a TAP result line,
357 # so that it matches the (perl) RE "^(not )?ok\b".
358 function setup_result_obj(line)
359 {
360 # Get the result, and remove it from the line.
361 result_obj["is_ok"] = (substr(line, 1, 2) == "ok" ? 1 : 0)
362 sub("^(not )?ok[ \t]*", "", line)
363
364 # If the result has an explicit number, get it and strip it; otherwise,
365 # automatically assign the next progresive number to it.
366 if (line ~ /^[0-9]+$/ || line ~ /^[0-9]+[^a-zA-Z0-9_]/)
367 {
368 match(line, "^[0-9]+")
369 # The final `+ 0` is to normalize numbers with leading zeros.
370 result_obj["number"] = substr(line, 1, RLENGTH) + 0
371 line = substr(line, RLENGTH + 1)
372 }
373 else
374 {
375 result_obj["number"] = testno
376 }
377
378 if (plan_seen == LATE_PLAN)
379 # No further test results are acceptable after a "late" TAP plan
380 # has been seen.
381 result_obj["is_unplanned"] = 1
382 else if (plan_seen && testno > planned_tests)
383 result_obj["is_unplanned"] = 1
384 else
385 result_obj["is_unplanned"] = 0
386
387 # Strip trailing and leading whitespace.
388 sub("^[ \t]*", "", line)
389 sub("[ \t]*$", "", line)
390
391 # This will have to be corrected if we have a "TODO"/"SKIP" directive.
392 result_obj["description"] = line
393 result_obj["directive"] = ""
394 result_obj["explanation"] = ""
395
396 if (index(line, "#") == 0)
397 return # No possible directive, nothing more to do.
398
399 # Directives are case-insensitive.
400 rx = "[ \t]*#[ \t]*([tT][oO][dD][oO]|[sS][kK][iI][pP])[ \t]*"
401
402 # See whether we have the directive, and if yes, where.
403 pos = match(line, rx "$")
404 if (!pos)
405 pos = match(line, rx "[^a-zA-Z0-9_]")
406
407 # If there was no TAP directive, we have nothing more to do.
408 if (!pos)
409 return
410
411 # Let`s now see if the TAP directive has been escaped. For example:
412 # escaped: ok \# SKIP
413 # not escaped: ok \\# SKIP
414 # escaped: ok \\\\\# SKIP
415 # not escaped: ok \ # SKIP
416 if (substr(line, pos, 1) == "#")
417 {
418 bslash_count = 0
419 for (i = pos; i > 1 && substr(line, i - 1, 1) == "\\"; i--)
420 bslash_count += 1
421 if (bslash_count % 2)
422 return # Directive was escaped.
423 }
424
425 # Strip the directive and its explanation (if any) from the test
426 # description.
427 result_obj["description"] = substr(line, 1, pos - 1)
428 # Now remove the test description from the line, that has been dealt
429 # with already.
430 line = substr(line, pos)
431 # Strip the directive, and save its value (normalized to upper case).
432 sub("^[ \t]*#[ \t]*", "", line)
433 result_obj["directive"] = toupper(substr(line, 1, 4))
434 line = substr(line, 5)
435 # Now get the explanation for the directive (if any), with leading
436 # and trailing whitespace removed.
437 sub("^[ \t]*", "", line)
438 sub("[ \t]*$", "", line)
439 result_obj["explanation"] = line
440 }
441
442 function get_test_exit_message(status)
443 {
444 if (status == 0)
445 return ""
446 if (status !~ /^[1-9][0-9]*$/)
447 abort("getting exit status")
448 if (status < 127)
449 exit_details = ""
450 else if (status == 127)
451 exit_details = " (command not found?)"
452 else if (status >= 128 && status <= 255)
453 exit_details = sprintf(" (terminated by signal %d?)", status - 128)
454 else if (status > 256 && status <= 384)
455 # We used to report an "abnormal termination" here, but some Korn
456 # shells, when a child process die due to signal number n, can leave
457 # in $? an exit status of 256+n instead of the more standard 128+n.
458 # Apparently, both behaviours are allowed by POSIX (2008), so be
459 # prepared to handle them both. See also Austing Group report ID
460 # 0000051 <http://www.austingroupbugs.net/view.php?id=51>
461 exit_details = sprintf(" (terminated by signal %d?)", status - 256)
462 else
463 # Never seen in practice.
464 exit_details = " (abnormal termination)"
465 return sprintf("exited with status %d%s", status, exit_details)
466 }
467
468 function write_test_results()
469 {
470 print ":global-test-result: " get_global_test_result() > trs_file
471 print ":recheck: " yn(must_recheck()) > trs_file
472 print ":copy-in-global-log: " yn(copy_in_global_log()) > trs_file
473 for (i = 0; i < test_results_index; i += 1)
474 print ":test-result: " test_results_list[i] > trs_file
475 close(trs_file);
476 }
477
478 BEGIN {
479
480 ## ------- ##
481 ## SETUP ##
482 ## ------- ##
483
484 '"$init_colors"'
485
486 # Properly initialized once the TAP plan is seen.
487 planned_tests = 0
488
489 COOKED_PASS = expect_failure ? "XPASS": "PASS";
490 COOKED_FAIL = expect_failure ? "XFAIL": "FAIL";
491
492 # Enumeration-like constants to remember which kind of plan (if any)
493 # has been seen. It is important that NO_PLAN evaluates "false" as
494 # a boolean.
495 NO_PLAN = 0
496 EARLY_PLAN = 1
497 LATE_PLAN = 2
498
499 testno = 0 # Number of test results seen so far.
500 bailed_out = 0 # Whether a "Bail out!" directive has been seen.
501
502 # Whether the TAP plan has been seen or not, and if yes, which kind
503 # it is ("early" is seen before any test result, "late" otherwise).
504 plan_seen = NO_PLAN
505
506 ## --------- ##
507 ## PARSING ##
508 ## --------- ##
509
510 is_first_read = 1
511
512 while (1)
513 {
514 # Involutions required so that we are able to read the exit status
515 # from the last input line.
516 st = getline
517 if (st < 0) # I/O error.
518 fatal("I/O error while reading from input stream")
519 else if (st == 0) # End-of-input
520 {
521 if (is_first_read)
522 abort("in input loop: only one input line")
523 break
524 }
525 if (is_first_read)
526 {
527 is_first_read = 0
528 nextline = $0
529 continue
530 }
531 else
532 {
533 curline = nextline
534 nextline = $0
535 $0 = curline
536 }
537 # Copy any input line verbatim into the log file.
538 print | "cat >&3"
539 # Parsing of TAP input should stop after a "Bail out!" directive.
540 if (bailed_out)
541 continue
542
543 # TAP test result.
544 if ($0 ~ /^(not )?ok$/ || $0 ~ /^(not )?ok[^a-zA-Z0-9_]/)
545 {
546 testno += 1
547 setup_result_obj($0)
548 handle_tap_result()
549 }
550 # TAP plan (normal or "SKIP" without explanation).
551 else if ($0 ~ /^1\.\.[0-9]+[ \t]*$/)
552 {
553 # The next two lines will put the number of planned tests in $0.
554 sub("^1\\.\\.", "")
555 sub("[^0-9]*$", "")
556 handle_tap_plan($0, "")
557 continue
558 }
559 # TAP "SKIP" plan, with an explanation.
560 else if ($0 ~ /^1\.\.0+[ \t]*#/)
561 {
562 # The next lines will put the skip explanation in $0, stripping
563 # any leading and trailing whitespace. This is a little more
564 # tricky in truth, since we want to also strip a potential leading
565 # "SKIP" string from the message.
566 sub("^[^#]*#[ \t]*(SKIP[: \t][ \t]*)?", "")
567 sub("[ \t]*$", "");
568 handle_tap_plan(0, $0)
569 }
570 # "Bail out!" magic.
571 # Older versions of prove and TAP::Harness (e.g., 3.17) did not
572 # recognize a "Bail out!" directive when preceded by leading
573 # whitespace, but more modern versions (e.g., 3.23) do. So we
574 # emulate the latter, "more modern" behaviour.
575 else if ($0 ~ /^[ \t]*Bail out!/)
576 {
577 bailed_out = 1
578 # Get the bailout message (if any), with leading and trailing
579 # whitespace stripped. The message remains stored in `$0`.
580 sub("^[ \t]*Bail out![ \t]*", "");
581 sub("[ \t]*$", "");
582 # Format the error message for the
583 bailout_message = "Bail out!"
584 if (length($0))
585 bailout_message = bailout_message " " $0
586 testsuite_error(bailout_message)
587 }
588 # Maybe we have too look for dianogtic comments too.
589 else if (comments != 0)
590 {
591 comment = extract_tap_comment($0);
592 if (length(comment))
593 report("#", comment);
594 }
595 }
596
597 ## -------- ##
598 ## FINISH ##
599 ## -------- ##
600
601 # A "Bail out!" directive should cause us to ignore any following TAP
602 # error, as well as a non-zero exit status from the TAP producer.
603 if (!bailed_out)
604 {
605 if (!plan_seen)
606 {
607 testsuite_error("missing test plan")
608 }
609 else if (planned_tests != testno)
610 {
611 bad_amount = testno > planned_tests ? "many" : "few"
612 testsuite_error(sprintf("too %s tests run (expected %d, got %d)",
613 bad_amount, planned_tests, testno))
614 }
615 if (!ignore_exit)
616 {
617 # Fetch exit status from the last line.
618 exit_message = get_test_exit_message(nextline)
619 if (exit_message)
620 testsuite_error(exit_message)
621 }
622 }
623
624 write_test_results()
625
626 exit 0
627
628 } # End of "BEGIN" block.
629 '
630
631 # TODO: document that we consume the file descriptor 3 :-(
632 } 3>"$log_file"
633
634 test $? -eq 0 || fatal "I/O or internal error"
635
636 # Local Variables:
637 # mode: shell-script
638 # sh-indentation: 2
639 # eval: (add-hook 'before-save-hook 'time-stamp)
640 # time-stamp-start: "scriptversion="
641 # time-stamp-format: "%:y-%02m-%02d.%02H"
642 # time-stamp-time-zone: "UTC0"
643 # time-stamp-end: "; # UTC"
644 # End:
This page took 0.05633 seconds and 4 git commands to generate.