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 llegint una vista prèvia.
Inicia sessió per llegir l'article complet. Qualsevol compte obre 4 articles gratuïts al mes; l'alumnat i el professorat llegeixen les pàgines del seu curs sense límit.
Inicia sessió