### Install Pre-commit Hooks Source: https://github.com/litestar-org/polyfactory/blob/main/CONTRIBUTING.rst Install `prek` and then run `prek install` to set up pre-commit hooks for linting and formatting. ```console prek install ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/litestar-org/polyfactory/blob/main/CONTRIBUTING.rst Use `uv sync` to install all necessary dependencies for the project, including extras, to set up your development environment. ```console uv sync --all-extras ``` -------------------------------- ### Install Polyfactory Source: https://github.com/litestar-org/polyfactory/blob/main/docs/getting-started.rst Install the library using pip. ```bash pip install polyfactory ``` -------------------------------- ### Dynamic Factory Generation Example Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/configuration.rst Demonstrates how factories generate new factories for supported types dynamically and cache them for reuse. ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Pet: name: str @dataclass class Person: name: str pet: Pet class PersonFactory(DataclassFactory[Person]): __model__ = Person person = PersonFactory.build() print(person.pet) ``` -------------------------------- ### Use Example Values in Factory Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/configuration.rst Set `__use_examples__` to True to use values from the `examples` attribute for fields. Requires Pydantic V2. ```python from typing import Literal from polyfactory.factories import PydanticV2Factory class User(BaseModel): name: str role: Literal["admin", "user", "guest"] model_config = ConfigDict( examples=[ {"name": "John Doe", "role": "admin"}, {"name": "Jane Doe", "role": "user"}, ] ) class UserFactory(PydanticV2Factory[User]): __use_examples__ = True user = UserFactory.build() assert user.role in ("admin", "user") ``` -------------------------------- ### Minimal Dataclass Example Source: https://github.com/litestar-org/polyfactory/blob/main/docs/getting-started.rst Demonstrates creating a mock data object for a dataclass with minimal configuration. Polyfactory infers generation strategies from type hints. ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Person: first_name: str last_name: str age: int class PersonFactory(DataclassFactory[Person]): __model__ = Person person = PersonFactory.build() print(person) # Person(first_name='...', last_name='...', age=...) ``` -------------------------------- ### Declare SQLAlchemy Factory Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/library_factories/sqlalchemy_factory.rst Declare a factory for a SQLAlchemy model. Ensure SQLAlchemy 2 is installed for these examples. ```python from polyfactory.factories import SQLAlchemyFactory from .models import User class UserFactory(SQLAlchemyFactory[User]): __model__ = User ``` -------------------------------- ### SQLAlchemy Example with Pre-fetched Data Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/fields.rst Demonstrates handling asynchronous data fetching outside the factory and passing the resolved value as a regular argument to the factory's build method, suitable for ORMs like SQLAlchemy. ```python from typing import Any from polyfactory.factories import DataclassFactory class User: def __init__(self, id: int, name: str, email: str) -> None: self.id = id self.name = name self.email = email class SQLAlchemyFactory(DataclassFactory[User]): @classmethod def build(cls, **kwargs: Any) -> User: # Simulate fetching data asynchronously # In a real scenario, this would involve an async database call prefetched_data = {"id": 123, "name": "Alice", "email": "alice@example.com"} # Merge prefetched data with any provided kwargs merged_kwargs = {**prefetched_data, **kwargs} return super().build(**merged_kwargs) # Example usage: # Assume 'get_user_data' is an async function that fetches user data # user_data = await get_user_data(user_id=123) # user = SQLAlchemyFactory.build(**user_data) # For demonstration purposes, we call build directly with simulated prefetched data user = SQLAlchemyFactory.build() assert user.id == 123 assert user.name == "Alice" assert user.email == "alice@example.com" ``` -------------------------------- ### Define Factory and Generate Coverage Examples Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/model_coverage.rst Use BaseFactory.coverage() to generate instances that cover all possible model variations. The number of generated instances is determined by the field with the highest number of options. ```python from polyfactory.factories import BaseFactory class Profile: def __init__(self, name: str, favourite_color: str, vehicle: str) -> None: self.name = name self.favourite_color = favourite_color self.vehicle = vehicle class ProfileFactory(BaseFactory[Profile]): __model__ = Profile @classmethod def favourite_color(cls) -> list[str]: return ["red", "blue", "green"] @classmethod def vehicle(cls) -> list[str]: return ["car", "bike"] # Generate coverage examples coverage_examples = ProfileFactory.coverage() for example in coverage_examples: print(example.__dict__) ``` -------------------------------- ### Using the post_generated decorator Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/decorators.rst This example demonstrates how to use the `post_generated` decorator. Classmethod parameters after `cls` must be named after the fields they depend on. ```python from polyfactory.decorators import post_generated from polyfactory.factories import DataclassFactory class User: def __init__(self, name: str, email: str) -> None: self.name = name self.email = email class UserFactory(DataclassFactory[User]): @post_generated @classmethod def set_email_domain(cls, name: str, __faker__) -> str: return f"{name.lower().replace(' ', '_')}@example.com" user = UserFactory.build() assert user.email == "user@example.com" ``` -------------------------------- ### ModelFactory for Pydantic Model Generation Source: https://context7.com/litestar-org/polyfactory/llms.txt Generates valid Pydantic model instances respecting field constraints, validators, and Field(examples=[...]). Set `__use_examples__ = True` to pick values from Field examples. ```python from pydantic import BaseModel, Field, EmailStr from polyfactory.factories.pydantic_factory import ModelFactory class UserProfile(BaseModel): username: str = Field(min_length=3, max_length=20) email: EmailStr age: int = Field(ge=18, le=120) score: float = Field(ge=0.0, le=1.0) currency: str = Field(examples=["USD", "EUR", "GBP"]) class UserProfileFactory(ModelFactory[UserProfile]): __use_examples__ = True # pick currency from Field examples profile = UserProfileFactory.build() assert 3 <= len(profile.username) <= 20 assert 18 <= profile.age <= 120 assert 0.0 <= profile.score <= 1.0 assert profile.currency in ["USD", "EUR", "GBP"] # Skip validation for speed-critical test setup raw = UserProfileFactory.build(factory_use_construct=True) assert isinstance(raw, UserProfile) ``` -------------------------------- ### Coverage Output for SocialGroup Model Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/model_coverage.rst When generating coverage for models with collection fields containing sub-models, the collection will include all coverage examples for those sub-models. ```python from polyfactory.factories import BaseFactory class Person: def __init__(self, name: str) -> None: self.name = name class PersonFactory(BaseFactory[Person]): __model__ = Person class SocialGroup: def __init__(self, name: str, members: list[Person]) -> None: self.name = name self.members = members class SocialGroupFactory(BaseFactory[SocialGroup]): __model__ = SocialGroup # Generate coverage examples coverage_examples = SocialGroupFactory.coverage() for example in coverage_examples: print(f"Group: {example.name}") for member in example.members: print(f" - Member: {member.name}") ``` -------------------------------- ### Create a New Release Source: https://github.com/litestar-org/polyfactory/blob/main/CONTRIBUTING.rst Run the `make release` command to automate version bumping and commit creation for a new release. ```console make release ``` -------------------------------- ### Run Linters and Formatters Source: https://github.com/litestar-org/polyfactory/blob/main/CONTRIBUTING.rst Optionally, run `prek run --all-files` to manually execute linters and formatters before committing changes. ```console prek run --all-files ``` -------------------------------- ### Persist to a real DB with create_sync() Source: https://context7.com/litestar-org/polyfactory/llms.txt Demonstrates persisting a generated model instance to a database using SQLAlchemy and Polyfactory's create_sync method. ```python from polyfactory.factories import DataclassFactory from sqlalchemy import create_engine from sqlalchemy.orm import Session # Assuming AuthorFactory and Base are defined elsewhere # from .models import Author, Base # engine = create_engine("sqlite:///:memory:") # Base.metadata.create_all(engine) # session = Session(engine) # AuthorFactory.__session__ = session # persisted_author = AuthorFactory.create_sync() # assert persisted_author.id is not None # assert persisted_author.id == persisted_author.books[0].author_id ``` -------------------------------- ### Define and Use Persistence Handlers Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/configuration.rst Specify sync and/or async persistence handlers for the factory to enable creation methods like .create_sync() and .create_batch_async(). ```python from polyfactory.factories import DataclassFactory from polyfactory.persistence import PersistenceHandler class SyncPersistenceHandler(PersistenceHandler): def create_sync(self, instance: object) -> object: # persist instance synchronously return instance def create_batch_sync(self, instances: list[object]) -> list[object]: # persist instances synchronously return instances class AsyncPersistenceHandler(PersistenceHandler): async def create_async(self, instance: object) -> object: # persist instance asynchronously return instance async def create_batch_async(self, instances: list[object]) -> list[object]: # persist instances asynchronously return instances class UserFactory(DataclassFactory[User]): __model__ = User __sync_persistence__ = SyncPersistenceHandler() __async_persistence__ = AsyncPersistenceHandler() ``` -------------------------------- ### Dynamically Generate a Factory with BaseFactory.create_factory() Source: https://context7.com/litestar-org/polyfactory/llms.txt Use `BaseFactory.create_factory()` to dynamically create a factory class at runtime for any supported model type. This is useful for one-off use cases and dynamic code generation. Configuration overrides can be passed during creation. ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Address: street: str city: str zip_code: str # Dynamically create a factory for Address AddressFactory = DataclassFactory.create_factory(Address) address = AddressFactory.build() assert isinstance(address, Address) assert isinstance(address.street, str) # Pass config overrides to the generated factory SeededAddressFactory = DataclassFactory.create_factory( Address, __random_seed__=42, __use_defaults__=True, ) addr1 = SeededAddressFactory.build() addr2 = SeededAddressFactory.build() # Reproducible values because of the fixed seed ``` -------------------------------- ### Sync Persistence with create_sync() Source: https://context7.com/litestar-org/polyfactory/llms.txt Persist models synchronously using a SyncPersistenceProtocol handler. Requires __sync_persistence__ to be set on the factory. ```python from typing import TypeVar from polyfactory.factories import DataclassFactory from polyfactory.persistence import SyncPersistenceProtocol T = TypeVar("T") class InMemoryRepo(SyncPersistenceProtocol[T]): store: list = [] def save(self, data: T) -> T: self.store.append(data) return data def save_many(self, data: list[T]) -> list[T]: self.store.extend(data) return data from dataclasses import dataclass @dataclass class Product: sku: str price: float class ProductFactory(DataclassFactory[Product]): __sync_persistence__ = InMemoryRepo product = ProductFactory.create_sync() assert isinstance(product, Product) products = ProductFactory.create_batch_sync(3) assert len(products) == 3 ``` -------------------------------- ### Build Mock Dataclass Instance with Polyfactory Source: https://github.com/litestar-org/polyfactory/blob/main/README.md Define a dataclass and a corresponding factory to build mock instances. The factory infers data types from the dataclass fields. ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Person: name: str age: float height: float weight: float class PersonFactory(DataclassFactory[Person]): ... def test_is_person() -> None: person_instance = PersonFactory.build() assert isinstance(person_instance, Person) ``` -------------------------------- ### Use SQLAlchemy Factory with Persistence Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/library_factories/sqlalchemy_factory.rst Configure the factory to use a SQLAlchemy session for persistence. By default, generated models are added to the session and then committed. ```python from polyfactory.factories import SQLAlchemyFactory from .models import Product from .session import session class ProductFactory(SQLAlchemyFactory[Product]): __model__ = Product __session__ = session ``` -------------------------------- ### Create Custom Base Factory for Dataclasses Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/handling_custom_types.rst Create a custom base factory by extending `DataclassFactory` and overriding `get_provider_map` to handle custom types consistently across multiple factories. This avoids code duplication when custom types are used frequently. ```python from polyfactory.factories import DataclassFactory class CustomSecret: def __init__(self, value: str) -> None: self.value = value class BaseSecretFactory(DataclassFactory[CustomSecret]): @classmethod def get_provider_map(cls) -> dict[type, callable]: # type: ignore return { CustomSecret: lambda: CustomSecret(value='jeronimo'), } class MyModelFactory(BaseSecretFactory): pass # Usage print(MyModelFactory.build()) ``` -------------------------------- ### Async Persistence with create_async() Source: https://context7.com/litestar-org/polyfactory/llms.txt Persist model instances asynchronously using an AsyncPersistenceProtocol handler. Requires __async_persistence__ to be set. ```python import asyncio from dataclasses import dataclass from typing import TypeVar from polyfactory.factories import DataclassFactory from polyfactory.persistence import AsyncPersistenceProtocol T = TypeVar("T") class AsyncInMemoryRepo(AsyncPersistenceProtocol[T]): store: list = [] async def save(self, data: T) -> T: self.store.append(data) return data async def save_many(self, data: list[T]) -> list[T]: self.store.extend(data) return data @dataclass class Event: event_id: int payload: str class EventFactory(DataclassFactory[Event]): __async_persistence__ = AsyncInMemoryRepo async def main() -> None: event = await EventFactory.create_async() assert isinstance(event, Event) events = await EventFactory.create_batch_async(5) assert len(events) == 5 asyncio.run(main()) ``` -------------------------------- ### Global type provider with BaseFactory.add_provider() Source: https://context7.com/litestar-org/polyfactory/llms.txt Registers a provider at the BaseFactory level so it applies to all factories in the process, not just a single subclass. Ensure providers are registered before factories are defined. ```python from dataclasses import dataclass from polyfactory.factories.base import BaseFactory from polyfactory.factories import DataclassFactory class Colour: def __init__(self, hex_code: str) -> None: self.hex_code = hex_code # Register globally before any factory is defined BaseFactory.add_provider(Colour, lambda: Colour("#ff5733")) @dataclass class Shirt: size: str colour: Colour class ShirtFactory(DataclassFactory[Shirt]): ... shirt = ShirtFactory.build() assert shirt.colour.hex_code == "#ff5733" ``` -------------------------------- ### Build a Single Dataclass Instance with Polyfactory Source: https://context7.com/litestar-org/polyfactory/llms.txt Use `DataclassFactory.build()` to create a single instance of a dataclass. Keyword arguments can override generated values for specific fields. ```python from dataclasses import dataclass from datetime import date, datetime from enum import Enum from typing import Union from uuid import UUID from polyfactory.factories import DataclassFactory class Species(str, Enum): CAT = "Cat" DOG = "Dog" @dataclass class Pet: name: str species: Species sound: str @dataclass class Person: id: UUID name: str hobbies: list[str] age: Union[float, int] birthday: Union[datetime, date] pets: list[Pet] class PersonFactory(DataclassFactory[Person]): __model__ = Person # optional when using the generic argument person = PersonFactory.build() assert isinstance(person, Person) assert isinstance(person.id, UUID) assert isinstance(person.hobbies, list) assert isinstance(person.pets[0], Pet) # Override individual fields at call-site specific = PersonFactory.build(name="Alice", age=30) assert specific.name == "Alice" assert specific.age == 30 ``` -------------------------------- ### Imperative Sub Factory Creation Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/declaring_factories.rst Create a sub-factory imperatively from an existing concrete factory, overriding some parent configuration. ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Person: name: str age: float class BasePersonFactory(DataclassFactory[Person]): ... # Create a sub-factory, inheriting the model from the parent SubPersonFactory = BasePersonFactory.create_factory() ``` -------------------------------- ### Imperative Factory Creation Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/declaring_factories.rst Create a factory imperatively using the `create_factory` method, specifying the model type. ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Person: name: str age: float # Imperatively create a factory for the Person model PersonFactory = DataclassFactory.create_factory(model=Person) ``` -------------------------------- ### Variable-Length Collections with `__randomize_collection_length__` Source: https://context7.com/litestar-org/polyfactory/llms.txt Enable randomly-sized collections by setting `__randomize_collection_length__` to `True`. The collection size will be bounded by `__min_collection_length__` and `__max_collection_length__`. ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Basket: items: list[str] tags: set[str] class BasketFactory(DataclassFactory[Basket]): __randomize_collection_length__ = True __min_collection_length__ = 2 __max_collection_length__ = 8 basket = BasketFactory.build() assert 2 <= len(basket.items) <= 8 assert 2 <= len(basket.tags) <= 8 ``` -------------------------------- ### Set Global SQLAlchemy Factory Overrides Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/library_factories/sqlalchemy_factory.rst Set up a global base factory by combining various settings, which can then be inherited by other factories. ```python from polyfactory.factories import SQLAlchemyFactory from .models import Base from .session import session class BaseSQLAlchemyFactory(SQLAlchemyFactory[Base]): __session__ = session __set_relationships__ = True __set_association_proxy__ = True class UserFactory(BaseSQLAlchemyFactory): __model__ = User class ProductFactory(BaseSQLAlchemyFactory): __model__ = Product ``` -------------------------------- ### Set Factory Faker Instance Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/configuration.rst Configure the factory's instance of Faker and set its locale. Results are deterministic when the random seed is also set. ```python from faker import Faker from polyfactory.factories import DataclassFactory class MyFactory(DataclassFactory[MyModel]): __faker__ = Faker(locale='es_ES') __random_seed__ = 1234 ``` -------------------------------- ### Build a Batch of Dataclass Instances with Polyfactory Source: https://context7.com/litestar-org/polyfactory/llms.txt Use `DataclassFactory.batch()` to generate a list of independently randomized model instances. Specify the desired number of instances using the `size` argument. ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Order: order_id: int amount: float status: str class OrderFactory(DataclassFactory[Order]): __model__ = Order orders = OrderFactory.batch(size=5) assert len(orders) == 5 assert all(isinstance(o, Order) for o in orders) # Each instance has independently randomised values assert len({o.order_id for o in orders}) > 1 # very likely unique ``` -------------------------------- ### DataclassFactory.batch() Source: https://context7.com/litestar-org/polyfactory/llms.txt Returns a list of `size` independently-generated model instances, each with different random values. ```APIDOC ## DataclassFactory.batch() — Build a list of instances Returns a list of `size` independently-generated model instances, each with different random values. ### Method DataclassFactory.batch(size: int) ### Parameters - **size** (int) - The number of instances to generate. ### Request Example ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Order: order_id: int amount: float status: str class OrderFactory(DataclassFactory[Order]): __model__ = Order orders = OrderFactory.batch(size=5) assert len(orders) == 5 assert all(isinstance(o, Order) for o in orders) # Each instance has independently randomised values assert len({o.order_id for o in orders}) > 1 # very likely unique ``` ### Response #### Success Response - A list of instances of the target dataclass. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Dynamic Factory Generation Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/declaring_factories.rst Dynamically create a factory for a different model using `create_factory` within an existing factory class. ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Pet: name: str age: int class PersonFactory(DataclassFactory[object]): @classmethod def _create_model_class(cls, model_class: type[object]) -> type[object]: return Pet # This will create a factory for the Pet model PetFactory = PersonFactory.create_factory() ``` -------------------------------- ### Shared provider extensions with custom base factory Source: https://context7.com/litestar-org/polyfactory/llms.txt Create a reusable base factory that propagates custom providers to all downstream factories automatically by setting `__is_base_factory__ = True`. ```python from dataclasses import dataclass from typing import Any, Generic, TypeVar from uuid import UUID from polyfactory.factories import DataclassFactory class CustomSecret: def __init__(self, value: str) -> None: self.value = value T = TypeVar("T") class AppDataclassFactory(DataclassFactory[T], Generic[T]): """Project-wide base factory with all custom type providers.""" __is_base_factory__ = True @classmethod def get_provider_map(cls) -> dict[type, Any]: return { CustomSecret: lambda: CustomSecret("default-secret"), **super().get_provider_map(), } @dataclass class User: id: UUID api_key: CustomSecret @dataclass class Service: name: str token: CustomSecret class UserFactory(AppDataclassFactory[User]): ... class ServiceFactory(AppDataclassFactory[Service]): ... user = UserFactory.build() svc = ServiceFactory.build() assert user.api_key.value == "default-secret" assert svc.token.value == "default-secret" ``` -------------------------------- ### DataclassFactory.build() Source: https://context7.com/litestar-org/polyfactory/llms.txt Build a single instance of a dataclass. Any keyword argument passed overrides the generated value for that field. ```APIDOC ## DataclassFactory.build() — Build a single instance Introspects the target dataclass and returns one fully-populated instance. Any keyword argument passed overrides the generated value for that field. ### Method DataclassFactory.build() ### Parameters Any keyword arguments passed to `build` will override the generated value for the corresponding field. ### Request Example ```python from dataclasses import dataclass from datetime import date, datetime from enum import Enum from typing import Union from uuid import UUID from polyfactory.factories import DataclassFactory class Species(str, Enum): CAT = "Cat" DOG = "Dog" @dataclass class Pet: name: str species: Species sound: str @dataclass class Person: id: UUID name: str hobbies: list[str] age: Union[float, int] birthday: Union[datetime, date] pets: list[Pet] class PersonFactory(DataclassFactory[Person]): __model__ = Person # optional when using the generic argument person = PersonFactory.build() assert isinstance(person, Person) assert isinstance(person.id, UUID) assert isinstance(person.hobbies, list) assert isinstance(person.pets[0], Pet) # Override individual fields at call-site specific = PersonFactory.build(name="Alice", age=30) assert specific.name == "Alice" assert specific.age == 30 ``` ### Response #### Success Response - An instance of the target dataclass, fully populated with generated data. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Configure SQLAlchemy Factory Association Proxies Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/library_factories/sqlalchemy_factory.rst Configure the factory to include SQLAlchemy association proxies. By default, __set_association_proxy__ is True. If True, both the association_proxy and its relationship fields will be created, with the relationship field being overwritten by create_sync/create_async. ```python from polyfactory.factories import SQLAlchemyFactory from .models import Comment class CommentFactory(SQLAlchemyFactory[Comment]): __model__ = Comment __set_association_proxy__ = True ``` -------------------------------- ### BaseFactory.create_factory() Source: https://context7.com/litestar-org/polyfactory/llms.txt Creates a new factory class at runtime for any supported model type without writing an explicit subclass. Useful for one-off use cases and dynamic code. ```APIDOC ## BaseFactory.create_factory() — Dynamically generate a factory Creates a new factory class at runtime for any supported model type without writing an explicit subclass. Useful for one-off use cases and dynamic code. ### Method BaseFactory.create_factory(model_type, **factory_kwargs) ### Parameters - **model_type**: The type (e.g., dataclass, Pydantic model) for which to create a factory. - **factory_kwargs**: Optional keyword arguments to configure the generated factory (e.g., `__random_seed__`, `__use_defaults__`). ### Request Example ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Address: street: str city: str zip_code: str # Dynamically create a factory for Address AddressFactory = DataclassFactory.create_factory(Address) address = AddressFactory.build() assert isinstance(address, Address) assert isinstance(address.street, str) # Pass config overrides to the generated factory SeededAddressFactory = DataclassFactory.create_factory( Address, __random_seed__=42, __use_defaults__=True, ) addr1 = SeededAddressFactory.build() addr2 = SeededAddressFactory.build() # Reproducible values because of the fixed seed ``` ### Response #### Success Response - A dynamically created factory class. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Attrs Class Support Source: https://context7.com/litestar-org/polyfactory/llms.txt Generate instances of attrs-decorated classes. ```python import attr from polyfactory.factories.attrs_factory import AttrsFactory @attr.s(auto_attribs=True) class Vector: x: float y: float z: float = 0.0 class VectorFactory(AttrsFactory[Vector]): ... v = VectorFactory.build() assert isinstance(v, Vector) assert isinstance(v.x, float) ``` -------------------------------- ### Randomized Collection Length Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/configuration.rst Configure the factory to generate collections with random lengths using __min_collection_length__ and __max_collection_length__. ```python from polyfactory.factories import DataclassFactory class MyFactory(DataclassFactory[MyModel]): __min_collection_length__ = 3 __max_collection_length__ = 8 ``` -------------------------------- ### Deterministic Generation with `__random_seed__` and `__random__` Source: https://context7.com/litestar-org/polyfactory/llms.txt Seed the internal `Random` instance using `__random_seed__` at class definition or `DataclassFactory.seed_random()` at runtime for reproducible output. This is crucial for snapshot tests and regression suites. ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Person: name: str age: float # Option 1: seed via class attribute (seeds at class definition) class SeededFactory(DataclassFactory[Person]): __random_seed__ = 1 @classmethod def name(cls) -> str: return cls.__random__.choice(["John", "Alice", "George"]) assert SeededFactory.build().name == "John" assert SeededFactory.build().name == "George" # Option 2: call seed_random() at runtime DataclassFactory.seed_random(42) ``` -------------------------------- ### Generate Dataclass Instance with Polyfactory Source: https://github.com/litestar-org/polyfactory/blob/main/docs/PYPI_README.md Use DataclassFactory to build mock instances of a dataclass. The factory infers data types from the dataclass's type hints. ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Person: name: str age: float height: float weight: float class PersonFactory(DataclassFactory[Person]): ... def test_is_person() -> None: person_instance = PersonFactory.build() assert isinstance(person_instance, Person) ``` -------------------------------- ### Declare Factory for Dataclass Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/declaring_factories.rst Declare a factory for a dataclass by subclassing `DataclassFactory` and specifying the model type. ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Person: name: str age: float height: float weight: float class PersonFactory(DataclassFactory[Person]): ... ``` -------------------------------- ### Register custom type providers with get_provider_map() Source: https://context7.com/litestar-org/polyfactory/llms.txt Override get_provider_map() on a factory to handle types that polyfactory cannot resolve automatically. Each entry maps a type to a zero-argument callable. ```python from dataclasses import dataclass from uuid import UUID from typing import Any from polyfactory.factories import DataclassFactory class CustomSecret: def __init__(self, value: str) -> None: self.value = value def __repr__(self) -> str: return "*" * len(self.value) @dataclass class Person: id: UUID secret: CustomSecret class PersonFactory(DataclassFactory[Person]): @classmethod def get_provider_map(cls) -> dict[type, Any]: return { CustomSecret: lambda: CustomSecret("s3cr3t"), **super().get_provider_map(), } person = PersonFactory.build() assert isinstance(person.secret, CustomSecret) assert person.secret.value == "s3cr3t" ``` -------------------------------- ### Configure SQLAlchemy Factory Persistence Method Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/library_factories/sqlalchemy_factory.rst Configure the factory to use flush() instead of commit() for persisting data. This allows changes to be saved to the database without permanently committing them. ```python from polyfactory.factories import SQLAlchemyFactory from polyfactory.persistence import SQLAlchemyPersistenceMethod from .models import Order from .session import session class OrderFactory(SQLAlchemyFactory[Order]): __model__ = Order __session__ = session __persistence_method__ = SQLAlchemyPersistenceMethod.FLUSH ``` -------------------------------- ### Use Callable for Field Generation Source: https://context7.com/litestar-org/polyfactory/llms.txt Wrap a callable with optional arguments to generate a field's value. The callable is invoked on each build. ```python from dataclasses import dataclass from enum import Enum from polyfactory import Use from polyfactory.factories import DataclassFactory class Species(str, Enum): CAT = "Cat" DOG = "Dog" @dataclass class Pet: name: str species: Species sound: str @dataclass class Person: name: str pets: list[Pet] class PetFactory(DataclassFactory[Pet]): # Use wraps random.choice; args/kwargs forwarded to fn name = Use(DataclassFactory.__random__.choice, ["Ralph", "Roxy"]) species = Use(DataclassFactory.__random__.choice, list(Species)) class PersonFactory(DataclassFactory[Person]): # Use a factory's batch method to generate a list pets = Use(PetFactory.batch, size=2) person = PersonFactory.build() assert len(person.pets) == 2 assert all(pet.name in ["Ralph", "Roxy"] for pet in person.pets) ``` -------------------------------- ### Require Field Value at Build Time Source: https://context7.com/litestar-org/polyfactory/llms.txt Use `Require` to enforce that a field value must be provided when calling `build()`. Omitting it raises `MissingBuildKwargException`. ```python from typing import TypedDict import pytest from polyfactory import Require from polyfactory.exceptions import MissingBuildKwargException from polyfactory.factories import TypedDictFactory class Person(TypedDict): id: int name: str class PersonFactory(TypedDictFactory[Person]): id = Require() # caller MUST pass id= # Providing the required kwarg works fine person = PersonFactory.build(id=42) assert person["id"] == 42 assert isinstance(person["name"], str) # Omitting it raises an exception with pytest.raises(MissingBuildKwargException): PersonFactory.build() ``` -------------------------------- ### Configure SQLAlchemy Factory Relationships Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/library_factories/sqlalchemy_factory.rst Configure the factory to include SQLAlchemy relationships in generated data. By default, __set_relationships__ is True. If True, ForeignKey fields associated with relationships will be automatically generated but overwritten by create_sync/create_async. ```python from polyfactory.factories import SQLAlchemyFactory from .models import Post class PostFactory(SQLAlchemyFactory[Post]): __model__ = Post __set_relationships__ = True ``` -------------------------------- ### Enable Check Factory Fields Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/configuration.rst When __check_model__ is True, declaring fields on the factory that don't exist on the model will trigger an exception. This is only true when fields are declared with Use, PostGenerated, Ignore, and Require. ```python from polyfactory.factories import DataclassFactory class MyFactory(DataclassFactory[MyModel]): __check_model__ = True ``` -------------------------------- ### DataclassFactory.coverage() Source: https://context7.com/litestar-org/polyfactory/llms.txt Yields one instance per possible value of Literal fields and Union branches, guaranteeing that every declared variant is exercised at least once. ```APIDOC ## DataclassFactory.coverage() — Exhaustive sub-type coverage Yields one instance per possible value of Literal fields and Union branches, guaranteeing that every declared variant is exercised at least once. ### Method DataclassFactory.coverage() ### Parameters None ### Request Example ```python from __future__ import annotations from dataclasses import dataclass from typing import Literal from polyfactory.factories.dataclass_factory import DataclassFactory @dataclass class Car: model: str @dataclass class Boat: can_float: bool @dataclass class Profile: age: int favourite_color: Literal["red", "green", "blue"] vehicle: Car | Boat class ProfileFactory(DataclassFactory[Profile]): ... profiles = list(ProfileFactory.coverage()) # Three instances: one per Literal value assert profiles[0].favourite_color == "red" assert isinstance(profiles[0].vehicle, Car) assert profiles[1].favourite_color == "green" assert isinstance(profiles[1].vehicle, Boat) assert profiles[2].favourite_color == "blue" ``` ### Response #### Success Response - An iterator yielding instances of the target dataclass, covering all possible variants. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Declare Factory for TypedDict Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/declaring_factories.rst Declare a factory for a `TypedDict` by subclassing `TypedDictFactory` and specifying the model type. ```python from typing import TypedDict from polyfactory.factories import TypedDictFactory class Pet(TypedDict): name: str age: int class PetFactory(TypedDictFactory[Pet]): ... ``` -------------------------------- ### Exhaustive Sub-type Coverage with DataclassFactory.coverage() Source: https://context7.com/litestar-org/polyfactory/llms.txt Use `DataclassFactory.coverage()` to yield instances covering all possible values of Literal fields and Union branches. This guarantees that every declared variant is exercised at least once. ```python from __future__ import annotations from dataclasses import dataclass from typing import Literal from polyfactory.factories.dataclass_factory import DataclassFactory @dataclass class Car: model: str @dataclass class Boat: can_float: bool @dataclass class Profile: age: int favourite_color: Literal["red", "green", "blue"] vehicle: Car | Boat class ProfileFactory(DataclassFactory[Profile]): ... profiles = list(ProfileFactory.coverage()) # Three instances: one per Literal value assert profiles[0].favourite_color == "red" assert isinstance(profiles[0].vehicle, Car) assert profiles[1].favourite_color == "green" assert isinstance(profiles[1].vehicle, Boat) assert profiles[2].favourite_color == "blue" ``` -------------------------------- ### Declare Custom Fields Using Class Methods Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/fields.rst Leverage class methods within a factory to define custom field generation logic, providing access to the factory instance for more complex or stateful generation. ```python from polyfactory.factories import DataclassFactory class Pet: def __init__(self, name: str, type: str) -> None: self.name = name self.type = type class Person: def __init__(self, name: str, age: int, pets: list[Pet]) -> None: self.name = name self.age = age self.pets = pets class PersonFactory(DataclassFactory[Person]): @classmethod def pets(cls) -> list[Pet]: return [Pet(name="Buddy", type="dog")] person = PersonFactory.build() assert person.pets == [Pet(name="Buddy", type="dog")] ``` -------------------------------- ### Respect Model Default Values with `__use_defaults__` Source: https://context7.com/litestar-org/polyfactory/llms.txt When `__use_defaults__` is `True`, the factory will use the field's declared default value or `default_factory` instead of generating a random one. Fields without defaults will still be randomly generated. ```python from dataclasses import dataclass from enum import Enum from polyfactory.factories import DataclassFactory class Species(str, Enum): CAT = "Cat" DOG = "Dog" @dataclass class Pet: name: str sound: str = "meow" species: Species = Species.CAT class PetFactory(DataclassFactory[Pet]): __use_defaults__ = True pet = PetFactory.build() assert pet.sound == "meow" assert pet.species == Species.CAT # 'name' has no default, so it is still randomly generated assert isinstance(pet.name, str) ``` -------------------------------- ### Set Factory Random Instance Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/configuration.rst Set the actual instance of random.Random. This is useful when embedding factories inside more complex logic or when factories are being dynamically generated. ```python import random from polyfactory.factories import DataclassFactory class MyFactory(DataclassFactory[MyModel]): __random__ = random.Random(1234) ``` -------------------------------- ### TypedDictFactory for TypedDict Generation Source: https://context7.com/litestar-org/polyfactory/llms.txt Generates instances of TypedDict classes, behaving identically to DataclassFactory but targeting TypedDict. ```python from typing import TypedDict, Optional from polyfactory.factories import TypedDictFactory class Config(TypedDict): host: str port: int debug: Optional[bool] tags: list[str] class ConfigFactory(TypedDictFactory[Config]): ... cfg = ConfigFactory.build() assert isinstance(cfg["host"], str) assert isinstance(cfg["port"], int) assert isinstance(cfg["tags"], list) # Build a batch for parameterised tests configs = ConfigFactory.batch(3) assert len(configs) == 3 ``` -------------------------------- ### Resolve Forward-Reference Types with `__forward_references__` Source: https://context7.com/litestar-org/polyfactory/llms.txt Use `__forward_references__` to provide a mapping from forward-reference strings to concrete types, enabling the factory to handle recursive or mutually-dependent models. ```python from __future__ import annotations from dataclasses import dataclass from typing import Union from polyfactory.factories import DataclassFactory RecursiveType = Union[list["RecursiveType"], int] @dataclass class RecursiveModel: value: RecursiveType class RecursiveModelFactory(DataclassFactory[RecursiveModel]): __forward_references__ = {"RecursiveType": int} # resolve to int result = RecursiveModelFactory.build() assert isinstance(result.value, int) or ( isinstance(result.value, list) and all(isinstance(v, int) for v in result.value) ) ``` -------------------------------- ### Register Factory as Pytest Fixture Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/fixtures.rst Use the `register_fixture` decorator to automatically register a factory as a pytest fixture. This makes the factory available for use in your tests. ```python from polyfactory.pytest_plugin import register_fixture from polyfactory.factories import DataclassFactory class User: def __init__(self, id: int, name: str) -> None: self.id = id self.name = name @register_fixture class UserFactory(DataclassFactory[User]): __model__ = User ``` -------------------------------- ### Use Default Values in Factory Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/configuration.rst Set `__use_defaults__` to True to use field default values instead of random ones. This setting is ignored for TypedDicts. ```python from polyfactory.factories import DataclassFactory class User: def __init__(self, name: str, age: int = 18) -> None: self.name = name self.age = age class UserFactory(DataclassFactory[User]): __use_defaults__ = True user = UserFactory.build() assert user.age == 18 ``` -------------------------------- ### Custom SQLAlchemy column types with get_sqlalchemy_types() Source: https://context7.com/litestar-org/polyfactory/llms.txt Override get_sqlalchemy_types() to teach the factory how to generate values for custom TypeEngine subclasses. Ensure the custom type is registered in the factory's mapping. ```python from decimal import Decimal from typing import Any from collections.abc import Callable from sqlalchemy import types from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from polyfactory.factories.sqlalchemy_factory import SQLAlchemyFactory class Location(types.TypeEngine): cache_ok = True class Base(DeclarativeBase): ... class Place(Base): __tablename__ = "location" id: Mapped[int] = mapped_column(primary_key=True) location: Mapped[tuple[Decimal, Decimal]] = mapped_column(Location) class PlaceFactory(SQLAlchemyFactory[Place]): @classmethod def get_sqlalchemy_types(cls) -> dict[Any, Callable[[], Any]]: mapping = super().get_sqlalchemy_types() mapping[Location] = cls.__faker__.latlng # returns (lat, lng) tuple return mapping place = PlaceFactory.build() assert isinstance(place.location, tuple) ``` -------------------------------- ### Declare Factory for Pydantic Model Source: https://github.com/litestar-org/polyfactory/blob/main/docs/usage/declaring_factories.rst Declare a factory for a Pydantic model by subclassing `PydanticFactory` and specifying the model type. ```python from pydantic import BaseModel from polyfactory.factories import PydanticFactory class Pet(BaseModel): name: str age: int class PetFactory(PydanticFactory[Pet]): ... ``` -------------------------------- ### Msgspec Struct Support Source: https://context7.com/litestar-org/polyfactory/llms.txt Generate instances of msgspec.Struct subclasses with full constraint handling. ```python import msgspec from polyfactory.factories.msgspec_factory import MsgspecFactory class Point(msgspec.Struct): x: float y: float label: str = "origin" class PointFactory(MsgspecFactory[Point]): ... pt = PointFactory.build() assert isinstance(pt, Point) assert isinstance(pt.x, float) ```