Testing Scripts with Stubs and Assertions

Testing Scripts with Stubs and Assertions in Bash: A commercial flight simulator is a full cockpit bolted to hydraulic legs, and every dial, switch, and…

The Analogy: The Flight Simulator and the Checkride

A commercial flight simulator is a full cockpit bolted to hydraulic legs, and every dial, switch, and warning lamp inside it is live. Nothing outside the cockpit is real. The engines, the weather, the air-traffic controllers, the runway lights at the far end of the strip -- all of it is synthesized by the simulator's computers and fed into the cockpit through exactly the same wires and signals that the real aircraft would use. The crew inside cannot tell, from the instruments alone, that they are sitting in a hangar.

The instructor sits at a station behind the seats and scripts the session. They set the cloud base, they inject an engine fire ten seconds after rotation, they fail a hydraulic pump at cruise altitude. Because the whole world is fabricated, the one-in-a-million emergency can be staged on demand, at no risk, and replayed identically for every crew that comes through. Each scenario has a defined right answer written down in advance: gear up by this speed, the memory drill in this order, the checklist read aloud. The checkride is graded against that expected sequence, not against the instructor's mood.

The reason for all this fabrication is isolation and repeatability. You are testing the crew, and only the crew -- not the airline's real jet, not real fuel, not two hundred real passengers behind them. A stubbed engine that "catches fire" precisely on cue lets you prove the crew handles the failure without ever endangering a soul, and the same failure lands at the same second for the next crew and the next. The graded sequence turns a judgement call into a repeatable pass-or-fail measurement.

But a simulator is only ever as honest as the models inside it. If the synthesized engine spins down more gently than a real one, or an instrument's lag is left out of the model, a crew can pass every checkride and still be caught out by the actual aircraft. Worse, a scenario nobody thought to script is a scenario nobody is ever tested against. The green result certifies performance against the situations the instructor imagined and modeled -- not against reality. Treat the simulator as a substitute for the aircraft rather than a rehearsal for it, and the gap between the model and the metal is exactly where the accident waits.


Syntax or Core Structure

A test does three things: run the code under test, compare what it produced against what you expected, and report the verdict. In Bash the smallest useful tool is an assertion helper -- a function that takes an expected value and an actual value and prints PASS or FAIL. Everything else is built on top of it.

assert_equals() {
  local expected="$1" actual="$2" name="${3:-}"
  if [ "$expected" = "$actual" ]; then
    echo "PASS $name"
  else
    echo "FAIL $name (expected '$expected', got '$actual')"
    return 1
  fi
}

# a function we want to test
add() { echo $(( $1 + $2 )); }

assert_equals 5  "$(add 2 3)"  "add 2 + 3"
assert_equals 15 "$(add 10 5)" "add 10 + 5"

The helper captures the function's output with command substitution, $(add 2 3), and compares it as a string. When the two sides match it prints a pass line and returns success; when they differ it prints both values so you can see the discrepancy and returns a non-zero status.

Output:

PASS add 2 + 3
PASS add 10 + 5

A helper that returns non-zero on failure is what lets a whole suite add up its verdicts and, at the end, exit non-zero if anything failed -- the single fact a continuous-integration system reads to decide whether the build is red or green.


Technical Depth: Isolating the Unit and Faking Its World

Two techniques do most of the work in Bash testing. The first isolates the code so you can call it directly; the second replaces its external dependencies with fakes you control.

Assertion helpers you will actually want

One equality check is rarely enough. A small kit covers most of what a suite needs, and each helper is just a comparison wrapped in a name and a verdict.

HelperWhat it checksFails when
assert_equalstwo strings are identicalthey differ in any character
assert_containsa substring is presentthe needle is missing from the haystack
assert_statusthe last command's exit codethe code is not the expected number

The status helper is the one people forget. It runs the command itself, captures $? immediately, and compares it to the code you expected -- the right way to test that a function fails when it should.

assert_status() {
  local expected="$1"; shift
  "$@"; local got=$?
  if [ "$got" -eq "$expected" ]; then
    echo "PASS status $* -> $got"
  else
    echo "FAIL status $* (expected $expected, got $got)"
  fi
}

assert_status 0 true
assert_status 1 false

