Skip to content

Instantly share code, notes, and snippets.

@pretorh
Last active January 1, 2023 08:06
Show Gist options
  • Save pretorh/57f9d4bd69bf3d9d78c2ecd540384fdb to your computer and use it in GitHub Desktop.
Save pretorh/57f9d4bd69bf3d9d78c2ecd540384fdb to your computer and use it in GitHub Desktop.
Bash test helper to general TAP output

shell script that can be sourced to have produce TAP output for test files

setup

  • create tests/setup.sh
  • create test files, ex tests/example.test.sh
  • run tests, and on success call ok <test name> or fail <test name> (or skip <test-name>)

do need to ensure that none of the tests output TAP related output (ex redirecting stdout)

using prove

Can now use prove to run tests: prove --directives tests/*test.sh:

tests/runs-commands.test.sh .. 
not ok 4 d # TODO: skipped
not ok 5 e # TODO: not yet implemented
ok
All tests successful.
Files=1, Tests=5,  0 wallclock secs ( 0.02 usr  0.00 sys +  0.01 cusr  0.00 csys =  0.03 CPU)
Result: PASS

can run directly

scripts can still be run directly to show the raw

#!/usr/bin/env bash
set -e
cd "$(dirname "$0")"
source ./setup.sh
run_2_tests() {
# tests can be in functions
ok "b"
ok "c"
}
ok "a"
run_2_tests
skip "d"
skip "e" "not yet implemented"
# skip "f" "commented out, wont count"
#!/usr/bin/env bash
set -e
tests_ran=0
ok() {
_record_test_result "ok" "$1"
}
fail() {
local reason=${2-'failed'}
_record_test_result "not ok" "$1" "# $reason"
}
skip() {
local reason=${2-'skipped'}
_record_test_result "not ok" "$1" "# TODO: $reason"
}
_record_test_result() {
local state=$1
local name=$2
local comment=$3
tests_ran=$((tests_ran + 1))
echo "$state $tests_ran $name $comment"
}
cd ..
total_tests=$(grep -Ec '^ *(ok|fail|skip) ' "$0" || echo "0")
echo "1..$total_tests"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment