#!/bin/bash # API测试脚本 - 客户管理 BASE_URL="http://localhost:3000" echo "=== 测试客户管理API ===" echo # 检查jq是否安装 if ! command -v jq &> /dev/null; then echo "错误: jq未安装。安装命令: dnf install -y jq" echo "将使用curl原始输出..." USE_JQ=false else USE_JQ=true fi # 格式化输出函数 format_output() { if [ "$USE_JQ" = true ]; then jq . else cat fi } # 1. 测试健康检查 echo "1. 测试健康检查:" curl -s "$BASE_URL/health" | format_output echo # 2. 测试获取客户列表 echo "2. 测试获取客户列表 (分页):" curl -s "$BASE_URL/api/customers?page=1&limit=3" | format_output echo # 3. 测试搜索客户 echo "3. 测试搜索客户 (搜索'张'):" curl -s "$BASE_URL/api/customers?search=张" | format_output echo # 4. 测试按状态过滤 echo "4. 测试按状态过滤 (active):" curl -s "$BASE_URL/api/customers?status=active&limit=5" | format_output echo # 5. 测试创建新客户 echo "5. 测试创建新客户:" curl -s -X POST "$BASE_URL/api/customers" \ -H "Content-Type: application/json" \ -d '{ "name": "测试客户", "email": "test@example.com", "phone": "12345678901", "address": "测试地址", "company": "测试公司", "tax_id": "TEST123456", "status": "active" }' | format_output echo # 6. 测试获取单个客户 echo "6. 测试获取单个客户 (ID=1):" curl -s "$BASE_URL/api/customers/1" | format_output echo # 7. 测试更新客户 echo "7. 测试更新客户 (ID=1):" curl -s -X PUT "$BASE_URL/api/customers/1" \ -H "Content-Type: application/json" \ -d '{ "phone": "13888888888", "company": "更新后的ABC科技" }' | format_output echo # 8. 测试获取客户联系人 echo "8. 测试获取客户联系人 (ID=1):" curl -s "$BASE_URL/api/customers/1/contacts" | format_output echo # 9. 测试验证错误 echo "9. 测试验证错误 (无效邮箱):" curl -s -X POST "$BASE_URL/api/customers" \ -H "Content-Type: application/json" \ -d '{ "name": "无效客户", "email": "invalid-email", "phone": "12345678901" }' | format_output echo # 10. 测试唯一约束错误 echo "10. 测试唯一约束错误 (重复邮箱):" curl -s -X POST "$BASE_URL/api/customers" \ -H "Content-Type: application/json" \ -d '{ "name": "重复客户", "email": "zhangsan@example.com", "phone": "12345678901" }' | format_output echo # 11. 测试删除客户 echo "11. 测试删除客户 (将创建测试客户然后删除):" # 先创建测试客户 CREATE_RESPONSE=$(curl -s -X POST "$BASE_URL/api/customers" \ -H "Content-Type: application/json" \ -d '{ "name": "待删除客户", "email": "delete-me@example.com", "phone": "11111111111" }') echo "创建响应:" echo "$CREATE_RESPONSE" | format_output # 提取客户ID if [ "$USE_JQ" = true ]; then CUSTOMER_ID=$(echo "$CREATE_RESPONSE" | jq -r '.data.id') else # 简单提取ID CUSTOMER_ID=$(echo "$CREATE_RESPONSE" | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2) fi if [ -n "$CUSTOMER_ID" ] && [ "$CUSTOMER_ID" != "null" ] && [ "$CUSTOMER_ID" != "" ]; then echo "删除客户 ID=$CUSTOMER_ID:" curl -s -X DELETE "$BASE_URL/api/customers/$CUSTOMER_ID" | format_output else echo "无法获取客户ID,跳过删除测试" fi echo # 12. 测试不存在的客户 echo "12. 测试不存在的客户 (ID=999):" curl -s "$BASE_URL/api/customers/999" | format_output echo echo "=== API测试完成 ===" echo "所有端点测试完成。查看上面的响应以验证API功能。"