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