Performance: Testing authentication
Testing authentication affects the speed and responsiveness of API endpoints during development and CI pipelines, impacting developer feedback loops.
def test_auth_good(client): # Test invalid login once response = client.post('/login', data={'username': 'user', 'password': 'wrong'}) assert response.status_code == 401 # Test valid login once response = client.post('/login', data={'username': 'user', 'password': 'correct'}) assert response.status_code == 200
def test_auth_bad(client): response = client.post('/login', data={'username': 'user', 'password': 'wrong'}) assert response.status_code == 401 response = client.post('/login', data={'username': 'user', 'password': 'correct'}) assert response.status_code == 200 # Repeatedly call login endpoint multiple times in one test for _ in range(10): client.post('/login', data={'username': 'user', 'password': 'correct'})
| Pattern | Server Calls | Test Duration | Resource Usage | Verdict |
|---|---|---|---|---|
| Repeated login calls in one test | Multiple redundant calls | Longer due to repeated processing | High CPU and memory during tests | [X] Bad |
| Single login call per test case | Minimal necessary calls | Shorter test runtime | Low resource usage | [OK] Good |
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
response = client.get('/protected')
print(response.status_code)from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
response = client.post('/login', json={'username': 'user', 'password': 'wrongpass'})
assert response.status_code == 200from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
# Options:
# A) client.get('/secure', headers={'Authorization': 'Bearer validtoken'})
# B) client.get('/secure')
# C) client.get('/secure', json={'token': 'validtoken'})
# D) client.get('/secure', cookies={'Authorization': 'validtoken'})Pass the test and this pattern moves unknown