cURL 是编写 API 自动化测试脚本的强大工具,配合 Shell 脚本可以实现完整的测试流程,包括测试执行、结果验证和报告生成。
基础测试脚本结构
bash#!/bin/bash # 基础 API 测试脚本 API_BASE="https://api.example.com/v1" TOKEN="your_bearer_token" PASSED=0 FAILED=0 # 测试函数 run_test() { local name="$1" local expected_status="$2" shift 2 echo "Running test: $name" # 执行请求并获取状态码 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 } # 执行测试 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" # 输出结果 echo "" echo "Test Results:" echo " Passed: $PASSED" echo " Failed: $FAILED" echo " Total: $((PASSED + FAILED))" exit $FAILED
响应内容验证
bash#!/bin/bash # 响应内容验证测试 API_BASE="https://api.example.com/v1" TOKEN="your_bearer_token" # JSON 验证函数 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 } # 测试用户 API echo "Testing User API..." # 创建用户 response=$(curl -s -X POST \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"name":"张三","email":"zhangsan@example.com"}' \ "$API_BASE/users") # 验证响应 assert_json_field "$response" ".name" "张三" assert_json_field "$response" ".email" "zhangsan@example.com" assert_json_field "$response" ".status" "active" # 验证响应包含特定字段 if echo "$response" | jq -e '.id' > /dev/null; then echo "✅ PASS: Response contains 'id' field" else echo "❌ FAIL: Response missing 'id' field" fi
性能测试脚本
bash#!/bin/bash # API 性能测试脚本 API_URL="https://api.example.com/v1/users" TOKEN="your_bearer_token" CONCURRENT=10 REQUESTS=100 # 单请求性能测试 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" # 并发性能测试 echo "" echo "Concurrent Load Test ($CONCURRENT concurrent, $REQUESTS total):" start_time=$(date +%s) # 使用 xargs 进行并发请求 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)) # 分析结果 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
集成测试流程
bash#!/bin/bash # 完整集成测试流程 set -e # 遇到错误立即退出 API_BASE="https://api.example.com/v1" TOKEN="your_bearer_token" TEST_USER_ID="" echo "========== API Integration Tests ==========" # 1. 健康检查 echo "1. Health Check" curl -sf "$API_BASE/health" | jq -e '.status == "ok"' echo "✅ Health check passed" # 2. 创建测试数据 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. 验证创建 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. 更新操作 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. 删除测试数据 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 =========="
测试报告生成
bash#!/bin/bash # 生成 HTML 测试报告 API_BASE="https://api.example.com/v1" TOKEN="your_bearer_token" REPORT_FILE="test-report.html" # 初始化报告 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 # 执行测试并记录结果 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" } # 执行测试 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"}' # 完成报告 echo "</table></body></html>" >> "$REPORT_FILE" echo "Report generated: $REPORT_FILE"
CI/CD 集成
bash#!/bin/bash # CI/CD 集成测试脚本 API_BASE="${API_BASE:-https://api.example.com/v1}" TOKEN="${API_TOKEN}" EXIT_CODE=0 # 颜色定义 RED='\033[0;31m' GREEN='\033[0;32m' NC='\033[0m' # 测试执行器 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 } # 运行测试 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" # 输出结果 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
最佳实践
- 模块化设计:将测试函数和配置分离
- 错误处理:使用
set -e或显式检查返回值 - 日志记录:保存详细日志便于调试
- 环境配置:使用环境变量管理不同环境
- 报告生成:生成可读性强的测试报告
- CI 集成:确保脚本能在 CI/CD 环境中运行