Testing
Testing: Getting Started
Introduction
Laravel Bash is built with testing in mind. ShellCheck is our Larastan, and bats is our Pest:
./sail test
./artisan test runs shellcheck over every script, then the bats suite. Both run in CI, which then migrates and queries SQLite and Postgres for real.
Writing Tests
Tests live in tests/*.bats:
#!/usr/bin/env bats
load test_helper
@test "an unknown route is 404" {
run http GET /nope
[[ ${lines[0]} == $'HTTP/1.1 404 Not Found\r' ]]
}
run captures the output in $output and $lines, and the exit code in $status. Any command that fails, fails the test.
HTTP tests
http sends a raw request to bootstrap/handle on stdin, exactly as socat would. No server is needed:
http() {
printf '%s %s HTTP/1.1\r\nHost: localhost\r\n\r\n' "$1" "$2" | "$BASE_PATH/bootstrap/handle"
}
Isolation
Each test gets its own SQLite database, queue folders and broadcast log in bats's temporary directory, so tests can run against a live application without touching it.
Things We Learned
- bats waits for fd 3 to close. A test that starts a background worker hangs forever, because the worker inherits fd 3. Start background processes with
3>&-. - Background jobs ignore SIGINT. A non-interactive shell starts
&jobs withSIGINTignored, sokill -INTdoes nothing. Usekill -TERM. ! commandnever fails a test.set -eignores commands that start with!. Userun, then check$status.
ShellCheck
ShellCheck finds the bugs you were going to write anyway: unquoted variables, cd without || exit, local x=$(cmd) hiding exit codes. Every warning is fixed, or disabled on the line with a comment saying why.