类型错误:对象响应不能在“等待”表达式中使用

问题描述 投票:0回答:1

我正在尝试执行这个单元测试。我想异步等待 GET,因为检索数据需要一段时间。但是,我得到:

TypeError: object Response can't be used in 'await' expression

@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": [],
        }
    )
    response = await client.get(f"/v2/report/{report_id }", headers=headers)
    assert response.status_code == 200

如果我删除

await
,我将得到此回复
{'detail': 'Not Found'}

python pytest python-asyncio
1个回答
0
投票

client.get 不是异步函数,这就是您收到错误的原因。我猜你正在使用 FastAPI,“.get”函数是同步的。在你的情况下,我想以下可能有效:

@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": [],
    }
)
async with client.get(f"/v2/report/{report_id}", headers=headers) as response:
    assert response.status == 200

希望这有效。

© www.soinside.com 2019 - 2024. All rights reserved.