litestar-org/litestar-skills/polyfactory
Claude Code and agent skill by litestar-org/litestar-skills
- community
Checking that the SKILL.md file is still in the repository.
Use when working with polyfactory, ModelFactory, DataclassFactory, MsgspecFactory, AttrsFactory, Use, register_fixture, pytest plugin, __random_seed__, or coverage(). Not for production seeding.
Install
npx vskill@latest install litestar-org/litestar-skills/polyfactorySKILL.md
polyfactory
Polyfactory is a typed mock-data factory library: declare ModelFactory[T] (or DataclassFactory, MsgspecFactory, AttrsFactory, TypedDictFactory) 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 is the canonical way to feed TestClient.post(...) / AsyncTestClient.put(...) payloads. The companion skill litestar:litestar-testing covers the request side.
Code Style Rules
- PEP 604 unions:
T | None, neverOptional[T]. - One factory per model. Don't reuse a factory across unrelated models — clarity beats DRY when the test fails at 3am.
- Pick the right factory base by backend:
ModelFactory(Pydantic),DataclassFactory,MsgspecFactory,AttrsFactory,TypedDictFactory. A mismatched base raisesConfigurationException. - Prefer
register_fixtureover hand-rolled@pytest.fixturewrappers. Call it in a pytest-discovered test module orconftest.pyso the injected fixture is collected.
Quick Reference
Picking the right factory base
| 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__ only exports BaseFactory, DataclassFactory, and TypedDictFactory. Always import backend-specific factories (ModelFactory, MsgspecFactory, AttrsFactory, SQLAlchemyFactory, BeanieDocumentFactory, OdmanticModelFactory) from their concrete submodules (polyfactory.factories.pydantic_factory, polyfactory.factories.msgspec_factory, polyfactory.factories.sqlalchemy_factory, etc.), register_fixture from polyfactory.pytest_plugin, and post_generated from polyfactory.decorators so runtime imports and mypy/pyright checks succeed.
Defining a factory
The single concrete generic argument lets Polyfactory infer __model__. build() returns one instance, batch(n) returns list[T], coverage() yields the smallest set of instances that covers the model's supported variants, create_sync() / create_batch_sync(n) and create_async() / create_batch_async(n) build and persist instances, seed_random(seed) re-seeds the factory PRNG and Faker instance, and add_provider(type_, fn) registers a custom type generator.
Customizing fields
Use(callable, *args, **kwargs) is re-invoked on every build(), so each generated instance gets a fresh value. Ignore() and Require() must be instantiated; omitting a Require() field at build time raises MissingBuildKwargException.
For standalone post-generation callbacks, use PostGenerated(fn, *args, **kwargs) where fn has signature (field_name, generated_values, *args, **kwargs):
Determinism and configuration
Set __random_seed__ (or call Factory.seed_random(seed) / __faker__.seed_instance(seed) on a custom __faker__ = Faker(locale="en_US")) when test assertions depend on the exact generated values. Never pass Faker(seed=...) — Faker.__init__ ignores a seed keyword argument without seeding.
Core BaseFactory configuration attributes:
__model__: target model class (inferred from a single concrete generic argument when omitted).__check_model__ = True: validates thatUse,PostGenerated,Ignore, andRequireattribute names exist on__model__.__random_seed__: integer seed passed tocls.seed_random(...)during class creation.__use_defaults__ = False: whenTrue, prefers model field defaults /default_factoryover generated values.__allow_none_optionals__ = True: whenTrue, optional fields (T | None) randomly produceNone; setFalseto always populateT.__set_as_default_factory_for_type__ = False: whenTrue, registers the factory globally for nested fields of type__model__.__faker__and__random__: the factory'sFakerandrandom.Randominstances.
Default factory registration
When __set_as_default_factory_for_type__ = True, polyfactory uses that factory whenever the type appears as a field on another model — no manual nesting required.
Pytest fixture from a factory
@register_fixture returns the class unchanged and injects a pytest fixture into the caller's module. The fixture name is the snake-cased class name and its value is the factory class.
Cross-model relationships
__set_as_default_factory_for_type__ = True lets Polyfactory populate nested Customer fields with CustomerFactory. Use Use(CustomerFactory.build) when one parent factory needs an explicit local override.
<workflow>
Workflow
Step 1: Pick the factory base
Match the base to your model backend (table above). A mismatched base fails during factory class creation. If your project uses multiple backends (e.g., Pydantic for HTTP DTOs + msgspec for internal events), import each base separately and don't try to share a factory across backends.
Step 2: Define one factory per model
Subclass the appropriate base with one concrete generic argument and let Polyfactory infer __model__. Set __model__ explicitly only when the generic declaration cannot identify exactly one model. Keep factories in tests/factories.py or tests/<feature>/factories.py, outside production code paths.
Step 3: Customize only what the test cares about
If a field can take any valid value, leave it for the factory to randomize. Override (literal value or Use(...)) only fields the assertion depends on. Tests that pin every field defeat the purpose of using a factory.
Step 4: Register as a pytest fixture (if used widely)
For factories used in many tests, decorate with @register_fixture in a pytest-discovered module and consume the snake-cased fixture name. For one-off use, call Factory.build() directly inline.
Step 5: Wire cross-model relationships
Set __set_as_default_factory_for_type__ = True on a base factory and let nested fields be populated automatically, or use Use(OtherFactory.build) for a local relationship override.
Step 6: Pin determinism only when needed
Tests that assert on specific generated values need __random_seed__ (or Factory.seed_random(seed) per test). Tests that assert on shape or invariants (e.g., total >= 0) should not — leaving randomization on widens coverage across runs.
</workflow>
<guardrails>
Guardrails
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 90 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/polyfactory/SKILL.md
Popularity
- 7-day trend score
- 0
Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/litestar-org/litestar-skills/polyfactory)