Script Valley
FastAPI: Build Production Python APIs
Testing FastAPI Applications/Assessment

Practice & Assessment

Test your understanding of Testing FastAPI Applications

Multiple Choice Questions

5
1

Why does the TestClient work synchronously even when FastAPI route handlers are defined with `async def`?

2

What happens if you forget to call `app.dependency_overrides.clear()` after a test that overrides `get_current_user`?

3

When testing a `/token` endpoint that uses `OAuth2PasswordRequestForm`, which TestClient parameter should you use?

4

What is the advantage of using transaction rollback in database test fixtures compared to dropping and recreating tables between tests?

5

What does `--cov-branch` add to standard line coverage measurement?

Coding Challenges

1
1

Full Test Suite for a Todo API

Given a working Todo FastAPI app with routes GET `/todos/`, POST `/todos/`, GET `/todos/{id}`, DELETE `/todos/{id}`, and a JWT-protected PATCH `/todos/{id}/complete` route: write a complete pytest test suite. Requirements: use a `conftest.py` with a shared `client` fixture and an `auth_token` fixture. Write tests for: successful responses and response body structure for all 5 routes, 404 response when todo id does not exist, 401 response when calling PATCH without a token, 422 response when POST body is missing required fields. Override `get_current_user` to return a fake user for auth tests. Achieve at least 85% coverage as reported by `pytest --cov`. Inputs: none required (fixture-provided). Outputs: passing test suite with coverage report. Estimated time: 25-30 minutes.

Medium

Mini Project

1

Fully Tested Blog API

Build and test a Blog API end to end. The API must have: User registration and JWT login, Post CRUD with ownership (only the author can edit or delete their post), and a Comment model where any authenticated user can comment on a post. Write a full pytest test suite in a `tests/` folder with: `conftest.py` defining `client`, `db_session` (SQLite in-memory with rollback isolation), and `auth_token` fixtures. Tests must cover: all happy paths, all 404 and 403 paths, all 401 unauthenticated paths, and at least two 422 validation error paths. Use `app.dependency_overrides` for the database session. Achieve at least 80% code coverage measured with `pytest --cov=app --cov-branch`. Include a `README.md` explaining how to run the app and tests.

Hard