FastAPI automated testing

Introduction to FastAPI

Matt Eckerle

Software and Data Engineering Leader

What Are Automated Tests?

Unit Tests

  • Focus: Isolated code
  • Purpose: Validate code function
  • Scope: Function or method
  • Environment: Isolated Python env
def test_main():
    response = main()
    assert response == {"msg": "Hello"}

System Tests

  • Focus: Isolated system operations
  • Purpose: Validate system function
  • Scope: Endpoint
  • Environment: Python env with app running
def test_read_main():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": 
                               "Hello"}
Introduction to FastAPI

Using TestClient

TestClient: HTTP client for pytest

# Import TestClient and app
from fastapi.testclient import TestClient
from .main import app

# Create test client with application context
client = TestClient(app)

def test_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello"}
Introduction to FastAPI

Testing Error or Failure Responses

App

app = FastAPI()

@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        raise HTTPException(
            status_code=404, 
            detail="Item not found.")
    else:
        delete_item_in_database(item)
        return {}

Test

def test_delete_nonexistent_item():
    response = client.delete(
        "/items",
        json={"id": -999})
    assert response.status_code == 404
    json = response.json()
    assert json == {"detail":
                    "Item not found."}
Introduction to FastAPI

Let's practice!

Introduction to FastAPI

Preparing Video For Download...