Performance: TestClient basics
This affects the speed and efficiency of backend API testing, impacting developer feedback loop and CI pipeline speed.
from fastapi.testclient import TestClient from myapp import app client = TestClient(app) response = client.get('/items/1') assert response.status_code == 200
import requests response = requests.get('http://localhost:8000/items/1') assert response.status_code == 200
| Pattern | Network Calls | Server Dependency | Test Speed | Verdict |
|---|---|---|---|---|
| Real HTTP requests with requests library | Yes | Requires running server | Slow due to network latency | [X] Bad |
| In-memory requests with FastAPI TestClient | No | No server needed | Fast, immediate response | [OK] Good |
TestClient?app?response.status_code be?
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/hello")
def hello():
return {"message": "Hi"}
client = TestClient(app)
response = client.get("/hello")
print(response.status_code)from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
client = TestClient(app)
response = client.get("/items/item1")
print(response.status_code)item_id but the test sends 'item1' which is a string./users/ that expects JSON data {"name": "Alice"}. Which TestClient call correctly sends this data and checks for a 201 status code?
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.post("/users/")
def create_user(user: dict):
return user, 201
client = TestClient(app)
# Which call is correct?json= sends JSON correctly.response.status_code == 201 is correct.Pass the test and this pattern moves unknown