
Module 14 Exercises: Building a Safety Net
Practical exercises to challenge your ability to write TestClient functions, override dependencies, and assert correctness.
Module 14 Exercises: Building a Safety Net
Code that isn't tested is code that is already broken. These exercises will help you build the "Safety Net" that allows you to move fast and break nothing.
Exercise 1: The First Test
Write a test for a POST /items/ endpoint.
- The endpoint expects a JSON body:
{"name": "Widget", "price": 10}. - The endpoint returns the same body plus an
id: 1. - Goal: Write the full Pytest function using
TestClient.
Exercise 2: The DB Override Challenge
You have a dependency get_database_session.
Write the code to override this dependency in your test file so it returns a local dictionary {} instead of a real database connection.
Exercise 3: Validating Failure
You have an endpoint that requires a token. If the token is missing, it returns a 401 Unauthorized. Write a test that:
- Calls the endpoint without the
Authorizationheader. - Asserts that the status code is
401.
Self-Correction / Discussion
Exercise 1 Answer:
def test_create_item():
payload = {"name": "Widget", "price": 10}
response = client.post("/items/", json=payload)
assert response.status_code == 200 # or 201
data = response.json()
assert data["name"] == "Widget"
assert "id" in data
Exercise 2 Answer:
def fake_db():
return {}
app.dependency_overrides[get_database_session] = fake_db
Exercise 3 Answer:
def test_auth_failure():
response = client.get("/protected")
assert response.status_code == 401
Summary of Module 14
You have moved from being a "Coder" to an "Engineer."
- Automation: You can verify your logic in milliseconds.
- Isolation: You can test your app without paying for external services.
- Trust: You can refactor your code knowing that your tests will catch any mistakes.
In Module 15: Performance and Scalability, we will look at how to handle millions of requests and how to optimize FastAPI's async core for maximum throughput.