Agentic AI项目中的FastAPI应用冒烟测试指南
引言
在Agentic AI项目的开发过程中,FastAPI作为现代Python Web框架被广泛应用于构建高性能API服务。本文将详细介绍如何为FastAPI应用执行全面的冒烟测试(Smoke Testing),确保应用在部署后能够正常运行。
什么是冒烟测试?
冒烟测试是一种轻量级的软件测试方法,用于验证系统的基本功能是否正常工作。它就像"冒烟"一样快速检测系统是否存在明显问题,通常作为部署后的第一步验证。
测试准备
在开始测试前,请确保满足以下条件:
- Python 3.8或更高版本已安装
- FastAPI应用已部署并运行
- 获取到应用的访问URL或端点
- 了解基本的API测试概念
测试内容详解
1. 基础设施验证
1.1 应用状态检查
async def check_application_status(base_url: str):
async with httpx.AsyncClient() as client:
try:
response = await client.get(f"{base_url}/health")
return response.status_code == 200
except Exception as e:
print(f"应用状态检查错误: {e}")
return False
这段代码会检查应用的/health端点是否返回200状态码,这是应用正常运行的最基本指标。
1.2 环境变量验证
async def check_environment(base_url: str):
async with httpx.AsyncClient() as client:
try:
response = await client.get(f"{base_url}/env")
env_vars = response.json()
required_vars = ["DATABASE_URL", "API_KEY", "ENVIRONMENT"]
missing = [var for var in required_vars if var not in env_vars]
if missing:
print(f"缺少环境变量: {missing}")
return False
return True
验证应用是否配置了所有必需的环境变量,这对于应用正常运行至关重要。
2. 应用健康检查
2.1 基础健康端点
async def test_health_endpoint(base_url: str):
async with httpx.AsyncClient() as client:
try:
response = await client.get(f"{base_url}/health")
return {
"status": response.status_code == 200,
"response_time": response.elapsed.total_seconds() * 1000,
"body": response.json()
}
不仅检查状态码,还记录响应时间和返回内容,提供更全面的健康状态信息。
2.2 数据库连接测试
async def test_database_connection(base_url: str):
async with httpx.AsyncClient() as client:
try:
# 测试Postgres连接
response = await client.get(f"{base_url}/postgres/health")
postgres_health = {
"status": response.status_code == 200,
"response_time": response.elapsed.total_seconds() * 1000,
"body": response.json()
}
# 测试Redis连接
response = await client.get(f"{base_url}/redis/health")
redis_health = {
"status": response.status_code == 200,
"response_time": response.elapsed.total_seconds() * 1000,
"body": response.json()
}
对于依赖多种数据库的应用,需要分别测试每种数据库的连接状态。
3. 核心功能测试
3.1 API端点测试
async def test_api_endpoints(base_url: str, endpoints: List[Dict]):
results = []
async with httpx.AsyncClient() as client:
for endpoint in endpoints:
try:
if endpoint["method"] == "GET":
response = await client.get(f"{base_url}{endpoint['path']}")
else:
response = await client.post(
f"{base_url}{endpoint['path']}",
json=endpoint.get("data", {})
)
results.append({
"endpoint": endpoint["path"],
"method": endpoint["method"],
"status": response.status_code == 200,
"response_time": response.elapsed.total_seconds() * 1000
})
测试所有关键API端点,包括GET和POST请求,记录每个端点的状态和响应时间。
3.2 认证测试
async def test_authentication(base_url: str, api_key: str):
async with httpx.AsyncClient() as client:
headers = {"Authorization": f"Bearer {api_key}"}
try:
response = await client.get(
f"{base_url}/api/v1/secure",
headers=headers
)
return {
"status": response.status_code == 200,
"response_time": response.elapsed.total_seconds() * 1000
}
验证API的认证机制是否正常工作,确保只有授权用户可以访问受保护资源。
4. 性能检查
4.1 响应时间测量
async def measure_response_times(base_url: str, num_requests: int = 10):
times: List[float] = []
async with httpx.AsyncClient() as client:
for _ in range(num_requests):
try:
response = await client.get(f"{base_url}/health")
times.append(response.elapsed.total_seconds() * 1000)
if times:
return {
"average": statistics.mean(times),
"median": statistics.median(times),
"p95": statistics.quantiles(times, n=20)[18]
}
通过多次请求计算平均响应时间、中位数和95分位数,全面评估API性能。
4.2 并发请求测试
async def test_concurrent_requests(base_url: str, num_requests: int = 10):
async with httpx.AsyncClient() as client:
tasks = []
for _ in range(num_requests):
task = client.get(f"{base_url}/health")
tasks.append(task)
responses = await asyncio.gather(*tasks, return_exceptions=True)
success_count = sum(1 for r in responses if isinstance(r, httpx.Response) and r.status_code == 200)
模拟多个并发请求,测试应用在高负载下的表现和稳定性。
5. 日志和监控检查
5.1 日志检查
async def check_application_logs(base_url: str):
async with httpx.AsyncClient() as client:
try:
response = await client.get(f"{base_url}/logs")
logs = response.json()
error_logs = [log for log in logs if log["level"] == "ERROR"]
return {
"total_logs": len(logs),
"error_logs": len(error_logs),
"has_errors": len(error_logs) > 0
}
检查应用日志,特别关注错误日志,帮助发现潜在问题。
5.2 监控指标检查
async def check_application_metrics(base_url: str):
async with httpx.AsyncClient() as client:
try:
response = await client.get(f"{base_url}/metrics")
metrics = response.json()
return {
"cpu_usage": metrics.get("cpu_usage"),
"memory_usage": metrics.get("memory_usage"),
"request_count": metrics.get("request_count")
}
获取CPU、内存使用率和请求数等关键指标,评估系统资源使用情况。
综合测试脚本
将所有测试整合到一个完整的测试类中:
class SmokeTest:
def __init__(self, base_url: str, api_key: str):
self.base_url = base_url
self.api_key = api_key
self.results: Dict = {}
async def run_all_tests(self):
self.results["timestamp"] = datetime.now().isoformat()
# 执行所有测试...
self.results["application_status"] = await self.check_application_status()
self.results["environment"] = await self.check_environment()
# 其他测试...
return self.results
常见问题与解决方案
-
连接超时
- 原因:网络问题或服务未启动
- 解决:检查网络连接和服务状态
- 预防:实现重试机制和超时设置
-
认证失败
- 原因:API密钥错误或过期
- 解决:验证密钥有效性
- 预防:实现密钥轮换和过期提醒
-
性能下降
- 原因:资源不足或代码效率低
- 解决:优化代码或增加资源
- 预防:设置性能基准和监控
最佳实践
-
测试策略
- 从基础检查开始,逐步深入
- 定期执行冒烟测试
- 记录每次测试结果
-
错误处理
- 捕获并记录所有异常
- 实现优雅降级
- 创建常见问题解决方案文档
-
监控
- 设置关键指标阈值
- 实现自动告警
- 定期审查日志
总结
本文详细介绍了Agentic AI项目中FastAPI应用的冒烟测试方法,涵盖了从基础设施验证到性能监控的各个方面。通过实施这些测试,可以确保应用部署后的稳定性和可靠性。建议将测试脚本集成到CI/CD流程中,实现自动化测试。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考