Guide Home Part 1 - FastAPI Foundations Part 2 - Building Applications Part 3 - Pages and HTML Part 4 - Security and Deployment Part 5 - Going Further Capstone Build Plan Markdown Source All Guides

Chapter 35: Unit Testing

ASP.NET Core developers often use xUnit, Moq, and FluentAssertions. Python's standard path is pytest.

Domain test:

import pytest

from recipevault.domain.recipes import RecipeDraft


def test_recipe_title_is_required():
    with pytest.raises(ValueError):
        RecipeDraft(title="", instructions="Mix.", servings=2)

Service test:

def test_owner_can_publish_recipe(fake_repo):
    service = RecipeService(fake_repo)
    recipe = service.publish(recipe_id=1, user_id=42)
    assert recipe.is_published

Testing practices:

Python tests are pleasant when your application logic is not trapped inside route functions.