Mocking Commands During Script Tests
Most useful Bash scripts are glue: they call other programs. A monitoring script calls curl, a deployment script calls git and systemctl, a backup script calls rsync and mysqldump. Testing such scripts by letting them call the real programs is slow, unreliable and sometimes dangerous. The test would need a running web server, a network connection, root rights and a real service to restart, and a mistake in the script could restart a production service or delete real data.
Mocking solves this by replacing the external commands with fakes during the test. A fake, also called a mock or stub, is a small program with the same name as the real command. It does not do the real work; instead it records how it was called and returns whatever result the test asks for: success, a specific failure, or a prepared output. The test can then check two things: that the script reacts correctly to each result, and that it called the commands with the right arguments.
This lesson explains how Bash finds commands and why that makes mocking possible, shows the three common mocking techniques, builds a small reusable mock library for Bats (lesson 185), and uses it to test a script that checks a website and restarts its service.
How Bash Finds a Command
When a script runs curl https://example.com, Bash looks for something called curl in a fixed order (lesson 183): an alias (only in interactive shells), then a shell function, then a built-in command, and finally an executable file in one of the directories listed in the PATH variable, searched from left to right. The first match wins.
Every one of these lookup steps is a place where a test can insert a fake:
- A directory at the front of
PATH: an executable file namedcurlin that directory is found before/usr/bin/curl. - A shell function named
curl: functions are found before files inPATH. - A variable holding the command name, such as
"$CURL": the test sets the variable to a fake.
The first technique works for almost any script without changing it, so it is the main technique of this lesson.
Technique 1: Fake Programs in PATH
The idea is simple: create a temporary directory, write a small executable script named after the command into it, and put the directory first in PATH. Every call of that command by the script under test, and by any program it starts, now reaches the fake:
mkdir -p /tmp/mk
printf '#!/bin/sh\necho "fake curl"\n' > /tmp/mk/curl
chmod +x /tmp/mk/curl
PATH=/tmp/mk:$PATH
curl x
type -a curl
fake curl
curl is /tmp/mk/curl
curl is /usr/bin/curl
curl is /bin/curl
type -a lists all the places where curl was found, in search order: the fake comes first and hides the real program. The fake must have a shebang line and be executable, because it is started like any other program. It can be written in any language; Bash is the natural choice.
Limits of PATH Fakes
A fake in PATH cannot replace everything:
- Absolute paths bypass
PATH. If the script calls/usr/bin/curl, Bash runs that exact file and never looks atPATH:
$ /usr/bin/curl -sS http://shop.test/
curl: (6) Could not resolve host: shop.test
This is one reason why scripts should call commands by name. If a script must use absolute paths, it can read them from variables, which leads to technique 3. Three more limits apply:
Built-in commands cannot be replaced by files.
echo,printf,read,cdandtestare built into Bash and found beforePATHis searched. They rarely need to be faked; when they must, a function can override them.The fakes need some real commands themselves. The fakes in this lesson use
dirname,wc,sed,tailandcatto do their bookkeeping. Faking one of these would break the other fakes, so either avoid faking basic tools or write fakes that call them by absolute path.The hash table. An interactive shell that already ran
curlremembers its location (lesson 183). Tests start fresh processes, so this rarely matters, but if a fake seems to be ignored in a long-running shell,hash -rclears the memory.
Technique 2: Function Overrides
A shell function with the name of a command replaces that command for the shell that defines it. With export -f, Bash also passes the function to child Bash processes through the environment, so a script started from the test sees it too:
curl() { echo "fake curl: $*" >&2; return 0; }
export -f curl
./reach.sh http://shop.test/
unset -f curl
./reach.sh http://shop.test/; echo "status $?"
fake curl: --silent http://shop.test/
reachable
status 6
reach.sh is a two-line script that runs curl --silent "$1" && echo "reachable". With the exported function, it called the fake and reported success; after unset -f curl, it reached the real curl, which failed with status 6 because the host does not exist.
Function overrides are convenient for unit tests of functions loaded with source, where the code under test runs in the same shell as the test. Exported functions have two limits: only Bash scripts receive them, so a program written in another language, or a script started with sh, still calls the real command; and they are invisible in the file system, which makes them harder to inspect when something goes wrong. Fakes in PATH work for every kind of program.
Technique 3: Commands in Variables
A script can take the commands it calls from variables with defaults:
CURL=${CURL:-curl}
"$CURL" --fail "$url"
A test then runs the script with CURL=/path/to/fake. This makes the dependency explicit and also works for absolute paths, at the cost of slightly less readable scripts. It is most useful for commands whose location really varies between systems, and for scripts that deliberately use absolute paths for security reasons.
What Makes a Good Fake
Whichever technique delivers it, a fake has three jobs:
- Record each call, including all arguments, so the test can check how the command was used.
- Return a controllable result: an exit status chosen by the test, and optionally prepared output.
- Support sequences, because many scripts call the same command several times and react to changing results: a retry loop needs
curlto fail twice and then succeed.
Recording arguments correctly needs care. Writing $* to the log joins all arguments with spaces, so the calls cmd "two words" and cmd two words would look identical. printf '%q ' writes each argument in Bash's quoted form instead, which keeps the boundaries visible:
printf '%q ' --output /dev/null "two words" 'a$b'; echo
--output /dev/null two\ words a\$b
Ordinary arguments appear unchanged, so the recorded calls stay readable, while spaces and special characters are escaped.
A Reusable Mock Library for Bats
The following helper file collects these ideas into four functions. It lives next to the tests as test/mocks.bash and is loaded in a test file with load mocks:
# mocks.bash - replace external commands with recording fakes in Bats tests
#
# mock_setup create the mock directory and put it first in PATH
# mock CMD [STATUS...] fake CMD; each call exits with the next STATUS (the last repeats)
# mock_output CMD TEXT the fake CMD also prints TEXT on every call
# mock_calls CMD print the recorded calls of CMD, one line per call
mock_setup() {
MOCK_DIR="$BATS_TEST_TMPDIR/mocks"
mkdir -p "$MOCK_DIR"
PATH="$MOCK_DIR:$PATH"
}
mock() {
local cmd=$1
shift
printf '%s\n' "${@:-0}" > "$MOCK_DIR/$cmd.statuses"
: > "$MOCK_DIR/$cmd.calls"
cat > "$MOCK_DIR/$cmd" <<STUB
#!/usr/bin/env bash
# fake $cmd created by mocks.bash
dir=\$(dirname "\$0")
args=\$(printf '%q ' "\$@") # quote each argument, keep boundaries
printf '%s\n' "\${args% }" >> "\$dir/$cmd.calls"
[[ -f "\$dir/$cmd.output" ]] && cat "\$dir/$cmd.output"
n=\$(wc -l < "\$dir/$cmd.calls")
status=\$(sed -n "\${n}p" "\$dir/$cmd.statuses")
exit "\${status:-\$(tail -n 1 "\$dir/$cmd.statuses")}"
STUB
chmod +x "$MOCK_DIR/$cmd"
}
mock_output() {
printf '%s\n' "$2" > "$MOCK_DIR/$1.output"
}
mock_calls() {
cat "$MOCK_DIR/$1.calls"
}
How It Works
mock_setupcreates amocksdirectory inside the test's private temporary directory,$BATS_TEST_TMPDIR, and puts it first inPATH. Because Bats runs every test in its own process and deletes the temporary directory afterwards, fakes never leak from one test into another.mock CMD STATUS...writes three files:CMD.statuseswith one exit status per line, an empty call logCMD.calls, and the fake programCMDitself."${@:-0}"uses the given statuses, or a single0if none were given, somock sleepcreates a fake that always succeeds.- The fake program is generated from a here document (lesson 63). The delimiter
STUBis unquoted, so$cmdis replaced by the command's name while the fake is written; every$that must stay in the fake is escaped as\$. Formock curl, the generated file starts like this:
#!/usr/bin/env bash
# fake curl created by mocks.bash
dir=$(dirname "$0")
args=$(printf '%q ' "$@") # quote each argument, keep boundaries
printf '%s\n' "${args% }" >> "$dir/curl.calls"
- Status sequences. On each call, the fake first appends its arguments to the call log, then counts the lines in the log to find out which call this is, and takes the status from the same line of the statuses file. When the list is exhausted,
sedprints nothing, and the fake falls back to the last status in the list.mock curl 7 7 7 0therefore fails three times with status 7 (curl's "failed to connect") and succeeds on every later call;mock curl 22fails on every call with status 22 (an HTTP error status with--fail). - Output.
mock_outputstores text that the fake prints on every call, for commands whose output the script uses. mock_callsprints the call log, one line per call, in a form tests can compare with expected strings or count withwc -l.
The Script Under Test
check-site.sh checks a web application's health URL. If several attempts in a row fail, it restarts the application's systemd service and checks once more:
#!/usr/bin/env bash
#
# check-site.sh - check a web application and restart its service when it stays down
#
# Usage: check-site.sh URL SERVICE
#
# The URL is tried up to ATTEMPTS times (default 3), WAIT seconds apart (default 5).
# If every attempt fails, the systemd SERVICE is restarted and checked once more.
# Exit status: 0 healthy, 1 restarted but still failing or restart failed, 2 usage error
set -euo pipefail
ATTEMPTS=${ATTEMPTS:-3}
WAIT=${WAIT:-5}
log() { printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*"; }
(( $# == 2 )) || { sed -n '5s/^# //p' "$0" >&2; exit 2; }
url=$1 service=$2
is_up() {
curl --fail --silent --show-error --max-time 10 --output /dev/null "$url"
}
for (( i = 1; i <= ATTEMPTS; i++ )); do
if is_up; then
log "OK $url (attempt $i)"
exit 0
fi
log "attempt $i of $ATTEMPTS failed"
(( i < ATTEMPTS )) && sleep "$WAIT"
done
log "restarting $service"
if ! sudo systemctl restart "$service"; then
log "ERROR: could not restart $service"
exit 1
fi
sleep "$WAIT"
if is_up; then
log "RECOVERED $url after restarting $service"
exit 0
fi
log "ERROR: $url still down after restarting $service"
exit 1
Testing it for real would require a web server that can be made to fail on demand, permission to restart a service, and patience: a single run of the "stays down" case waits 15 seconds. Four commands make it hard to test, and each is replaced by a fake:
| Command | Problem in tests | Fake behavior |
|---|---|---|
curl | needs a server whose health the test controls | status sequence chosen per test |
sudo | needs root rights; would restart a real service | records the call, succeeds or fails as asked |
sleep | makes tests slow | returns immediately, records the duration |
date | output changes every second, so lines cannot be compared exactly | prints a fixed timestamp |
Faking sudo rather than systemctl is deliberate: the script calls sudo, which in turn would call systemctl. Replacing the outermost command keeps the test from ever needing administrator rights, and the recorded call systemctl restart shop still shows exactly what would have been executed.
A Complete Example: Testing check-site.sh
The test file creates the common fakes in setup and adds a curl fake with the right behavior in each test:
#!/usr/bin/env bats
#
# Tests for bin/check-site.sh. curl, sudo, sleep and date are replaced by fakes,
# so the tests need no network, no root rights and no waiting.
bats_require_minimum_version 1.5.0
setup() {
load mocks
mock_setup
mock sleep # never wait
mock sudo # never restart anything for real
mock date
mock_output date '2026-12-01 09:00:00'
CHECK="$BATS_TEST_DIRNAME/../bin/check-site.sh"
URL=http://shop.test/health
}
@test "a healthy site is reported once, without waiting or restarting" {
mock curl 0
run -0 "$CHECK" "$URL" shop
[ "$output" = "2026-12-01 09:00:00 OK $URL (attempt 1)" ]
[ -z "$(mock_calls sleep)" ]
[ -z "$(mock_calls sudo)" ]
}
@test "curl is called with fail, timeout and the URL" {
mock curl 0
run -0 "$CHECK" "$URL" shop
[ "$(mock_calls curl)" = "--fail --silent --show-error --max-time 10 --output /dev/null $URL" ]
}
@test "a short outage is retried after waiting" {
mock curl 7 0 # first call fails, second succeeds
run -0 "$CHECK" "$URL" shop
[ "${lines[0]}" = "2026-12-01 09:00:00 attempt 1 of 3 failed" ]
[ "${lines[1]}" = "2026-12-01 09:00:00 OK $URL (attempt 2)" ]
[ "$(mock_calls sleep)" = "5" ]
[ -z "$(mock_calls sudo)" ]
}
@test "a site that stays down is restarted and checked again" {
mock curl 7 7 7 0 # three failures, then healthy after the restart
run -0 "$CHECK" "$URL" shop
[ "$(mock_calls sudo)" = "systemctl restart shop" ]
[ "$(mock_calls curl | wc -l)" -eq 4 ]
[ "$(mock_calls sleep | wc -l)" -eq 3 ]
[ "${lines[-1]}" = "2026-12-01 09:00:00 RECOVERED $URL after restarting shop" ]
}
@test "a site still down after the restart exits with status 1" {
mock curl 22 # every call fails
run -1 "$CHECK" "$URL" shop
[[ ${lines[-1]} == *"ERROR: $URL still down after restarting shop" ]]
}
@test "a failed restart exits with status 1 and skips the final check" {
mock curl 7
mock sudo 1
run -1 "$CHECK" "$URL" shop
[[ ${lines[-1]} == *"ERROR: could not restart shop" ]]
[ "$(mock_calls curl | wc -l)" -eq 3 ]
}
@test "ATTEMPTS and WAIT can be changed through the environment" {
mock curl 7
ATTEMPTS=2 WAIT=1 run -1 "$CHECK" "$URL" shop
[ "$(mock_calls sleep)" = $'1\n1' ]
}
@test "a missing argument is a usage error" {
run -2 "$CHECK" "$URL"
[[ $output == Usage:* ]]
}
What the Tests Check
- Results and reactions. Each test sets up one situation through the
curlfake's status sequence, from "healthy at once" to "down even after a restart", and checks the script's exit status and messages. Becausedateis fixed, whole lines can be compared exactly. - Interactions. The tests also check what the script did with the outside world: that a healthy site causes no restart (
mock_calls sudois empty), that a restart calls exactlysystemctl restart shop, thatcurlis called with--failand a timeout, and how often the script waited. These checks catch bugs that the output alone would not reveal, such as a script that prints "OK" but forgot--fail, which would makecurlreport success for an HTTP 500 response. - Counting calls. In the restart test,
curlmust run four times (three attempts plus the check after the restart) andsleepthree times (two waits between attempts plus one after the restart). If the script failed to skip the wait after the last attempt, or forgot the final check, the counts would differ. - A negative path that must not happen. When the restart itself fails, the script must stop without checking again; the test verifies that
curlran exactly three times. - Configuration.
ATTEMPTS=2 WAIT=1 run ...sets the two variables only for this one command. The recordedsleepcalls,1and1, prove that the script used the configured wait time.$'1\n1'is a string with a newline between the two values (lesson 47).
Running the Tests
All eight tests pass, and the whole run takes well under a second because nothing waits and nothing goes over the network. As in lesson 185, Bats itself could not be installed where this lesson was prepared, which had no network access; the tests were executed with a stand-in harness that implements the Bats features used here, plus load, and prints TAP output in the format of bats --tap:
$ bats --tap test/check-site.bats
1..8
ok 1 a healthy site is reported once, without waiting or restarting
ok 2 curl is called with fail, timeout and the URL
ok 3 a short outage is retried after waiting
ok 4 a site that stays down is restarted and checked again
ok 5 a site still down after the restart exits with status 1
ok 6 a failed restart exits with status 1 and skips the final check
ok 7 ATTEMPTS and WAIT can be changed through the environment
ok 8 a missing argument is a usage error
To confirm that the tests really guard the behavior, a plausible bug was introduced: the condition (( i < ATTEMPTS )) && was removed, so the script also waits after its last failed attempt, which delays every restart for no reason. Two tests detect it through the recorded sleep calls, although every message the script prints is still correct:
not ok 4 a site that stays down is restarted and checked again
# (in test file test/check-site.bats, line 47)
# `[ "$(mock_calls sleep | wc -l)" -eq 3 ]' failed
...
not ok 7 ATTEMPTS and WAIT can be changed through the environment
# (in test file test/check-site.bats, line 68)
# `[ "$(mock_calls sleep)" = '1
1' ]' failed
Deciding What to Mock
Mocks make tests fast and safe, but every mock is an assumption about how the real command behaves. If the assumption is wrong, the tests pass and the script still fails in production. A few guidelines keep that risk small:
- Mock at the boundary. Replace the commands that reach outside the test: the network (
curl,ssh), the system (sudo,systemctl,apt-get), time (sleep,date) and anything destructive. Let simple local tools such asgrep,sedandsortrun for real; they are fast and deterministic, and faking them only adds assumptions. - Base fake behavior on real behavior. Use real exit codes, like curl's 7 and 22, and real output formats, copied from an actual run. A fake that returns statuses the real program never uses tests a situation that cannot happen.
- Prefer checking results over checking every call. Checking that the right service was restarted is valuable; checking the exact order of every option makes tests break whenever the script is reformatted. Check arguments when they carry meaning, as
--failand--max-timedo here. - Keep some tests against the real commands. A few integration tests in a disposable environment, such as a Docker container with a real web server and service (lessons 175 and 176), confirm that the assumptions built into the fakes still hold. Fast mocked tests run on every change; slower real tests run less often.
The next lesson looks at testing error paths and exit codes in more depth; fakes like the ones in this lesson are often the easiest way to provoke the failures those tests need.