Test
Project setup
First, create a new project and install the required testing dependencies:
uv init test
cd test
uv add fastapi[standard]
uv add --dev pytest httpxFastAPI testing is built on HTTPX, which shares a similar design with the popular Requests library. This makes testing familiar and intuitive.
Since HTTPX is compatible with PyTest, you can use pytest directly to test your FastAPI applications.
TestClient
Create your FastAPI application in main.py:
=
return Then create a test file test_main.py:
=
=
assert == 200
assert == Writing Tests
- Create a TestClient instance by passing your FastAPI application to it
- Define test functions with names starting with
test_(standardpytestconvention) - Make HTTP requests using the
TestClientobject the same way as you would withhttpx - Add assertions using standard Python
assertstatements to verify the expected behavior
Notice that test functions use regular def, not async def.
Client calls are also synchronous (no await needed).
This allows you to use pytest directly without complications.
Estás leyendo una vista previa.
Inicia sesión para leer el artículo completo. Cualquier cuenta abre 4 artículos gratuitos al mes; el alumnado y el profesorado leen las páginas de su curso sin límite.
Iniciar sesión