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 == 422

Example (run tests)

pytest -q

Example output

..                                                     [100%]
2 passed in 0.31s