Component testing evaluates one software component in isolation. For an API, it exercises requests and responses without requiring the other application components, helping reveal malformed requests and exception conditions. section 4.3.1
Use component testing to:
- Check an endpoint’s status code and returned data. section 4.3.1
- Test more behavior than a unit test while avoiding the dependencies of integration testing. section 4.3.1
- Place fast, relatively isolated checks below integration, UI, and manual testing in the testing pyramid. section 4.3.1
Testing a GET endpoint
A FastAPI test creates a TestClient, calls GET /files, asserts a 200 status code, and verifies the JSON response. The same endpoint can also be described with a BDD feature and step definitions. 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
Inspect the complete endpoint test, including TestClient setup, the GET request, status assertion, and JSON assertion. section 4.3.1


