polyfactory
Installation
SKILL.md
polyfactory
Polyfactory is a typed mock-data factory library: declare ModelFactory[T] (or DataclassFactory, MsgspecFactory, AttrsFactory, TypedDictFactory) and .build() returns a fully-populated, validation-passing instance of T. Because the factory inspects the model's annotations and constraints, generated data already respects msgspec.Meta ranges, Pydantic Field constraints, and attrs validators — no additional fixtures needed for happy-path tests.
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]. from __future__ import annotationsrule — Modules that define factory subclasses with introspectedMetaconfig (__model__,__random_seed__,__set_as_default_factory_for_type__) are library-like and SHOULD avoid future annotations on the factory module itself if the model class is also defined there. Test modules that use factories (call.build(), register fixtures) MAY and typically SHOULD use future annotations — they are pure consumer code. The same rule applies as msgspec/dishka/SAQ.- 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. The wrong base silently degrades to attribute-by-attribute introspection and produces lower-quality data. - Prefer
register_fixtureover hand-rolled@pytest.fixturewrappers — it gives you both the fixture and the factory class with one decorator.