Use when working with polyfactory, ModelFactory, DataclassFactory, MsgspecFactory, AttrsFactory, Use, register_fixture, pytest plugin, __random_seed__, or coverage(). Not for production seeding.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Polyfactory?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/litestar-org-polyfactory-litestar-skills)
---
name: polyfactory
description: "Use when working with polyfactory, ModelFactory, DataclassFactory, MsgspecFactory, AttrsFactory, Use, register_fixture, pytest plugin, __random_seed__, or coverage(). Not for production seeding."
---
# polyfactory
Polyfactory is a typed mock-data factory library: declare `ModelFactory[T]` (or `DataclassFactory`, `MsgspecFactory`, `AttrsFactory`, `TypedDictFactory`, `SQLAlchemyFactory`) and `.build()` returns a populated instance of `T`. The matching factory base inspects the model's annotations and supported constraints so tests do not need hand-written happy-path fixtures.
In Litestar projects, polyfactory's pytest plugin feeds `TestClient.post(...)` and `AsyncTestClient.put(...)` payloads. The companion `litestar-testing` skill covers the request side.
## Code Style Rules
- PEP 604 unions (`T | None`), never `Optional[T]`.
- One factory per model. Do not reuse a factory across unrelated models.
- Pick the factory base matching the model backend; a mismatched base raises `ConfigurationException`.
- Import backend-specific factories from their concrete submodules (`polyfactory.factories.pydantic_factory`, `polyfactory.factories.msgspec_factory`, `polyfactory.factories.sqlalchemy_factory`, `polyfactory.factories.attrs_factory`), `register_fixture` from `polyfactory.pytest_plugin`, and `post_generated` from `polyfactory.decorators`.
- Prefer `register_fixture` over hand-rolled `@pytest.fixture` wrappers in a pytest-discovered test module or `conftest.py`.
## Quick Reference
### Factory Bases
| Model kind | Factory base | Import |
| --- | --- | --- |
| `pydantic.BaseModel` | `ModelFactory` | `from polyfactory.factories.pydantic_factory import ModelFactory` |
| `@dataclass` | `DataclassFactory` | `from polyfactory.factories.dataclass_factory import DataclassFactory` |
| `msgspec.Struct` | `MsgspecFactory` | `from polyfactory.factories.msgspec_factory import MsgspecFactory` |
| `@attrs.define` / `attr.s` | `AttrsFactory` | `from polyfactory.factories.attrs_factory import AttrsFactory` |
| `TypedDict` | `TypedDictFactory` | `from polyfactory.factories.typed_dict_factory import TypedDictFactory` |
| SQLAlchemy declarative | `SQLAlchemyFactory` | `from polyfactory.factories.sqlalchemy_factory import SQLAlchemyFactory` |
| Beanie `Document` | `BeanieDocumentFactory` | `from polyfactory.factories.beanie_odm_factory import BeanieDocumentFactory` |
| Odmantic `Model` / `EmbeddedModel` | `OdmanticModelFactory` | `from polyfactory.factories.odmantic_odm_factory import OdmanticModelFactory` |
`polyfactory.factories.__all__` exports only `BaseFactory`, `DataclassFactory`, and `TypedDictFactory`.
### Defining and Customizing a Factory
```python
from polyfactory import Ignore, Require, Use
from polyfactory.decorators import post_generated
from polyfactory.factories.dataclass_factory import DataclassFactory
class OrderFactory(DataclassFactory[Order]):
__random_seed__ = 42
status = "pending"
customer_email = Use(lambda: "test@example.com")
total_cents = Use(DataclassFactory.__random__.randint, 100, 10_000)
internal_note = Ignore()
tenant_id = Require()
@post_generated
@classmethod
def reference(cls, id: int) -> str:
return f"order-{id}"
```
- **Build helpers**: `build(**overrides)`, `batch(n, **overrides)`, `coverage(**overrides)` (minimal representative variant set, not a Cartesian product), `create_sync()` / `create_batch_sync(n)`, `create_async()` / `create_batch_async(n)`, `seed_random(seed)`.
- **Markers**: `Use(fn, *args, **kwargs)` re-evaluates per build; `Ignore()` delegates to model defaults; `Require()` requires a kwarg on build or raises `MissingBuildKwargException`; `PostGenerated(fn, *args, **kwargs)` or `@post_generated` (placed above `@classmethod`) derives fields from already-generated values.
- **Core options**: `__model__` (inferred from a single concrete generic argument), `__check_model__ = True`, `__random_seed__`, `__use_defaults__ = False`, `__use_examples__ = False`, `__allow_none_optionals__ = True`, `__set_as_default_factory_for_type__ = False`, `__forward_references__` / `__base_factory_overrides__` (3.5+, plus `ModelFactory.__forward_ref_resolution_type_mapping__`). `TypedDictFactory` supports `Required`, `NotRequired`, and `ReadOnly`.
See [Factories](references/factories.md) for collection bounds, persistence protocols, SQLAlchemy 3.3+ flags (`__set_primary_key__`, `__set_relationships__`, `SQLAlchemyPersistenceMethod.FLUSH`), and dynamic `create_factory()`.
### Pytest Fixtures and Relationships
```python
from polyfactory import Use
from polyfactory.factories.dataclass_factory import DataclassFactory
from polyfactory.pytest_plugin import register_fixture
@register_fixture
class CustomerFactory(DataclassFactory[Customer]):
__set_as_default_factory_for_type__ = True
@register_fixture
class OrderFactory(DataclassFactory[Order]):
customer = Use(CustomerFactory.build)
def test_order_total(order_factory: type[OrderFactory]) -> None:
order = order_factory.build()
assert order.total_cents >= 0
```
`@register_fixture` returns the class unchanged and injects a snake-cased fixture (`order_factory`) into the calling module. Setting `__set_as_default_factory_for_type__ = True` populates nested fields of that model across factories automatically.
<workflow>
## Workflow
1. **Pick the factory base** matching the model backend (table above). Do not share one factory base across mixed backends.
2. **Define one factory per model** under `tests/factories.py` or `tests/<feature>/factories.py` using one concrete generic argument (`MsgspecFactory[MyDTO]`).
3. **Customize only asserted fields** with literals or `Use(...)`; leave unasserted fields randomized.
4. **Register shared factories** with `@register_fixture` in `conftest.py` or a pytest-discovered test module; call `.build()` inline for one-offs.
5. **Wire nested relationships** via `__set_as_default_factory_for_type__ = True` or explicit `Use(ChildFactory.build)`.
6. **Pin determinism only when needed** with `__random_seed__` or `Factory.seed_random(seed)`.
</workflow>
<guardrails>
## Guardrails
- **Import from concrete submodules.** `polyfactory.factories.__all__` exports only `BaseFactory`, `DataclassFactory`, and `TypedDictFactory`; concrete submodule imports keep runtime and `mypy`/`pyright` clean.
- **Supply one concrete generic argument or explicit `__model__`.** An unparameterized concrete factory raises `ConfigurationException`.
- **Do not mutate global provider registries carelessly.** `BaseFactory.add_provider(type_, fn)` registers a process-wide provider shared across every factory subclass; prefer per-factory `get_provider_map()` overrides or clean up global state in fixtures.
- **Never pass `Faker(seed=...)`.** `Faker.__init__` ignores `seed`; use `__random_seed__`, `Factory.seed_random(seed)`, or `__faker__.seed_instance(seed)`. Do not share one seed across factories that share a Faker instance.
- **Factories belong under `tests/`.** Never import test factories from production modules or reuse them for production seeding.
- **`coverage()` is not exhaustive.** It emits a minimal representative set and reuses exhausted variants; use Hypothesis for property-based input exploration.
- **Instantiate `Ignore()` and `Require()`, and place `@post_generated` above `@classmethod`.** Passing the uninstantiated class assigns the marker object as the field value; inverting decorator order raises `TypeError`.
- **Async methods persist data.** `create_async()` / `create_batch_async()` require `__async_persistence__` or a backend session; there is no `build_async()`.
</guardrails>
<validation>
## Validation Checkpoint
- [ ] Factory base matches the model backend and is imported from its concrete submodule.
- [ ] Each factory has one concrete generic model argument or explicit `__model__` and lives under `tests/`.
- [ ] Only asserted fields are pinned; `Ignore()` / `Require()` are instantiated; `@post_generated` sits above `@classmethod`.
- [ ] `__random_seed__` is set only when assertions depend on exact generated values.
- [ ] `@register_fixture` is called in a pytest-discovered module for shared factories.
- [ ] Async persistence calls (`create_async()`) have `__async_persistence__` or `__async_session__` configured.
</validation>
<example>
## Example: Litestar Handler Test with msgspec DTOs
```python
from polyfactory.factories.msgspec_factory import MsgspecFactory
from polyfactory.pytest_plugin import register_fixture
from myapp.events import OrderCreatedEvent
@register_fixture
class OrderCreatedEventFactory(MsgspecFactory[OrderCreatedEvent]):
pass
```
```python
from __future__ import annotations
import msgspec
import pytest
from litestar.testing import AsyncTestClient
from tests.factories import OrderCreatedEventFactory
@pytest.mark.anyio
async def test_create_order_emits_event(
client: AsyncTestClient,
order_created_event_factory: type[OrderCreatedEventFactory],
) -> None:
payload = order_created_event_factory.build()
response = await client.post("/orders", json=msgspec.to_builtins(payload))
assert response.status_code == 201
assert response.json()["id"] == payload.id
```
</example>
## References Index
- **[Factories](references/factories.md)** — Per-backend bases, field customization, determinism, forward-reference overrides, `coverage()`, persistence protocols, and SQLAlchemy 3.3+ behavior.
- **[Pytest integration](references/pytest-integration.md)** — `@register_fixture`, registration from `conftest.py`, fixture scoping and naming, collection boundaries, and async persistence.
- **[Litestar patterns](references/litestar-patterns.md)** — `TestClient` / `AsyncTestClient` payloads, `coverage()` parametrization, `advanced-alchemy` model factories, SAQ payloads, and Channels events.
## Official References
- <https://github.com/litestar-org/polyfactory>
- <https://pypi.org/project/polyfactory/>
- <https://polyfactory.litestar.dev/>
## Shared Styleguide Baseline
- [General Principles](../litestar-styleguide/references/general.md)
- [Python](../litestar-styleguide/references/python.md)