Testing with portable assertions
Write a small test script that detects faulty helper behavior.
An assertion is a comparison
A test calls code with a known input and compares its actual behavior with an expected result. In Bash, a small assertion function can use [ "$actual" = "$expected" ], print a diagnostic to stderr, and return nonzero when the values differ. Quote both sides so empty strings remain valid test arguments.
Test boundaries, not just one comfortable example. If a helper classifies values below 20 as low, try 19, 20 and 21. Test errors too: a valid-looking output alongside a failing status may not satisfy the function’s contract.
Make the test fail for the right reason
A test script should exit nonzero when any assertion fails, even if a later printf succeeds. Record failures explicitly or exit at the point of failure. Tests that always print PASS cannot establish that the code worked.
Here you write tests for a supplied helper rather than implement the helper itself. The browser checks replace that helper with several intentionally faulty versions. Your tests must accept the correct implementation and reject the faulty ones. Grades come from trusted exit/output/filesystem observations outside your Bash process; terminal text never declares completion.
assert_equal() {
if [ "$1" != "$2" ]; then printf 'Expected <%s>, got <%s>\n' "$2" "$1" >&2; return 1; fi
}
actual=$(printf 'ready')
assert_equal "$actual" ready && printf 'Assertion passed\n'
Put it into practice.
Source `capacity.sh` and test its `capacity_label` function. It must return `low` for 19 and `ok` for both 20 and 21, always with status 0. Print only `3 checks passed` and exit 0 if all three cases satisfy this contract. Otherwise print `Check failed` to stderr, no stdout, and exit nonzero. Your script must reject a wrong threshold, an always-ok helper, and a helper that prints the right text but returns failure.
See an explained solution
. ./capacity.sh || exit 1
fail() { printf 'Check failed\n' >&2; exit 1; }
assert_label() {
local actual
actual=$(capacity_label "$1") || fail
[ "$actual" = "$2" ] || fail
}
assert_label 19 low
assert_label 20 ok
assert_label 21 ok
printf '3 checks passed\n'
The test checks both the value and status. Boundary cases catch an off-by-one threshold, and the final message appears only after every assertion succeeds.