114 lines
3.1 KiB
Python
114 lines
3.1 KiB
Python
"""异常场景测试脚本"""
|
||
|
||
import requests
|
||
import json
|
||
import time
|
||
|
||
CLOUD_URL = "http://127.0.0.1:5000/api/upload"
|
||
|
||
def test_scenario(name, url, data, headers, expected_status):
|
||
"""测试单个异常场景"""
|
||
print(f"\n{'='*60}")
|
||
print(f"测试场景: {name}")
|
||
print('='*60)
|
||
|
||
try:
|
||
response = requests.post(url, json=data, headers=headers, timeout=5)
|
||
|
||
print(f"状态码: {response.status_code}")
|
||
print(f"响应: {json.dumps(response.json(), indent=2, ensure_ascii=False)}")
|
||
|
||
if response.status_code == expected_status:
|
||
print(f"✅ 通过(符合预期 {expected_status})")
|
||
return True
|
||
else:
|
||
print(f"❌ 失败(预期 {expected_status},实际 {response.status_code})")
|
||
return False
|
||
except Exception as e:
|
||
print(f"❌ 异常: {e}")
|
||
return False
|
||
|
||
def main():
|
||
"""运行所有异常场景测试"""
|
||
print("="*60)
|
||
print("🧪 云端异常场景测试")
|
||
print("="*60)
|
||
|
||
results = []
|
||
current_time = time.time()
|
||
|
||
# 场景1: 错误的API Key (401)
|
||
results.append(test_scenario(
|
||
"错误的API Key",
|
||
CLOUD_URL,
|
||
{
|
||
"device_id": "test_device",
|
||
"upload_time": "2026-01-12T10:00:00",
|
||
"events": [{"timestamp": current_time, "heart_rate": 72}],
|
||
"summary": {}
|
||
},
|
||
{
|
||
"Authorization": "Bearer wrong_api_key_123456",
|
||
"Content-Type": "application/json"
|
||
},
|
||
401
|
||
))
|
||
|
||
# 场景2: 缺少必填字段 (400)
|
||
results.append(test_scenario(
|
||
"缺少必填字段 (events)",
|
||
CLOUD_URL,
|
||
{
|
||
"device_id": "test_device",
|
||
"upload_time": "2026-01-12T10:00:00",
|
||
# 故意缺少 events
|
||
"summary": {}
|
||
},
|
||
{
|
||
"Authorization": "Bearer edge_device_key_001",
|
||
"Content-Type": "application/json"
|
||
},
|
||
400
|
||
))
|
||
|
||
# 场景3: 字段类型错误 (400)
|
||
results.append(test_scenario(
|
||
"字段类型错误 (heart_rate为字符串)",
|
||
CLOUD_URL,
|
||
{
|
||
"device_id": "test_device",
|
||
"upload_time": "2026-01-12T10:00:00",
|
||
"events": [{
|
||
"timestamp": current_time,
|
||
"heart_rate": "not_a_number", # 故意用字符串
|
||
"rmssd": 30,
|
||
"sdnn": 45
|
||
}],
|
||
"summary": {}
|
||
},
|
||
{
|
||
"Authorization": "Bearer edge_device_key_001",
|
||
"Content-Type": "application/json"
|
||
},
|
||
400
|
||
))
|
||
|
||
# 总结
|
||
print("\n" + "="*60)
|
||
print("📊 测试总结")
|
||
print("="*60)
|
||
print(f"总共测试: {len(results)} 个场景")
|
||
print(f"通过: {sum(results)} 个")
|
||
print(f"失败: {len(results) - sum(results)} 个")
|
||
|
||
if all(results):
|
||
print("\n✅ 所有异常场景测试通过!")
|
||
return True
|
||
else:
|
||
print("\n⚠️ 部分测试未通过,请查看详细日志")
|
||
return False
|
||
|
||
if __name__ == '__main__':
|
||
success = main()
|
||
exit(0 if success else 1)
|