test_api.sh (2187B)
1 #!/bin/bash 2 # test_api.sh — Run API tests against the Django app 3 # 4 # Usage: ./test_api.sh <base_url> <output_dir> 5 6 set -euo pipefail 7 8 BASE_URL="${1:-http://localhost:8000}" 9 OUTPUT_DIR="${2:-.}" 10 11 PASSED=0 12 FAILED=0 13 RESULTS="" 14 15 run_test() { 16 local name="$1" 17 local url="$2" 18 local expected_code="$3" 19 local expected_body="$4" # substring to look for in response body 20 21 echo -n "TEST: $name ... " 22 23 local http_code body 24 body=$(curl -s -w '\n%{http_code}' "$url" 2>&1) || true 25 http_code=$(echo "$body" | tail -1) 26 body=$(echo "$body" | sed '$d') 27 28 local status="PASS" 29 local detail="" 30 31 if [ "$http_code" != "$expected_code" ]; then 32 status="FAIL" 33 detail="expected HTTP $expected_code, got $http_code" 34 elif [ -n "$expected_body" ] && ! echo "$body" | grep -q "$expected_body"; then 35 status="FAIL" 36 detail="response body missing '$expected_body'" 37 fi 38 39 if [ "$status" = "PASS" ]; then 40 echo "PASS" 41 PASSED=$((PASSED + 1)) 42 else 43 echo "FAIL ($detail)" 44 FAILED=$((FAILED + 1)) 45 fi 46 47 RESULTS+="$status $name (HTTP $http_code) $detail\n" 48 } 49 50 echo "========================================" 51 echo "API Tests — $BASE_URL" 52 echo "========================================" 53 echo 54 55 # --- Health endpoint --- 56 run_test "GET /health/ returns 200" "$BASE_URL/health/" 200 '"status"' 57 run_test "GET /health/ contains ok" "$BASE_URL/health/" 200 '"ok"' 58 59 # --- Items endpoint --- 60 run_test "GET /items/ returns 200" "$BASE_URL/items/" 200 '"items"' 61 run_test "GET /items/ returns JSON array" "$BASE_URL/items/" 200 'items' 62 63 # --- Not Found --- 64 run_test "GET /nonexistent/ returns 404" "$BASE_URL/nonexistent/" 404 '' 65 66 echo 67 echo "========================================" 68 echo "Results: $PASSED passed, $FAILED failed" 69 echo "========================================" 70 71 # Write results file 72 { 73 echo "API Test Results" 74 echo "================" 75 echo "Base URL: $BASE_URL" 76 echo "Date: $(date -u)" 77 echo 78 echo -e "$RESULTS" 79 echo "Total: $PASSED passed, $FAILED failed" 80 } > "$OUTPUT_DIR/api-test-results.txt" 81 82 if [ "$FAILED" -gt 0 ]; then 83 exit 1 84 fi