TestClient provides a practical way to exercise an application route and inspect its response. A pytest test creates a client for the app, sends a request, and checks the returned status and JSON. section 4.3.1
Testing the /files endpoint
Create client = TestClient(app), call client.get("/files"), assert a 200 status, and compare response.json() with the expected file list. Change the endpoint, request type, status, or JSON to confirm that the test fails when validation is incorrect. section 4.3.1
Listing 4.4 Testing our first endpoint
from fastapi import FastAPI #1
from fastapi.testclient import TestClient #1
from app.main import app #1
client = TestClient(app) #2
def test_read_files(): #3
response = client.get("/files") #4
assert response.status_code == 200 #5
assert response.json() == #5
➥[{"file": "File_1"}, {"file": "File_2"}] #5
Use the complete endpoint test as a compact reference for imports, client construction, request execution, and response assertions. section 4.3.1
