Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 38 ยท Performance and Patterns

Testing and Design Patterns with Pydantic

Test Pydantic models, validators and settings with clear, small tests. Learn factories, parametrized cases, error assertions, DTO and repository patterns and schema versioning.

Models are code, and code that checks other code is where bugs hide. A validator with a wrong comparison silently accepts bad data, or rejects good data, and nobody notices until production. This lesson shows how to test Pydantic models well, and then collects four design patterns that appear in most Pydantic projects: boundary models (DTOs), factories for test data, a repository that hides storage, and versioned schemas.

The tests below use plain assert statements and a tiny runner, so they run in the editor on this page. In a real project you would use pytest (pip install pytest); the test bodies stay exactly the same, with pytest.raises and pytest.mark.parametrize replacing the helpers shown.

What to test

For each model, write tests for three things:

  1. Valid input gives the expected values, including conversions and defaults.
  2. Invalid input raises ValidationError with the right field and error type. Check errors(), not message text, because messages can change between versions.
  3. Boundaries: the smallest and largest allowed values and the first value just outside them. Most validator bugs hide at the boundary, for example > where you meant >=.
Python Model tests with asserts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A failing assert raises AssertionError with the line number. The else: branch of try catches the case "no exception when one was expected", which is the easiest test mistake to make.

With pytest the middle test shortens to a parametrized test:

Python
import pytest
from pydantic import ValidationError

@pytest.mark.parametrize("guests", [0, 9])
def test_guest_limits(guests):
    with pytest.raises(ValidationError) as info:
        Booking(guests=guests, email="[email protected]")
    assert info.value.errors()[0]["loc"] == ("guests",)

Test JSON round trips

A model that serializes and parses back to an equal model is consistent. This one test catches many mistakes in custom serializers and aliases.

Python A round-trip test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pattern 1: boundary models (DTOs)

A data transfer object is a model that exists only at a boundary: the request body, a message on a queue, a file format. Inside your program you can use richer domain objects. Keep the DTO strict (extra="forbid"), convert at the edge, and do not let it leak deep into business code. The earlier lessons on FastAPI request models use exactly this approach.

Pattern 2: factories for test data

Tests need many valid objects. Writing every field each time buries what the test is about. A small factory function returns a valid default and lets the test override only what matters:

Python A model factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each test names only the field it cares about, so a reader sees at once why paid=False blocks shipping.

Pattern 3: repository returning models

A repository hides where data lives. Its methods accept and return Pydantic models, so the rest of the program never touches dictionaries, SQL rows or file formats. The in-memory version below is also what your tests use.

Python An in-memory repository

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Swapping this class for one that uses SQLite or an HTTP API changes nothing in the callers, because the contract is "models in, models out".

Pattern 4: versioned schemas

Stored data and public APIs live longer than code. When a field changes, old records still have the old shape. A reliable approach is to tag every stored document with a version and migrate it on read with a before model validator.

Python Upgrading old documents on read

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Write a test per old version that loads a saved sample document, so you notice immediately if a change breaks an old format.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why assert on error type and location instead of the message text?

    type (such as int_parsing) and loc are part of the stable error format; the wording of msg may be improved over time.
  2. 2. Which boundary values should you test for a field with ge=1, le=8?

    Mistakes such as > instead of >= appear exactly at the edges.
  3. 3. What does a model factory like make_order(**overrides) achieve?

    Valid defaults keep tests short and make the intent of each test obvious.
  4. 4. How do you read old stored documents after the schema changed?

    A version tag plus a migration on read lets old and new documents coexist.

Summary

  • Test valid input, invalid input (error type and location) and boundaries; add a JSON round-trip test.
  • DTOs: strict models at the boundary, domain objects inside.
  • Factories keep tests short; repositories accept and return models.
  • Version stored documents and migrate old ones in a before validator.

Next: Project: A Configuration Loader