如何在 fastapi 中将 httpx AsyncClient 与 pytest 结合使用?

Mar*_*lle 9 python unit-testing pytest pytest-asyncio fastapi

我已经尝试了所有我能找到的东西,但我无法让异步测试工作。

我开始RuntimeError: This event loop is already running运行TestClient(根据文档,这是有意义的),但我开始httpx.ConnectError: [Errno 8] nodename nor servname provided, or not known使用httpx AsyncClient.

我有一个简单的测试:

@pytest.fixture(scope="module")
async def async_client() -> Generator:
    async with AsyncClient(app=app, base_url='http://0.0.0.0') as client:
        yield client

@pytest.mark.asyncio@mock.patch('apps.core.views.requests.get', new=mocked_get_request)
async def test_get_non_json_response(async_client: AsyncClient):
    response = await async_client.get("/mymedia")
    assertEqual(response.json()['error']['message']['message'], 'Not json')
Run Code Online (Sandbox Code Playgroud)

哪里 /media

@app.get('/mymedia')
async def my_media(request: Request, cache: RedisCacheBackend = Depends(redis_cache)):
    return await my_media_ep(request, cache=cache)
Run Code Online (Sandbox Code Playgroud)

my_media_ep是一个包含多个异步 api 调用的长函数。

我也按照异步测试文档中的建议进行了尝试,但得到了相同的错误。

有什么建议或例子吗?