乐闻世界logo
搜索文章和话题

How to write automated test scripts using cURL?

3月6日 23:06

cURL is a powerful tool for writing API automation test scripts. Combined with Shell scripts, it can implement complete test workflows including test execution, result validation, and report generation.

Basic Test Script Structure

bash
#!/bin/bash # Basic API test script API_BASE="https://api.example.com/v1" TOKEN="your_bearer_token" PASSED=0 FAILED=0 # Test function run_test() { local name="$1" local expected_status="$2" shift 2 echo "Running test: $name" # Execute request and get status code status=$(curl -s -o /dev/null -w "%{http_code}" "$@") if [ "$status" = "$expected_status" ]; then echo "✅ PASS: $name (Status: $status)" ((PASSED++)) else echo "❌ FAIL: $name (Expected: $expected_status, Got: $status)" ((FAILED++)) fi } # Execute tests run_test "GET users" 200 -H "Authorization: Bearer $TOKEN" "$API_BASE/users" run_test "GET user by ID" 200 -H "Authorization: Bearer $TOKEN" "$API_BASE/users/1" run_test "POST create user" 201 -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"name":"test"}' "$API_BASE/users" run_test "DELETE user" 204 -X DELETE -H "Authorization: Bearer $TOKEN" "$API_BASE/users/999" # Output results echo "" echo "Test Results:" echo " Passed: $PASSED" echo " Failed: $FAILED" echo " Total: $((PASSED + FAILED))" exit $FAILED

Response Content Validation

bash
#!/bin/bash # Response content validation test API_BASE="https://api.example.com/v1" TOKEN="your_bearer_token" # JSON validation function assert_json_field() { local response="$1" local field="$2" local expected="$3" actual=$(echo "$response" | jq -r "$field") if [ "$actual" = "$expected" ]; then echo "✅ PASS: Field $field = $expected" return 0 else echo "❌ FAIL: Field $field expected '$expected', got '$actual'" return 1 fi } # Test user API echo "Testing User API..." # Create user response=$(curl -s -X POST \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"name":"John","email":"john@example.com"}' \ "$API_BASE/users") # Validate response assert_json_field "$response" ".name" "John" assert_json_field "$response" ".email" "john@example.com" assert_json_field "$response" ".status" "active" # Verify response contains specific field if echo "$response" | jq -e '.id' > /dev/null; then echo "✅ PASS: Response contains 'id' field" else echo "❌ FAIL: Response missing 'id' field" fi

Performance Test Script

bash
#!/bin/bash # API performance test script API_URL="https://api.example.com/v1/users" TOKEN="your_bearer_token" CONCURRENT=10 REQUESTS=100 # Single request performance test echo "Single Request Performance:" curl -w " DNS Lookup: %{time_namelookup}s TCP Connect: %{time_connect}s SSL Handshake: %{time_appconnect}s TTFB: %{time_starttransfer}s Total Time: %{time_total}s Size: %{size_download} bytes Speed: %{speed_download} bytes/s " \ -o /dev/null -s \ -H "Authorization: Bearer $TOKEN" \ "$API_URL" # Concurrent performance test echo "" echo "Concurrent Load Test ($CONCURRENT concurrent, $REQUESTS total):" start_time=$(date +%s) # Use xargs for concurrent requests seq $REQUESTS | xargs -P $CONCURRENT -I {} \ curl -s -o /dev/null -w "%{http_code},%{time_total}\n" \ -H "Authorization: Bearer $TOKEN" \ "$API_URL" > results.txt end_time=$(date +%s) duration=$((end_time - start_time)) # Analyze results echo "Results Analysis:" echo " Total Time: ${duration}s" echo " Requests/sec: $(echo "scale=2; $REQUESTS / $duration" | bc)" echo " Success Rate: $(grep -c "^200" results.txt) / $REQUESTS" echo " Avg Response Time: $(awk -F',' '{sum+=$2; count++} END {print sum/count}' results.txt)s" rm results.txt

Integration Test Flow