Output:

PASS status true -> 0
PASS status false -> 1

Notice the order inside assert_status: it runs the command and reads $? on the very next line. That immediacy is not optional. $? holds the status of the last command only, so a stray echo or even an if between the call and the capture overwrites it with that command's status, and the assertion then grades the wrong thing. The same discipline matters for pipelines, where $? reflects only the final stage unless you consult PIPESTATUS. Capture the status into a named local the instant the command returns, then assert against the copy.

Stubbing a dependency two ways

When the code calls something external -- date, curl, aws -- you replace it with a fake so the test is deterministic and offline. There are two mechanisms, and the difference between them is scope.

ApproachHow you do itWhat it affects
Function shadowdefine a shell function with the command's namethe current shell and its subshells only
PATH shimput a fake executable early on PATHthe current shell and any external programs it runs

A function named date shadows the real date everywhere in the current shell, including inside command substitution -- but it is invisible to a separate program the script runs, unless you export -f it. A fake executable placed first on PATH is seen by child processes too, which is what you need when the code under test runs a genuine external tool.

# function shadow: stub 'date' so a report header is deterministic
date() { echo "2020-01-01"; }
report() { echo "generated on $(date)"; }
report

Output:

generated on 2020-01-01

The PATH shim reaches further. Here forecast.sh runs an external weather command, and a fake executable on PATH answers in its place -- even though the script runs in a child process.

# forecast.sh contains:   echo "today: $(weather)"
# stubs/weather is a fake executable we control:
#   #!/usr/bin/env bash
#   echo "sunny 21C"

PATH="$PWD/stubs:$PATH" bash forecast.sh

Output:

today: sunny 21C

Real World Example: A Test Suite for a Report Library

Here is a small library of report-building functions and a hand-rolled test suite that exercises it. The library, user-report.sh, defines three functions and runs nothing when sourced. One of them, report_header, calls the external date, which the test will stub so the suite never depends on today's date.

#!/usr/bin/env bash
# user-report.sh -- functions for building a user activity report

format_line() {
  local name="$1" count="$2"
  echo "$name: $count events"
}

total_events() {
  local sum=0 name count
  while read -r name count; do
    sum=$((sum + count))
  done
  echo "$sum"
}

report_header() {
  echo "report for $(date +%F)"
}

The test file sources that library, defines its own assert_equals that also tallies passes and failures, stubs date with a one-line function, and then makes three assertions -- one per library function. The final line exits with the failure count, so a green suite exits 0 and any failure makes the script exit non-zero.

#!/usr/bin/env bash
# test-user-report.sh -- unit tests for user-report.sh
set -uo pipefail

source ./user-report.sh

pass=0
fail=0

assert_equals() {
  local expected="$1" actual="$2" name="$3"
  if [ "$expected" = "$actual" ]; then
    echo "PASS $name"
    pass=$((pass + 1))
  else
    echo "FAIL $name (expected '$expected', got '$actual')"
    fail=$((fail + 1))
  fi
}

# stub the external 'date' so the header is deterministic
date() { echo "2020-05-01"; }

assert_equals "ada: 3 events" "$(format_line ada 3)" "format_line"
assert_equals "6" "$(printf '%s\n' 'ada 2' 'bob 4' | total_events)" "total_events"
assert_equals "report for 2020-05-01" "$(report_header)" "report_header"

echo "passed: $pass  failed: $fail"
exit "$fail"

Run it with bash test-user-report.sh. The stub makes report_header produce a fixed date, total_events sums the piped pairs, and format_line builds its string; all three match, so the suite passes and exits 0.

Output:

PASS format_line
PASS total_events
PASS report_header
passed: 3  failed: 0

This suite is honest about what it covers and silent about what it does not, and that gap is the real lesson. The date stub ignores its arguments entirely -- it returns 2020-05-01 whether the code calls date +%F, date -u, or date with no arguments at all, so a test can pass while the production code passes a flag the real date would reject. total_events is never tested with empty input, non-numeric counts, or a final line lacking a trailing newline, and read behaves differently in each case. And because the stub is a shell function, it works only because the suite sources the library into the same shell; the moment the code under test ran date from a child process the function stub would be invisible and the test would silently exercise the real clock. A passing suite here means "correct for the three inputs I imagined," which is exactly the flight simulator's promise and exactly its limit.


