Performance: Testing path operations
Testing path operations affects development speed and reliability but can indirectly impact user experience by preventing slow or broken endpoints.
from fastapi.testclient import TestClient from main import app from unittest.mock import patch client = TestClient(app) @patch('main.get_items_from_db') def test_get_items(mock_db): mock_db.return_value = [{'id': 1, 'name': 'Test Item'}] response = client.get('/items') assert response.status_code == 200 assert response.json() == [{'id': 1, 'name': 'Test Item'}]
from fastapi.testclient import TestClient from main import app client = TestClient(app) def test_get_items(): response = client.get('/items') assert response.status_code == 200 assert 'items' in response.json() # Tests run with real database calls and no mocks
| Pattern | Test Speed | Dependency Cost | Reliability | Verdict |
|---|---|---|---|---|
| Real DB calls in tests | Slow (seconds) | High (real DB) | Flaky | [X] Bad |
| Mocked dependencies in tests | Fast (milliseconds) | Low (mocked) | Stable | [OK] Good |
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get('/hello')
def read_hello():
return {'message': 'Hello World'}
client = TestClient(app)
response = client.get('/hello')from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.post('/items')
def create_item(item: dict):
return item
client = TestClient(app)
response = client.get('/items')
print(response.status_code)Pass the test and this pattern moves unknown