Complete the code to define a simple FastAPI fixture that provides a test client.
import pytest from fastapi.testclient import TestClient from myapp.main import app @pytest.fixture def client(): return [1](app)
The TestClient is used to create a test client for FastAPI apps in fixtures.
Complete the fixture to yield a database session for tests.
import pytest from myapp.database import SessionLocal @pytest.fixture def db_session(): db = [1]() try: yield db finally: db.close()
SessionLocal is the factory that creates new database sessions for tests.
Fix the error in this fixture that overrides the dependency for the database session.
from fastapi.testclient import TestClient from myapp.main import app from myapp.database import SessionLocal import pytest from myapp.database import get_db @pytest.fixture def client_override_db(): def override_get_db(): db = SessionLocal() try: yield db finally: db.close() app.dependency_overrides[[1]] = override_get_db with TestClient(app) as c: yield c app.dependency_overrides.clear()
The dependency_overrides dictionary keys must be the original dependency function, here get_db.
Fill both blanks to create a fixture that resets the database before each test.
import pytest from myapp.database import Base, engine @pytest.fixture(autouse=True) def reset_db(): Base.metadata.[1](bind=engine) Base.metadata.[2](bind=engine)
First, drop_all removes all tables, then create_all recreates them for a clean state.
Fill all three blanks to define a fixture that provides an authenticated test client.
import pytest from fastapi.testclient import TestClient from myapp.main import app from myapp.auth import create_access_token @pytest.fixture def auth_client(): token = create_access_token(data={"sub": [1]) headers = {"Authorization": f"Bearer [2]"} client = TestClient(app) client.headers.update([3]) return client
The token is created for user "testuser", then used in the Authorization header, which is added to the client headers.