Performance: Async test patterns
This affects the responsiveness and speed of running asynchronous tests, impacting developer feedback loop and CI pipeline efficiency.
import pytest import httpx @pytest.mark.asyncio async def test_endpoint(): async with httpx.AsyncClient(app=app, base_url='http://test') as client: response = await client.get('/async-endpoint') assert response.status_code == 200
def test_endpoint(): response = client.get('/async-endpoint') assert response.status_code == 200
| Pattern | Event Loop Usage | Concurrency | Test Suite Runtime | Verdict |
|---|---|---|---|---|
| Synchronous test client | Blocks event loop | No concurrency | Longer runtime | [X] Bad |
| Async test client with await | Non-blocking | Single concurrency | Faster runtime | [!] OK |
| Concurrent async tests with asyncio.gather | Non-blocking | High concurrency | Shortest runtime | [OK] Good |
async def in FastAPI test functions?async def in tests lets you call async code properly without blocking the test runner.async def to run async code [OK]AsyncClient from httpx in a FastAPI async test?from module import Class syntax, so from httpx import AsyncClient is correct.async with to properly open and close async connections.import pytest
from httpx import AsyncClient
@pytest.mark.asyncio
async def test_hello(app):
async with AsyncClient(app=app, base_url='http://test') as client:
response = await client.get('/hello')
print(response.status_code)
Assuming the '/hello' endpoint returns status 200, what is printed?await to get the response from the async client, so the response is valid.response.status_code is 200 and printing it outputs '200'.import pytest
from httpx import AsyncClient
@pytest.mark.asyncio
def test_root(app):
async with AsyncClient(app=app, base_url='http://test') as client:
response = await client.get('/')
assert response.status_code == 200
def but calls await inside, which requires async def.async def, Python raises a syntax error when using await.@pytest.mark.asyncio and use async def with async with AsyncClient to handle async calls properly.Pass the test and this pattern moves unknown