liveBook · Manning

TestClient

As explained in Build Financial Software with Generative AI (From Scratch)

TestClient is a testing client interface that sends requests to an application and exposes the resulting responses for assertions.

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

How Build Financial Software with Generative AI (From Scratch) covers it

How deep it goes
Defines client creation, GET requests, status and JSON assertions, but does not detail client internals.
Examples
Uses a hardcoded /files response containing File_1 and File_2, then verifies status codes and JSON values.
What it assumes
Assumes an application object, an HTTP endpoint, and basic pytest assertions; demonstrates the testing workflow explicitly.
What you can do after
Apply it via FastAPI and pytest to send endpoint requests, assert responses, and verify that tests detect incorrect expectations.
How it connects
Connects FastAPI, pytest, HTTP requests, unit testing, integration testing, and behavior-driven development.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Financial Software with Generative AI (From Scratch). The section links point to the parts of the book it draws on.