- Spec files
pypi-fastapi
Describes: pkg:pypi/fastapi@0.116.x
- Description
- FastAPI framework, high performance, easy to learn, fast to code, ready for production
- Author
- tessl
- Last updated
testing.md docs/
1# Testing Support23FastAPI provides comprehensive testing capabilities through the TestClient class, which enables testing of FastAPI applications with full HTTP request simulation. The TestClient is built on top of HTTPX and provides a convenient interface for testing API endpoints without needing to run a live server.45## Capabilities67### TestClient Class89A test client for testing FastAPI applications with comprehensive HTTP request simulation capabilities.1011```python { .api }12class TestClient:13def __init__(14self,15app: ASGIApp,16base_url: str = "http://testserver",17raise_server_exceptions: bool = True,18root_path: str = "",19backend: str = "asyncio",20backend_options: dict = None,21cookies: httpx.Cookies = None,22headers: dict = None,23follow_redirects: bool = False,24) -> None:25"""26Create a test client for a FastAPI application.2728Parameters:29- app: The FastAPI application to test30- base_url: Base URL for requests (default: http://testserver)31- raise_server_exceptions: Whether to raise server exceptions during tests32- root_path: Root path for the application33- backend: Async backend to use (asyncio or trio)34- backend_options: Options for the async backend35- cookies: Default cookies for requests36- headers: Default headers for requests37- follow_redirects: Whether to automatically follow redirects38"""39```4041### HTTP Methods4243Standard HTTP methods for testing API endpoints with full request and response handling.4445```python { .api }46def get(self, url: str, **kwargs) -> httpx.Response:47"""Send GET request to the specified URL."""4849def post(self, url: str, **kwargs) -> httpx.Response:50"""Send POST request with optional data/json body."""5152def put(self, url: str, **kwargs) -> httpx.Response:53"""Send PUT request with optional data/json body."""5455def delete(self, url: str, **kwargs) -> httpx.Response:56"""Send DELETE request to the specified URL."""5758def patch(self, url: str, **kwargs) -> httpx.Response:59"""Send PATCH request with optional data/json body."""6061def head(self, url: str, **kwargs) -> httpx.Response:62"""Send HEAD request to the specified URL."""6364def options(self, url: str, **kwargs) -> httpx.Response:65"""Send OPTIONS request to the specified URL."""6667def request(68self,69method: str,70url: str,71**kwargs72) -> httpx.Response:73"""Send request with specified HTTP method."""74```7576### Context Manager Support7778TestClient supports context manager protocol for proper resource cleanup.7980```python { .api }81def __enter__(self) -> TestClient:82"""Enter context manager."""8384def __exit__(self, *args) -> None:85"""Exit context manager and cleanup resources."""86```8788### WebSocket Testing8990Support for testing WebSocket connections.9192```python { .api }93def websocket_connect(94self,95url: str,96subprotocols: List[str] = None,97**kwargs98) -> WebSocketTestSession:99"""Create WebSocket connection for testing."""100```101102## Usage Examples103104### Basic API Testing105106```python107from fastapi import FastAPI108from fastapi.testclient import TestClient109110app = FastAPI()111112@app.get("/items/{item_id}")113def read_item(item_id: int, q: str = None):114return {"item_id": item_id, "q": q}115116@app.post("/items/")117def create_item(item: dict):118return item119120# Create test client121client = TestClient(app)122123def test_read_item():124response = client.get("/items/1?q=test")125assert response.status_code == 200126assert response.json() == {"item_id": 1, "q": "test"}127128def test_create_item():129item_data = {"name": "Test Item", "price": 10.50}130response = client.post("/items/", json=item_data)131assert response.status_code == 200132assert response.json() == item_data133```134135### Testing with Authentication136137```python138from fastapi import FastAPI, Depends, HTTPException, status139from fastapi.security import HTTPBearer140from fastapi.testclient import TestClient141142app = FastAPI()143security = HTTPBearer()144145@app.get("/protected")146def protected_endpoint(token: str = Depends(security)):147if token.credentials != "valid-token":148raise HTTPException(status_code=401, detail="Invalid token")149return {"message": "Protected data"}150151client = TestClient(app)152153def test_protected_endpoint():154# Test without token155response = client.get("/protected")156assert response.status_code == 403157158# Test with invalid token159response = client.get(160"/protected",161headers={"Authorization": "Bearer invalid-token"}162)163assert response.status_code == 401164165# Test with valid token166response = client.get(167"/protected",168headers={"Authorization": "Bearer valid-token"}169)170assert response.status_code == 200171assert response.json() == {"message": "Protected data"}172```173174### Testing File Uploads175176```python177from fastapi import FastAPI, File, UploadFile178from fastapi.testclient import TestClient179import io180181app = FastAPI()182183@app.post("/upload/")184def upload_file(file: UploadFile = File(...)):185return {"filename": file.filename, "size": len(file.file.read())}186187client = TestClient(app)188189def test_file_upload():190test_file = io.BytesIO(b"test file content")191response = client.post(192"/upload/",193files={"file": ("test.txt", test_file, "text/plain")}194)195assert response.status_code == 200196data = response.json()197assert data["filename"] == "test.txt"198assert data["size"] > 0199```200201### Testing with Context Manager202203```python204from fastapi import FastAPI205from fastapi.testclient import TestClient206207app = FastAPI()208209@app.get("/")210def read_root():211return {"Hello": "World"}212213def test_with_context_manager():214with TestClient(app) as client:215response = client.get("/")216assert response.status_code == 200217assert response.json() == {"Hello": "World"}218```219220### WebSocket Testing221222```python223from fastapi import FastAPI, WebSocket224from fastapi.testclient import TestClient225226app = FastAPI()227228@app.websocket("/ws")229async def websocket_endpoint(websocket: WebSocket):230await websocket.accept()231await websocket.send_text("Hello WebSocket!")232await websocket.close()233234client = TestClient(app)235236def test_websocket():237with client.websocket_connect("/ws") as websocket:238data = websocket.receive_text()239assert data == "Hello WebSocket!"240```241242## Types243244```python { .api }245from typing import Any, Dict, List, Optional, Union246import httpx247from starlette.types import ASGIApp248249# Test client response type250TestResponse = httpx.Response251252# WebSocket test session253class WebSocketTestSession:254def send_text(self, data: str) -> None: ...255def send_bytes(self, data: bytes) -> None: ...256def send_json(self, data: Any) -> None: ...257def receive_text(self) -> str: ...258def receive_bytes(self) -> bytes: ...259def receive_json(self) -> Any: ...260def close(self, code: int = 1000) -> None: ...261```