Testing authentication helps make sure only the right users can access your app. It checks if login and security work correctly.
Testing authentication in FastAPI
from fastapi.testclient import TestClient from your_app import app client = TestClient(app) response = client.post('/login', data={'username': 'user', 'password': 'pass'}) assert response.status_code == 200 assert 'access_token' in response.json()
Use TestClient from FastAPI to simulate requests to your app.
Check response status and content to confirm authentication success or failure.
response = client.post('/login', data={'username': 'alice', 'password': 'secret'}) assert response.status_code == 200 assert 'access_token' in response.json()
response = client.post('/login', data={'username': 'alice', 'password': 'wrong'}) assert response.status_code == 401
response = client.get('/protected-route', headers={'Authorization': 'Bearer validtoken'}) assert response.status_code == 200
response = client.get('/protected-route') assert response.status_code == 401
This FastAPI app has a simple login endpoint and a protected route. The test client checks login success, failure, and access control.
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from fastapi.testclient import TestClient app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") fake_users_db = { "johndoe": { "username": "johndoe", "password": "secret" } } def fake_verify_token(token: str): if token == "validtoken": return True return False @app.post("/token") async def login(form_data: OAuth2PasswordRequestForm = Depends()): user = fake_users_db.get(form_data.username) if not user or user["password"] != form_data.password: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password" ) return {"access_token": "validtoken", "token_type": "bearer"} @app.get("/protected-route") async def protected_route(token: str = Depends(oauth2_scheme)): if not fake_verify_token(token): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials" ) return {"message": "You are authenticated"} client = TestClient(app) def test_authentication(): # Test successful login response = client.post("/token", data={"username": "johndoe", "password": "secret"}) assert response.status_code == 200 assert "access_token" in response.json() # Test failed login response = client.post("/token", data={"username": "johndoe", "password": "wrong"}) assert response.status_code == 401 # Test access protected route with valid token response = client.get("/protected-route", headers={"Authorization": "Bearer validtoken"}) assert response.status_code == 200 assert response.json() == {"message": "You are authenticated"} # Test access protected route without token response = client.get("/protected-route") assert response.status_code == 401 # Run tests if __name__ == "__main__": test_authentication() print("All authentication tests passed.")
Always test both success and failure cases for authentication.
Use TestClient to simulate real HTTP requests in tests.
Keep test data simple and clear to understand what is being tested.
Testing authentication ensures your app only lets in the right users.
Use FastAPI's TestClient to simulate login and protected route access.
Check both successful and failed login attempts to cover all cases.
Practice
Solution
Step 1: Understand authentication testing goal
Authentication testing ensures users are properly verified before accessing certain parts of the app.Step 2: Identify the correct purpose
Only authorized users should access protected routes, which is what authentication testing checks.Final Answer:
To verify that only authorized users can access protected routes -> Option CQuick Check:
Authentication testing = verify authorized access [OK]
- Confusing authentication with UI or performance testing
- Thinking authentication tests improve speed
- Mixing authentication with database tests
Solution
Step 1: Recall FastAPI testing utilities
FastAPI provides TestClient to simulate HTTP requests in tests easily.Step 2: Match the tool to the name
TestClient is the official tool; others are not part of FastAPI.Final Answer:
TestClient -> Option BQuick Check:
FastAPI request simulation = TestClient [OK]
- Using non-existent tools like HTTPServer or AuthTester
- Confusing TestClient with server components
- Not importing TestClient from fastapi.testclient
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
response = client.get('/protected')
print(response.status_code)Solution
Step 1: Understand protected route behavior
Protected routes require authentication; without credentials, access is denied.Step 2: Identify expected HTTP status code
Unauthorized access returns 401 status code, not 200 (success) or 404 (not found).Final Answer:
401 -> Option AQuick Check:
Unauthorized access = 401 status [OK]
- Expecting 200 OK without authentication
- Confusing 401 with 404 Not Found
- Assuming server error 500 instead of auth error
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 == 200Solution
Step 1: Analyze expected login response
Wrong password should cause login failure, usually status 401 or 403, not 200.Step 2: Check test assertion correctness
Asserting status 200 on wrong credentials is incorrect and will fail the test.Final Answer:
The test expects status 200 even with wrong password -> Option DQuick Check:
Wrong password should NOT return 200 [OK]
- Assuming POST is wrong method for login
- Using incorrect JSON keys for credentials
- Misimporting TestClient
from 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'})Solution
Step 1: Recall JWT token usage in HTTP requests
JWT tokens are sent in the Authorization header with 'Bearer ' prefix for authentication.Step 2: Evaluate each option's correctness
Sending the token in the Authorization header with 'Bearer ' prefix correctly simulates authentication. No token, JSON body for GET, or cookies will fail.Final Answer:
Send the token in Authorization header with 'Bearer ' prefix -> Option AQuick Check:
JWT token in Authorization header = Send the token in Authorization header with 'Bearer ' prefix [OK]
- Sending token in JSON body for GET requests
- Omitting the 'Bearer ' prefix
- Using cookies instead of headers for JWT
Ready to prove it?
Pass the test and this pattern moves unknown
