Skip to content
Sarj Code Standards

prefer-pydantic-model-assertion

Compare a Pydantic model or an explicit field projection instead of consecutive property assertions.

Why

Consecutive assertions on the same model scatter one expected record across statements and obscure which fields form the test's contract.

Fix

Prefer 'assert result == ExpectedModel(...)' for the complete contract, or 'assert result.model_dump(include={...}) == {...}' for an intentional subset. Keep any needed None guard. Preserve identity, approximate comparisons, custom serialization and private-attribute semantics; do not fill irrelevant fields or use model_construct/model_copy to bypass validation.

Examples

Before — flagged Two assertions describe one expected model
tests/test_user.py
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
def test_user(result: User):
assert result.id == 1
assert result.name == "Alice"
After — preferred One assertion states the selected field contract
tests/test_user.py
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
def test_user(result: User):
assert result.model_dump(include={"id", "name"}) == {"id": 1, "name": "Alice"}