Common Mistakes

  1. Testing the script by running it instead of sourcing it. If your test executes the whole script, you test only its top-level path and cannot call individual functions in isolation. Split the code into a sourceable library of functions plus a thin entry point, and source the library in the test.
  1. Writing a stub that does not behave like the real command. A date stub that ignores flags, or a curl stub that always succeeds, lets tests pass against behavior the real tool would never produce. Make the stub honor the arguments and exit codes your code actually depends on.
  1. Using == inside [ ] and assuming it is portable. In [ ] the portable string-equality operator is =; == is a bashism that fails under a plain sh. Use = in [ ], or switch to [[ ]] deliberately.
  1. Letting set -e kill the suite on the first failing assertion. With set -e, a helper called as a bare command that returns non-zero aborts the whole run, so you never see the other results. Omit -e in the harness, or make the helper always return zero after tallying.
  1. Depending on test order or shared state. Tests that pass only because an earlier test left a file or a variable behind break the moment you run one in isolation or reorder them. Make each test set up and tear down its own fixtures.
  1. Asserting on formatted output instead of the value. Comparing an entire log line, timestamps and all, makes the test brittle and non-deterministic. Assert on the specific value you care about, and stub anything that would otherwise vary between runs.
  1. Forgetting that a function stub is not exported to child processes. A date() { ...; } function shadows the command in the current shell only. If the code under test runs date from a separate bash -c or an external script, use a PATH shim or export -f instead.
  1. Ignoring the suite's exit status. If the harness always exits 0, CI reports green even when assertions failed. Tally failures and exit "$fail" so the exit code reflects the result.
  1. Leaving stub directories or fixtures on PATH after the run. A stubs directory left prepended to PATH, or a fixture file left in place, can poison later commands in the same shell or the next test. Scope the PATH change to a single invocation, or clean up in a trap.

Best Practices

  • Structure code as a sourceable library plus a thin runner. Keep the logic in functions that do nothing on source, and put the "run it" part behind a guard like if [ "${BASH_SOURCE[0]}" = "$0" ]; then main "$@"; fi. Tests then source the functions without triggering execution.
  • Make stubs match the real contract. A stub should accept the same arguments and return the same exit codes as the tool it replaces, so a passing test says something true about the real dependency.
  • Assert on values, not on volatile text. Compare the specific number, field, or status you care about, and stub clocks, hostnames, and random sources so the same input always yields the same output.
  • Give every assertion a name. A bare PASS or FAIL tells you nothing at three in the morning; a name like total_events_sums_pairs points straight at the broken function.
  • Tally results and exit with the failure count. End the suite with exit "$fail" so a single non-zero exit tells CI the build is red and a zero tells it green.
  • Scope stubs to the smallest region that needs them. Prefer PATH="$PWD/stubs:$PATH" some-command on one line over exporting a polluted PATH for the rest of the shell, and drop a function stub with unset -f once a later test needs the real command.
  • Keep tests fast and offline. A suite that hits the network or sleeps is a suite people quietly stop running. Stub the slow and the remote so the whole thing finishes in under a second.
  • Run the suite in CI on every change. Tests that run only when someone remembers add little; wire bash test-*.sh into the pipeline so a red suite blocks the merge automatically.

Practice Exercises

  1. Build the three-helper kit. Write assert_equals, assert_contains, and assert_status in one file. assert_contains should pass when its second argument contains the first as a substring, and assert_status should run a command and compare $? to an expected code. Prove each with one passing and one failing call.
  1. Make a flaky function deterministic. Given a greeting function that prints hello, it is $(date +%A), write a test that stubs date so the assertion does not depend on which day you run it. Confirm the same test passes on any day.
  1. Stub an external tool with a PATH shim. Write a script that calls an external curl to fetch a URL, then a test that puts a fake curl first on PATH so the script runs offline. Assert on the script's output and confirm the real curl is never contacted.
  1. Turn the suite red on purpose. Take a passing suite, break one expected value, and confirm the suite prints the failing assertion with both values and exits non-zero. Then fix it and confirm the exit code returns to 0.