Skip to content
Latchkey

FastAPI "pydantic ValidationError" in tests in CI

A model rejected the data a test built directly. In Pydantic v2 validation is stricter about types and coercion, so fixtures that passed on v1 (or before a field change) now raise ValidationError when constructing the model.

What this error means

A unit test that constructs a Pydantic model fails with "pydantic_core.ValidationError: N validation error(s)" listing the offending fields and their type errors.

python
pydantic_core._pydantic_core.ValidationError: 1 validation error for Item
price
  Input should be a valid number, unable to parse string as a number
  [type=float_parsing, input_value='ten', input_type=str]

Common causes

The test payload no longer matches the schema

A field was renamed, made required, or retyped, but the fixture still uses the old shape, so construction fails validation.

Pydantic v2 stricter coercion

v2 rejects some loose conversions v1 accepted (for example a non-numeric string for a float), surfacing latent test data problems.

How to fix it

Update fixtures to the current schema

  1. Read the field names and error types in the ValidationError.
  2. Fix the fixture values or use a factory that mirrors the model.
  3. Re-run the test to confirm the model constructs.
tests/factories.py
def make_item(**over):
    data = {"name": "widget", "price": 9.99}
    data.update(over)
    return Item(**data)

Assert validation failures explicitly

Where a test intends to prove rejection, catch the error rather than letting it bubble up as a test failure.

tests/test_models.py
import pytest
from pydantic import ValidationError

with pytest.raises(ValidationError):
    Item(name="x", price="ten")

How to prevent it

  • Build test data with factories tied to the current model.
  • Update fixtures in the same commit as schema changes.
  • Assert intended validation failures with pytest.raises(ValidationError).

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →