tap/awk: support Solaris /usr/xpg4/bin/awk
[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-08-21.21; # 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   # FIXME: this usage loses the test program exit status.  We should
120   # probably rewrite the awk script to use the
121   #   expression | getline [var]
122   # idiom, which should allow us to obtain the final exit status from
123   # <expression> when closing it.
124   { test $merge -eq 0 || exec 2>&1; "$@"; } \
125     | LC_ALL=C ${AM_TAP_AWK-awk} \
126         -v me="$me" \
127         -v test_script_name="$test_name" \
128         -v log_file="$log_file" \
129         -v trs_file="$trs_file" \
130         -v expect_failure="$expect_failure" \
131         -v merge="$merge" \
132         -v ignore_exit="$ignore_exit" \
133         -v comments="$comments" \
134         -v diag_string="$diag_string" \
135 '
136 # FIXME: the usages of "cat >&3" below could be optimized whne using
137 # FIXME: GNU awk, and/on on systems that supports /dev/fd/.
138
139 # Implementation note: in what follows, `result_obj` will be an
140 # associative array that (partly) simulates a TAP result object
141 # from the `TAP::Parser` perl module.
142
143 ## ----------- ##
144 ##  FUNCTIONS  ##
145 ## ----------- ##
146
147 function fatal(msg)
148 {
149   print me ": " msg | "cat >&3"
150   exit 1
151 }
152
153 function abort(where)
154 {
155   fatal("internal error " where)
156 }
157
158 # Convert a boolean to a "yes"/"no" string.
159 function yn(bool)
160 {
161   return bool ? "yes" : "no";
162 }
163
164 function add_test_result(result)
165 {
166   if (!test_results_index)
167     test_results_index = 0
168   test_results_list[test_results_index] = result
169   test_results_index += 1
170   test_results_seen[result] = 1;
171 }
172
173 # Whether the test script should be re-run by "make recheck".
174 function must_recheck()
175 {
176   for (k in test_results_seen)
177     if (k != "XFAIL" && k != "PASS" && k != "SKIP")
178       return 1
179   return 0
180 }
181
182 # Whether the content of the log file associated to this test should
183 # be copied into the "global" test-suite.log.
184 function copy_in_global_log()
185 {
186   for (k in test_results_seen)
187     if (k != "PASS")
188       return 1
189   return 0
190 }
191
192 # FIXME: this can certainly be improved ...
193 function get_global_test_result()
194 {
195     if ("ERROR" in test_results_seen)
196       return "ERROR"
197     all_skipped = 1
198     for (k in test_results_seen)
199       if (k != "SKIP")
200         all_skipped = 0
201     if (all_skipped)
202       return "SKIP"
203     if ("FAIL" in test_results_seen || "XPASS" in test_results_seen)
204       return "FAIL"
205     return "PASS";
206 }
207
208 function stringify_result_obj(obj)
209 {
210   if (obj["is_unplanned"] || obj["number"] != testno)
211     return "ERROR"
212
213   if (plan_seen == LATE_PLAN)
214     return "ERROR"
215
216   if (result_obj["directive"] == "TODO")
217     return obj["is_ok"] ? "XPASS" : "XFAIL"
218
219   if (result_obj["directive"] == "SKIP")
220     return obj["is_ok"] ? "SKIP" : COOKED_FAIL;
221
222   if (length(result_obj["directive"]))
223       abort("in function stringify_result_obj()")
224
225   return obj["is_ok"] ? COOKED_PASS : COOKED_FAIL
226 }
227
228 function decorate_result(result)
229 {
230   color_name = color_for_result[result]
231   if (color_name)
232     return color_map[color_name] "" result "" color_map["std"]
233   # If we are not using colorized output, or if we do not know how
234   # to colorize the given result, we should return it unchanged.
235   return result
236 }
237
238 function report(result, details)
239 {
240   if (result ~ /^(X?(PASS|FAIL)|SKIP|ERROR)/)
241     {
242       msg = ": " test_script_name
243       add_test_result(result)
244     }
245   else if (result == "#")
246     {
247       msg = " " test_script_name ":"
248     }
249   else
250     {
251       abort("in function report()")
252     }
253   if (length(details))
254     msg = msg " " details
255   # Output on console might be colorized.
256   print decorate_result(result) msg | "cat >&3";
257   # Log the result in the log file too, to help debugging (this is
258   # especially true when said result is a TAP error or "Bail out!").
259   print result msg;
260 }
261
262 function testsuite_error(error_message)
263 {
264   report("ERROR", "- " error_message)
265 }
266
267 function handle_tap_result()
268 {
269   details = result_obj["number"];
270   if (length(result_obj["description"]))
271     details = details " " result_obj["description"]
272
273   if (plan_seen == LATE_PLAN)
274     {
275       details = details " # AFTER LATE PLAN";
276     }
277   else if (result_obj["is_unplanned"])
278     {
279        details = details " # UNPLANNED";
280     }
281   else if (result_obj["number"] != testno)
282     {
283        details = sprintf("%s # OUT-OF-ORDER (expecting %d)",
284                          details, testno);
285     }
286   else if (result_obj["directive"])
287     {
288       details = details " # " result_obj["directive"];
289       if (length(result_obj["explanation"]))
290         details = details " " result_obj["explanation"]
291     }
292
293   report(stringify_result_obj(result_obj), details)
294 }
295
296 # `skip_reason` should be emprty whenever planned > 0.
297 function handle_tap_plan(planned, skip_reason)
298 {
299   planned += 0 # Avoid getting confused if, say, `planned` is "00"
300   if (length(skip_reason) && planned > 0)
301     abort("in function handle_tap_plan()")
302   if (plan_seen)
303     {
304       # Error, only one plan per stream is acceptable.
305       testsuite_error("multiple test plans")
306       return;
307     }
308   planned_tests = planned
309   # The TAP plan can come before or after *all* the TAP results; we speak
310   # respectively of an "early" or a "late" plan.  If we see the plan line
311   # after at least one TAP result has been seen, assume we have a late
312   # plan; in this case, any further test result seen after the plan will
313   # be flagged as an error.
314   plan_seen = (testno >= 1 ? LATE_PLAN : EARLY_PLAN)
315   # If testno > 0, we have an error ("too many tests run") that will be
316   # automatically dealt with later, so do not worry about it here.  If
317   # $plan_seen is true, we have an error due to a repeated plan, and that
318   # has already been dealt with above.  Otherwise, we have a valid "plan
319   # with SKIP" specification, and should report it as a particular kind
320   # of SKIP result.
321   if (planned == 0 && testno == 0)
322     {
323       if (length(skip_reason))
324         skip_reason = "- "  skip_reason;
325       report("SKIP", skip_reason);
326     }
327 }
328
329 function extract_tap_comment(line)
330 {
331   # FIXME: verify there is not an off-by-one bug here.
332   if (index(line, diag_string) == 1)
333     {
334       # Strip leading `diag_string` from `line`.
335       # FIXME: verify there is not an off-by-one bug here.
336       line = substr(line, length(diag_string) + 1)
337       # And strip any leading and trailing whitespace left.
338       sub("^[ \t]*", "", line)
339       sub("[ \t]*$", "", line)
340       # Return what is left (if any).
341       return line;
342     }
343   return "";
344 }
345
346 # When this function is called, we know that line is a TAP result line,
347 # so that it matches the (perl) RE "^(not )?ok\b".
348 function setup_result_obj(line)
349 {
350   # Get the result, and remove it from the line.
351   result_obj["is_ok"] = (substr(line, 1, 2) == "ok" ? 1 : 0)
352   sub("^(not )?ok[ \t]*", "", line)
353
354   # If the result has an explicit number, get it and strip it; otherwise,
355   # automatically assing the next progresive number to it.
356   if (line ~ /^[0-9]+$/ || line ~ /^[0-9]+[^a-zA-Z0-9_]/)
357     {
358       match(line, "^[0-9]+")
359       # The final `+ 0` is to normalize numbers with leading zeros.
360       result_obj["number"] = substr(line, 1, RLENGTH) + 0
361       line = substr(line, RLENGTH + 1)
362     }
363   else
364     {
365       result_obj["number"] = testno
366     }
367
368   if (plan_seen == LATE_PLAN)
369     # No further test results are acceptable after a "late" TAP plan
370     # has been seen.
371     result_obj["is_unplanned"] = 1
372   else if (plan_seen && testno > planned_tests)
373     result_obj["is_unplanned"] = 1
374   else
375     result_obj["is_unplanned"] = 0
376
377   # Strip trailing and leading whitespace.
378   sub("^[ \t]*", "", line)
379   sub("[ \t]*$", "", line)
380
381   # This will have to be corrected if we have a "TODO"/"SKIP" directive.
382   result_obj["description"] = line
383   result_obj["directive"] = ""
384   result_obj["explanation"] = ""
385
386   # TODO: maybe we should allow a way to escape "#"?
387   if (index(line, "#") == 0)
388     return # No possible directive, nothing more to do.
389
390   # Directives are case-insensitive.
391   rx = "[ \t]*#[ \t]*([tT][oO][dD][oO]|[sS][kK][iI][pP])[ \t]*"
392
393   # See whether we have the directive, and if yes, where.
394   pos = match(line, rx "$")
395   if (!pos)
396     pos = match(line, rx "[^a-zA-Z0-9_]")
397
398   # If there was no TAP directive, we have nothing more to do.
399   if (!pos)
400     return
401
402   # Strip the directive and its explanation (if any) from the test
403   # description.
404   result_obj["description"] = substr(line, 1, pos - 1)
405   # Now remove the test description from the line, that has been dealt
406   # with already.
407   line = substr(line, pos)
408   # Strip the directive, and save its value (normalized to upper case).
409   sub("^[ \t]*#[ \t]*", "", line)
410   result_obj["directive"] = toupper(substr(line, 1, 4))
411   line = substr(line, 5)
412   # Now get the explanation for the directive (if any), with leading
413   # and trailing whitespace removed.
414   sub("^[ \t]*", "", line)
415   sub("[ \t]*$", "", line)
416   result_obj["explanation"] = line
417 }
418
419 function write_test_results()
420 {
421   print ":global-test-result: " get_global_test_result() > trs_file
422   print ":recheck: "  yn(must_recheck()) > trs_file
423   print ":copy-in-global-log: " yn(copy_in_global_log()) > trs_file
424   for (i = 0; i < test_results_index; i += 1)
425     print ":test-result: " test_results_list[i] > trs_file
426   close(trs_file);
427 }
428
429 ## ------- ##
430 ##  SETUP  ##
431 ## ------- ##
432
433 BEGIN {
434
435   '"$init_colors"'
436
437   # Properly initialized once the TAP plan is seen.
438   planned_tests = 0
439
440   COOKED_PASS = expect_failure ? "XPASS": "PASS";
441   COOKED_FAIL = expect_failure ? "XFAIL": "FAIL";
442
443   # Enumeration-like constants to remember which kind of plan (if any)
444   # has been seen.  It is important that NO_PLAN evaluates "false" as
445   # a boolean.
446   NO_PLAN = 0
447   EARLY_PLAN = 1
448   LATE_PLAN = 2
449
450   testno = 0     # Number of test results seen so far.
451   bailed_out = 0 # Whether a "Bail out!" directive has been seen.
452
453   # Whether the TAP plan has been seen or not, and if yes, which kind
454   # it is ("early" is seen before any test result, "late" otherwise).
455   plan_seen = NO_PLAN
456
457 }
458
459 ## --------- ##
460 ##  PARSING  ##
461 ## --------- ##
462
463 {
464   # Copy any input line verbatim into the log file.
465   print
466   # Parsing of TAP input should stop after a "Bail out!" directive.
467   if (bailed_out)
468     next
469 }
470
471 # TAP test result.
472 ($0 ~ /^(not )?ok$/ || $0 ~ /^(not )?ok[^a-zA-Z0-9_]/) {
473
474   testno += 1
475   setup_result_obj($0)
476   handle_tap_result()
477   next
478
479 }
480
481 # TAP plan (normal or "SKIP" without explanation).
482 /^1\.\.[0-9]+[ \t]*$/ {
483
484   # The next two lines will put the number of planned tests in $0.
485   sub("^1\\.\\.", "")
486   sub("[^0-9]*$", "")
487   handle_tap_plan($0, "")
488   next
489
490 }
491
492 # TAP "SKIP" plan, with an explanation.
493 /^1\.\.0+[ \t]*#/ {
494
495   # The next lines will put the skip explanation in $0, stripping any
496   # leading and trailing whitespace.  This is a little more tricky in
497   # thruth, since we want to also strip a potential leading "SKIP"
498   # string from the message.
499   sub("^[^#]*#[ \t]*(SKIP[: \t][ \t]*)?", "")
500   sub("[ \t]*$", "");
501   handle_tap_plan(0, $0)
502   next
503
504 }
505
506 # "Bail out!" magic.
507 /^Bail out!/ {
508
509   bailed_out = 1
510   # Get the bailout message (if any), with leading and trailing
511   # whitespace stripped.  The message remains stored in `$0`.
512   sub("^Bail out![ \t]*", "");
513   sub("[ \t]*$", "");
514   # Format the error message for the
515   bailout_message = "Bail out!"
516   if (length($0))
517     bailout_message = bailout_message " " $0
518   testsuite_error(bailout_message)
519   next
520
521 }
522
523 (comments != 0) {
524
525   comment = extract_tap_comment($0);
526   if (length(comment))
527     report("#", comment);
528
529 }
530
531 ## -------- ##
532 ##  FINISH  ##
533 ## -------- ##
534
535 END {
536
537   # A "Bail out!" directive should cause us to ignore any following TAP
538   # error, as well as a non-zero exit status from the TAP producer.
539   if (!bailed_out)
540     {
541       if (!plan_seen)
542         testsuite_error("missing test plan")
543       else if (planned_tests != testno)
544         {
545           bad_amount = testno > planned_tests ? "many" : "few"
546           testsuite_error(sprintf("too %s tests run (expected %d, got %d)",
547                                   bad_amount, planned_tests, testno))
548         }
549     }
550   write_test_results()
551
552   exit 0
553 }
554 '
555
556 # TODO: document that we consume the file descriptor 3 :-(
557 } 3>&1 >"$log_file" 2>&1
558
559 test $? -eq 0 || fatal "I/O or internal error"
560
561 # Local Variables:
562 # mode: shell-script
563 # sh-indentation: 2
564 # eval: (add-hook 'write-file-hooks 'time-stamp)
565 # time-stamp-start: "scriptversion="
566 # time-stamp-format: "%:y-%02m-%02d.%02H"
567 # time-stamp-time-zone: "UTC"
568 # time-stamp-end: "; # UTC"
569 # End: