Complete the code to create a test client for FastAPI.
from fastapi.testclient import TestClient from main import app client = [1](app)
The TestClient class from fastapi.testclient is used to create a test client for the FastAPI app.
Complete the code to override the database dependency in FastAPI for testing.
from fastapi import Depends def override_get_db(): db = SessionLocal() try: yield db finally: db.close() app.dependency_overrides[[1]] = override_get_db
The original database dependency function is usually named get_db. We override it with our test version.
Fix the error in the test function to correctly use the test client and database session.
def test_create_item(): response = client.post('/items/', json={'name': 'Test Item'}) assert response.status_code == [1] data = response.json() assert data['name'] == 'Test Item'
When creating a new item, the API should return status code 201 Created to indicate success.
Fill both blanks to create a test database session and override the app dependency.
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args=[1]) TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) def override_get_db(): db = TestingSessionLocal() try: yield db finally: db.close() app.dependency_overrides[[2]] = override_get_db
SQLite requires check_same_thread=False for testing with multiple threads. The dependency to override is get_db.
Fill all three blanks to write a test that creates an item and checks the database directly.
def test_create_and_check_db(): response = client.post('/items/', json=[1]) assert response.status_code == 201 data = response.json() with TestingSessionLocal() as db: item = db.query(Item).filter(Item.name == [2]).first() assert item is not None assert item.name == [3]
The test posts JSON with the item name, then queries the database for the same name as a string. The JSON uses a dictionary, and the query uses string literals.