Sub topic 8
Testing the API
This chapter shows how to test the prediction service you built in the earlier chapters. It assumes you can read basic Python and pytest output, and that you have the main.py service and model.joblib file from the previous chapters in your working directory. You also need pytest and httpx installed, because FastAPI's TestClient uses httpx to make requests.
pip install pytest httpxWhy test a model API
A model API has several parts that can break independently. The model file can be missing or incompatible. The request schema can accept values it should reject. The response can have the wrong shape. A test suite checks these parts without starting a real server or opening a network port.
Tests for a model service answer different questions than tests for the model itself. Evaluating the model asks whether predictions are accurate. Testing the API asks whether the service does what its contract says. Does it return 200 for a valid request? Does it return 422 for an invalid one? Does it load the model before serving traffic? This chapter covers only the second set of questions.
How TestClient works
TestClient is a class from FastAPI that calls your application directly in the same process. It sends requests through the app's ASGI interface (the standard interface between Python web servers and applications), so no socket is opened and no Uvicorn process is needed. This makes tests fast and easy to run in continuous integration.
The client exposes methods named after HTTP verbs: get, post, and so on. Each returns a response object with status_code, json(), and text.
The startup trap
Your service loads the model in a lifespan function. Lifespan code runs when the application starts. TestClient only runs it when you use the client as a context manager, with a with block.
If you create the client without with, the model is never loaded. The models dictionary stays empty, and the first request to /predict fails with a KeyError on models["iris"]. FastAPI turns that into a 500 response.
from fastapi.testclient import TestClient
from main import app
# Wrong: lifespan does not run, so the model is not loaded.
client = TestClient(app)
response = client.post(
"/predict",
json={
"sepal_length": 5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2,
},
)
print(response.status_code)Running this raises the KeyError inside the test client, because TestClient re-raises server exceptions by default. In a real deployment you would see a 500 response instead. Either way, the cause is the same: the startup code did not run.
Writing the first tests
The two tests below check the two most important behaviors of /predict. A valid request returns 200 and an integer class index. A request that breaks the schema returns 422, which is the status code FastAPI uses for validation errors.
from fastapi.testclient import TestClient
from main import app
def test_predict_returns_class_index():
with TestClient(app) as client:
response = client.post(
"/predict",
json={
"sepal_length": 5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2,
},
)
assert response.status_code == 200
assert isinstance(response.json()["class_index"], int)
def test_predict_rejects_negative_values():
with TestClient(app) as client:
response = client.post(
"/predict",
json={
"sepal_length": -1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2,
},
)
assert response.status_code == 422Save these in test_main.py and run pytest from the project directory. The from main import app line only works if main.py is importable, so run the command from the directory that contains it.
The second test passes because of the Field(gt=0) constraint on IrisFeatures. The test is evidence that the constraint is wired up. If someone later removes the constraint, this test fails.
Sharing one client with a fixture
Repeating the with block in every test is noisy. A pytest fixture (a function that prepares something for tests) can create the client once and hand it to each test. Put the fixture in a file named conftest.py and pytest finds it automatically.
import pytest
from fastapi.testclient import TestClient
from main import app
@pytest.fixture(scope="module")
def client():
with TestClient(app) as c:
yield cWith scope="module", the model loads once per test file instead of once per test. The yield hands the client to the tests and returns control to the fixture afterward, so the with block exits and the lifespan shutdown code runs after the last test in the module.
Tests then take client as an argument:
def test_health_reports_model_loaded(client):
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "ok", "model_loaded": True}This also tests the health check from the previous chapter. It confirms that model_loaded is True only because startup ran.
What to cover
A useful suite for this service covers these cases.
| Case | Request | Expected result |
|---|---|---|
| Valid input | All four features, positive numbers | 200, integer `class_index` |
| Negative value | `sepal_length: -1` | 422 |
| Zero value | `petal_width: 0` | 422, because `gt=0` excludes zero |
| Missing field | Omit `petal_length` | 422 |
| Wrong type | `sepal_width: "wide"` | 422 |
| Health check | `GET /health` | 200, `model_loaded` is true |
Parametrized tests keep the invalid-input cases compact. pytest.mark.parametrize runs one test function once for each set of arguments.
import pytest
VALID = {
"sepal_length": 5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2,
}
@pytest.mark.parametrize(
"change",
[
{"sepal_length": -1},
{"petal_width": 0},
{"sepal_width": "wide"},
],
)
def test_invalid_values_return_422(client, change):
response = client.post("/predict", json={**VALID, **change})
assert response.status_code == 422
def test_missing_field_returns_422(client):
payload = {k: v for k, v in VALID.items() if k != "petal_length"}
response = client.post("/predict", json=payload)
assert response.status_code == 422The 422 response body lists which field failed and why. You can assert on it when the exact field matters. In FastAPI, response.json()["detail"] is a list of error objects, each with a loc entry such as ["body", "sepal_length"].
Testing the batch endpoint
If you added the batch endpoint, test that it returns one prediction per input row and keeps their order. A single-row batch should agree with /predict for the same input.
def test_batch_matches_single_prediction(client):
single = client.post("/predict", json=VALID).json()["class_index"]
batch = client.post("/predict/batch", json={"instances": [VALID, VALID]})
assert batch.status_code == 200
assert batch.json()["class_indices"] == [single, single]This kind of consistency test catches mistakes in the feature order. The batch code builds its rows by hand, and a swapped column would silently change predictions without raising an error.
Edge cases and limits of these tests
- Deterministic predictions. The model was trained with
random_state=0and is loaded from a file, so the same input gives the same output. Tests can compare against an exact class index for a well-known sample, such as the first iris row. Pin that expectation only if you retrain rarely, because retraining can legitimately change borderline predictions. - Missing model file. If
model.joblibis absent, the lifespan function raises and thewith TestClient(app)line fails at startup. That failure is useful: it shows the service would not start in production either. - Test data location. The model path is relative, so tests must run from the directory that holds
model.joblib. For a larger project, read the path from an environment variable and point it at a small fixture model in tests. - What the tests do not show.
TestClientskips the network, Uvicorn, and the container. It will not catch a wrong--hostflag or a missing file in the Docker image. Cover those by starting the container and calling/health, as described in the next chapter.
Common errors
- 500 or
KeyError: 'iris'. The client was created withoutwith, so startup did not run. ModuleNotFoundError: No module named 'main'. Runpytestfrom the project directory, or add aconftest.pythere so pytest adds that directory to the import path.RuntimeErrorabouthttpx. Installhttpx. Current versions ofTestClientrequire it.- Tests pass but the container fails. The tests do not exercise the Dockerfile. Verify the image separately.
Exercise
A teammate writes client = TestClient(app) at the top of the test file and calls /predict without a with block. The valid-input test fails with KeyError: 'iris'. Explain why, and show the fix.
Show answer
The model is loaded in the lifespan function, which TestClient runs only when it is used as a context manager. Without with, startup never runs, models stays empty, and models["iris"] raises KeyError. The fix is to use with TestClient(app) as client: around the requests, or to create the client in a fixture that uses with and yields it.
Exercise
Add a test that sends petal_length: 0 to /predict and checks that the response is 422 and that the error points to the petal_length field.
Show answer
Use this test:
def testzeropetallengthnamesfield(client):
payload = {**VALID, "petallength": 0}
response = client.post("/predict", json=payload)
assert response.statuscode == 422
locations = [error["loc"] for error in response.json()["detail"]]
assert ["body", "petallength"] in locations
Zero fails because the field is declared with Field(gt=0), which requires values strictly greater than zero. Each error in detail has a loc list that names where the problem occurred.