bash
#!/bin/bash # Complete integration test flow set -e # Exit immediately on error API_BASE="https://api.example.com/v1" TOKEN="your_bearer_token" TEST_USER_ID="" echo "========== API Integration Tests ==========" # 1. Health check echo "1. Health Check" curl -sf "$API_BASE/health" | jq -e '.status == "ok"' echo "✅ Health check passed" # 2. Create test data echo "" echo "2. Create Test User" response=$(curl -s -X POST \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"name":"Test User","email":"test@example.com"}' \ "$API_BASE/users") TEST_USER_ID=$(echo "$response" | jq -r '.id') echo "✅ Created user with ID: $TEST_USER_ID" # 3. Verify creation echo "" echo "3. Verify User Creation" curl -sf -H "Authorization: Bearer $TOKEN" \ "$API_BASE/users/$TEST_USER_ID" | jq -e '.name == "Test User"' echo "✅ User verified" # 4. Update operation echo "" echo "4. Update User" curl -s -X PATCH \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"name":"Updated Name"}' \ "$API_BASE/users/$TEST_USER_ID" | jq -e '.name == "Updated Name"' echo "✅ User updated" # 5. Delete test data echo "" echo "5. Cleanup" curl -s -X DELETE -H "Authorization: Bearer $TOKEN" \ "$API_BASE/users/$TEST_USER_ID" echo "✅ Test user deleted" echo "" echo "========== All Tests Passed =========="

Test Report Generation

bash
#!/bin/bash # Generate HTML test report API_BASE="https://api.example.com/v1" TOKEN="your_bearer_token" REPORT_FILE="test-report.html" # Initialize report cat > "$REPORT_FILE" << 'EOF' <!DOCTYPE html> <html> <head> <title>API Test Report</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } .pass { color: green; } .fail { color: red; } table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #4CAF50; color: white; } </style> </head> <body> <h1>API Test Report</h1> <p>Generated: $(date)</p> <table> <tr> <th>Test Name</th> <th>Method</th> <th>Status</th> <th>Duration</th> <th>Result</th> </tr> EOF # Execute tests and record results run_test() { local name="$1" local method="$2" local url="$3" shift 3 start=$(date +%s.%N) response=$(curl -s -w "\n%{http_code}" "$@" "$url") end=$(date +%s.%N) http_code=$(echo "$response" | tail -1) duration=$(echo "$end - $start" | bc) if [ "$http_code" = "200" ] || [ "$http_code" = "201" ]; then result="<span class='pass'>PASS</span>" else result="<span class='fail'>FAIL</span>" fi echo "<tr> <td>$name</td> <td>$method</td> <td>$http_code</td> <td>${duration}s</td> <td>$result</td> </tr>" >> "$REPORT_FILE" } # Execute tests run_test "List Users" "GET" "$API_BASE/users" -H "Authorization: Bearer $TOKEN" run_test "Get User" "GET" "$API_BASE/users/1" -H "Authorization: Bearer $TOKEN" run_test "Create User" "POST" "$API_BASE/users" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"name":"test"}' # Complete report echo "</table></body></html>" >> "$REPORT_FILE" echo "Report generated: $REPORT_FILE"

CI/CD Integration

bash
#!/bin/bash # CI/CD integration test script API_BASE="${API_BASE:-https://api.example.com/v1}" TOKEN="${API_TOKEN}" EXIT_CODE=0 # Color definitions RED='\033[0;31m' GREEN='\033[0;32m' NC='\033[0m' # Test executor execute_test() { local description="$1" local command="$2" local expected="$3" echo "Testing: $description" result=$(eval "$command") if [ "$result" = "$expected" ]; then echo -e "${GREEN}✓ PASS${NC}" else echo -e "${RED}✗ FAIL${NC}" echo " Expected: $expected" echo " Got: $result" EXIT_CODE=1 fi } # Run tests echo "========== Running API Tests ==========" execute_test "API Health Check" \ "curl -s -o /dev/null -w '%{http_code}' $API_BASE/health" \ "200" execute_test "Authentication Required" \ "curl -s -o /dev/null -w '%{http_code}' $API_BASE/users" \ "401" execute_test "List Users with Auth" \ "curl -s -o /dev/null -w '%{http_code}' -H 'Authorization: Bearer $TOKEN' $API_BASE/users" \ "200" # Output results echo "" if [ $EXIT_CODE -eq 0 ]; then echo -e "${GREEN}All tests passed!${NC}" else echo -e "${RED}Some tests failed!${NC}" fi exit $EXIT_CODE

Best Practices

  1. Modular Design: Separate test functions and configuration
  2. Error Handling: Use set -e or explicit return value checking
  3. Logging: Save detailed logs for debugging
  4. Environment Configuration: Use environment variables for different environments
  5. Report Generation: Generate human-readable test reports
  6. CI Integration: Ensure scripts can run in CI/CD environments
标签:cURL