liveBook · Manning

Pytest

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

pytest is a Python testing framework for writing and running automated tests.

pytest is a Python testing framework for writing and running automated tests. It supports short feedback cycles by checking small pieces of functionality as code is built, including generated code that still requires verification. section 2.4

A practical pytest workflow starts with small questions and expands toward deeper behavior:

  • Check whether a file can be read and whether it contains the expected number of records. section 2.4
  • Test individual record types and parsing behavior after the basic file-reading test works. section 2.4
  • Exercise an API endpoint through FastAPI's TestClient, then assert its HTTP status and JSON response. section 4.3.1
  • Deliberately change the endpoint, request type, expected status, or expected JSON to confirm that the test can fail. section 4.3.1

Testing a files endpoint

Create a TestClient for the application, call GET /files, assert status code 200, and compare the returned JSON with the expected file list. 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 endpoint test listing as a compact reference for importing TestClient, creating a client, making a request, and asserting the response. section 4.3.1

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

How deep it goes
Builds from file-reading checks to record parsing and HTTP assertions, while deferring broader testing categories and deeper application behavior.
Examples
Demonstrates ACH-file parsing checks and a GET /files test that verifies status code 200 and a hardcoded JSON response.
What it assumes
Assumes basic Python application code and HTTP concepts, while teaching test construction from simple file checks and endpoint requests.
What you can do after
Apply it via pytest and TestClient to validate parsing logic and API responses, including tests designed to fail when expectations are wrong.
How it connects
Connects unit testing with test-driven development, integration testing, behavior-driven development, FastAPI, and TestClient.

Also explained in

Compare how 11 books explain pytest →

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.