How to Test Authentication in FastAPI: Simple Guide
To test authentication in
FastAPI, use TestClient to simulate requests and override the authentication dependency with a test version. This lets you check protected routes by providing mock user credentials or tokens without real login flows.Syntax
Testing authentication in FastAPI involves these parts:
TestClient: Simulates HTTP requests to your app.- Dependency override: Replace the real authentication logic with a test version that returns a mock user.
- Protected route: An endpoint that requires authentication.
python
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from fastapi.testclient import TestClient app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def fake_decode_token(token: str): if token == "validtoken": return {"username": "testuser"} raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") def get_current_user(token: str = Depends(oauth2_scheme)): return fake_decode_token(token) @app.get("/protected") def protected_route(user: dict = Depends(get_current_user)): return {"hello": user["username"]} client = TestClient(app) # Override example app.dependency_overrides[get_current_user] = lambda: {"username": "testuser"}
Example
This example shows how to test a protected route by overriding the authentication dependency to simulate a logged-in user.
python
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from fastapi.testclient import TestClient app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def fake_decode_token(token: str): if token == "validtoken": return {"username": "testuser"} raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") def get_current_user(token: str = Depends(oauth2_scheme)): return fake_decode_token(token) @app.get("/protected") def protected_route(user: dict = Depends(get_current_user)): return {"hello": user["username"]} client = TestClient(app) # Test with real token response = client.get("/protected", headers={"Authorization": "Bearer validtoken"}) print("Status code with valid token:", response.status_code) print("Response JSON:", response.json()) # Test with invalid token response_invalid = client.get("/protected", headers={"Authorization": "Bearer invalidtoken"}) print("Status code with invalid token:", response_invalid.status_code) # Override dependency to bypass token app.dependency_overrides[get_current_user] = lambda: {"username": "overrideuser"} response_override = client.get("/protected") print("Status code with override:", response_override.status_code) print("Response JSON with override:", response_override.json())
Output
Status code with valid token: 200
Response JSON: {'hello': 'testuser'}
Status code with invalid token: 401
Status code with override: 200
Response JSON with override: {'hello': 'overrideuser'}
Common Pitfalls
Common mistakes when testing authentication in FastAPI include:
- Not overriding the authentication dependency, causing tests to fail due to missing or invalid tokens.
- Hardcoding tokens without matching the real token validation logic.
- Forgetting to reset dependency overrides after tests, which can affect other tests.
Always use app.dependency_overrides to replace authentication during tests and clean up overrides if running multiple tests.
python
from fastapi import FastAPI, Depends from fastapi.testclient import TestClient app = FastAPI() def get_current_user(): # Real auth logic here pass @app.get("/protected") def protected_route(user: dict = Depends(get_current_user)): return {"hello": user["username"]} client = TestClient(app) # Wrong: No override, test will fail if no token provided response = client.get("/protected") print(response.status_code) # Likely 401 # Right: Override to bypass auth app.dependency_overrides[get_current_user] = lambda: {"username": "testuser"} response = client.get("/protected") print(response.status_code) # 200 # Clean up after test app.dependency_overrides.clear()
Output
401
200
Quick Reference
Tips for testing authentication in FastAPI:
- Use
TestClientto simulate requests. - Override authentication dependencies with
app.dependency_overrides. - Provide mock user data or tokens in overrides.
- Test both valid and invalid token scenarios.
- Clear overrides after tests to avoid side effects.
Key Takeaways
Use TestClient and dependency overrides to test authentication in FastAPI.
Override the authentication dependency to simulate logged-in users without real tokens.
Test both valid and invalid authentication scenarios for complete coverage.
Always clear dependency overrides after tests to prevent interference.
Mock tokens or user data should match your app's authentication logic.