Concept Flow - Testing with database
Setup Test DB
Create Test Client
Run Test Function
Perform DB Operations
Assert Results
Teardown Test DB
This flow shows how a test sets up a temporary database, runs API calls, checks results, and cleans up.
from fastapi.testclient import TestClient from main import app, get_db def test_create_item(): client = TestClient(app) response = client.post('/items/', json={'name': 'Test'}) assert response.status_code == 200
| Step | Action | DB State | Response Status | Assertion |
|---|---|---|---|---|
| 1 | Setup test database (empty) | Empty | N/A | N/A |
| 2 | Create TestClient instance | Empty | N/A | N/A |
| 3 | Send POST /items/ with {'name': 'Test'} | Contains 1 item | 200 | Pass |
| 4 | Check response status code | Contains 1 item | 200 | Pass |
| 5 | Teardown test database | Deleted all | N/A | N/A |
| Variable | Start | After Step 3 | After Step 5 |
|---|---|---|---|
| client | None | TestClient instance | TestClient instance |
| response.status_code | N/A | 200 | N/A |
| database contents | Empty | Contains 1 item | Empty |
Testing with database in FastAPI: - Setup a test database separate from production - Use TestClient to simulate HTTP requests - Perform API calls that read/write test DB - Assert expected responses and DB changes - Teardown test DB to keep tests isolated