异步单元测试报错:TypeError: object Response can't be used in 'await' expression
问题解决:TypeError: object Response can't be used in 'await' expression 及 404 Not Found
问题分析
- await报错原因:
await仅能用于可等待对象(协程、Task、Future等),如果你的client.get是同步方法(比如FastAPI的TestClient),直接加await会抛出TypeError。 - 404原因:代码中路径字符串
f"/v2/report/{report_id }"里report_id后多了一个空格,导致请求路径变成/v2/report/sample-report-id(末尾带空格),与接口定义路径不匹配;另外需确认mock的服务是否正确注入到请求流程中。
解决方案
1. 修复路径空格问题
这是导致404的直接原因,移除report_id后面的空格:
# 错误写法(带空格) response = await client.get(f"/v2/report/{report_id }", headers=headers) # 正确写法 response = await client.get(f"/v2/report/{report_id}", headers=headers)
2. 调整await的使用
根据client类型决定是否保留await:
- 异步客户端(如FastAPI的
AsyncTestClient、aiohttp的ClientSession):保留await,确保客户端方法本身是异步的。 - 同步客户端(如标准
TestClient):移除await,同时可去掉@pytest.mark.asyncio装饰器(同步测试无需该标记)。
3. 确保mock生效
确认report_service实例被正确注入到测试的请求处理流程中,保证query_fetchone的AsyncMock替代了原始数据库查询方法。若mock未生效,请求会走真实数据库逻辑,因找不到数据返回404。
修正后的示例代码
异步客户端版本
@pytest.mark.asyncio async def test_get_report(report_service, client, headers): """Test Report GET Response""" report_id = "sample-report-id" report_service.query_db.query_fetchone = mock.AsyncMock( return_value={ "id": "sample-id", "reportId": "sample-report-id", "reportName": "sample-report-name", "report": [], } ) # 修复路径空格,保留await response = await client.get(f"/v2/report/{report_id}", headers=headers) assert response.status_code == 200
同步客户端版本
def test_get_report(report_service, client, headers): """Test Report GET Response""" report_id = "sample-report-id" report_service.query_db.query_fetchone = mock.AsyncMock( return_value={ "id": "sample-id", "reportId": "sample-report-id", "reportName": "sample-report-name", "report": [], } ) # 移除await,修复路径空格 response = client.get(f"/v2/report/{report_id}", headers=headers) assert response.status_code == 200
内容的提问来源于stack exchange,提问作者Tenserflu
相关产品推荐
相关产品推荐

