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