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