Careeroza
TestClient & pytest
Writing Tests
FastAPI's TestClient calls your app in-process, without a running server. Combined with pytest, tests are short and fast:
# test_main.py
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_home():
r = client.get("/")
assert r.status_code == 200
assert r.json() == {"message": "Hello, FastAPI!"}
def test_validation_error():
r = client.get("/users/not-a-number")
assert r.status_code == 422Example (run tests)
pytest -qExample output
.. [100%] 2 passed in 0.31s