73 / 80 · 12 Programming for QA · Bash Scripting for QA← prev⊞ allnext →☰ Read as one page
9.3Test Environment Setup Script
#!/bin/bash
set -euo pipefail
echo "=== Resetting test database ==="
psql -h localhost -U testuser -d testdb -f reset.sql
echo "=== Starting test server ==="
npm run start:test &
SERVER_PID=$!
# Wait for server to be ready (up to 30 seconds)
echo "=== Waiting for server ==="
for i in {1..30}; do
if curl -s http://localhost:3000/health > /dev/null 2>&1; then
echo "Server ready after ${i}s"
break
fi
if [ $i -eq 30 ]; then
echo "ERROR: Server did not start within 30s"
kill $SERVER_PID 2>/dev/null || true
exit 1
fi
sleep 1
done
echo "=== Running tests ==="
pytest tests/ --junitxml=results.xml
TEST_EXIT=$?
echo "=== Stopping server ==="
kill $SERVER_PID 2>/dev/null || true
echo "=== Done (exit code: $TEST_EXIT) ==="
exit $TEST_EXIT
Key Patterns in This Script
- Background process (
&and$!): Start the server in the background and capture its PID - Health check loop: Wait for the server to be ready before running tests
- Exit code capture (
$?): Save the test exit code before running cleanup - Cleanup on exit: Kill the server regardless of test outcome
- Graceful error handling:
kill $PID 2>/dev/null || truedoes not fail if the process is already dead