File: test_example_12.py

package info (click to toggle)
python-polyfactory 3.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,148 kB
  • sloc: python: 11,529; makefile: 102; sh: 34
file content (27 lines) | stat: -rw-r--r-- 858 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from pydantic import AliasPath, BaseModel, Field

from polyfactory.factories.pydantic_factory import ModelFactory


class User(BaseModel):
    username: str = Field(..., validation_alias="user_name")
    email: str = Field(..., validation_alias=AliasPath("contact", "email"))  # type: ignore[pydantic-alias]


class UserFactory(ModelFactory[User]):
    __by_name__ = True

    # Set factory defaults using field names
    username = "john_doe"


def test_by_name() -> None:
    # Factory uses model_validate with by_name=True
    instance = UserFactory.build()
    assert instance.username == "john_doe"
    assert isinstance(instance.email, str)

    # Can override factory defaults
    instance2 = UserFactory.build(username="jane_doe", email="jane@example.com")
    assert instance2.username == "jane_doe"
    assert instance2.email == "jane@example.com"