🎓 A1Learner
🔍
0 of 45 lessons completed

Bash Test Fixtures

Test fixtures are the temporary files and folders a test needs to run. Setup builds a fresh fixture before each test, and teardown removes it after.

Setup and teardown around a temp dir

Setup creates a temp dir and confirms it exists. Teardown removes it and prints a fixed label, never the path.

setup() {
  dir=$(mktemp -d)
  if [ -d "$dir" ]; then
    echo "temp dir ready"
  fi
}
teardown() {
  if [ -n "$dir" ]; then
    rm -rf "$dir"
  fi
  echo "temp dir removed"
}
setup
teardown

A fixture file inside the temp dir

Setup writes a known input file into the fresh temp dir. The test reads that file, then teardown cleans up.

setup() {
  dir=$(mktemp -d)
  printf 'hello
' > "$dir/input.txt"
}
teardown() {
  rm -rf "$dir"
}
setup
if [ -f "$dir/input.txt" ]; then
  echo "fixture ready"
fi
cat "$dir/input.txt"
teardown
echo "cleaned up"

A fresh dir per test proves isolation

The first test writes a marker file and its teardown removes the whole dir. The second test starts fresh and finds no marker.

setup() {
  dir=$(mktemp -d)
}
teardown() {
  rm -rf "$dir"
}
setup
printf 'x
' > "$dir/marker.txt"
if [ -f "$dir/marker.txt" ]; then
  echo "test A: marker present"
fi
teardown
setup
if [ -f "$dir/marker.txt" ]; then
  echo "test B: leaked"
else
  echo "test B: isolated"
fi
teardown

Example

passed=0
setup() {
  dir=$(mktemp -d)
  printf 'hello
' > "$dir/input.txt"
}
teardown() {
  rm -rf "$dir"
}
test_read() {
  setup
  if grep -q 'hello' "$dir/input.txt"; then
    echo "PASS: read fixture"
    passed=$((passed + 1))
  else
    echo "FAIL: read fixture"
  fi
  teardown
}
test_missing() {
  setup
  if [ -f "$dir/nope.txt" ]; then
    echo "FAIL: missing file"
  else
    echo "PASS: missing file absent"
    passed=$((passed + 1))
  fi
  teardown
}
test_read
test_missing
echo "$passed passed, 0 failed"

Key points

  • Setup: a function that builds the fixture a test needs, before the test runs.
  • Teardown: a function that removes the fixture after the test, pass or fail.
  • mktemp -d: create a fresh temporary directory for one test, and never print its path.
  • Existence only: assert that the temp dir exists, and print a fixed label instead of the path.
  • Isolation: a fresh dir per test stops one test from seeing another test's files.
  • Cleanup duty: teardown runs even for a failing test, so temp files never pile up.
  • Honest limit: fixtures prove behaviour with known inputs, not with real-world data.

In this example, a fixture harness runs two tests with fresh temp dirs. Setup builds a temp dir with a known input file for each test. The first test reads the fixture, and the second test checks that an absent file stays absent. Teardown removes each dir, and the final line reports two passes.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Why does each test get its own temp dir?