Declarative test data generation for Python
Project description
conformly
Declarative test data generator for Python. Turns data models (now only dataclasses) and type constraints into valid fixtures and negative test cases.
conformly allows you to define your data schema once using standard Python dataclasses and Annotated constraints, and instantly generate rigorous test data. It replaces verbose factory patterns with a smart, schema-aware generator that supports both happy-path and edge-case testing.
Instead of writing separate factory classes or hardcoding test dictionaries, Conformly:
- Interprets constraints defined at the type level as an executable schema (length bounds, regex patterns, numeric ranges)
- Generates valid data strictly adhering to all constraints for happy-path testing
- Generates invalid data intelligently violating constraints for negative testing and fuzzing
- Bridges static typing and dynamic testing — your schema is the single source of truth
Key Features
-
Typed Constraints as First-Class Objects
Constraints in Conformly are explicit, typed entities bound to base Python types. They are interpreted as part of the schema and drive both valid and invalid data generation, rather than being treated as passive metadata. -
Schema-Driven Generation
Your dataclass and its type annotations form a complete, executable data schema. Test data is derived directly from this schema — no factories, no duplicated validation logic, no hardcoded dictionaries. -
Systematic Negative Testing
Invalid data is generated by intentionally violating constraints of a single, explicitly targeted field, while keeping the rest of the object valid. This produces minimal, meaningful negative cases suitable for API and validation tests. -
Guaranteed Happy-Path
Valid generation strictly satisfies all declared constraints. Generated data is internally consistent and suitable for end-to-end tests, database seeding, and contract testing. -
Multiple Constraint Definition Styles
Constraints can be defined using:- Annotated[T, Constraint(...)] (typed, reusable, recommended)
- Annotated[T, "k=v"] shorthand (compact and convenient)
- field(metadata={...}) for compatibility and gradual adoption
-
Zero Boilerplate, Pure Python
Works directly with standard dataclasses and typing.Annotated. No custom DSLs, no runtime code generation, no magic metaclasses. Lightweight, dependency-minimal, and fully type-checkable with mypy.
Install
pip install conformly
# or with uv
uv add conformly
Quickstart
Define a model:
from dataclasses import dataclass, field
from typing import Annotated, Optional
from conformly import case, cases
from conformly.constraints import MinLength, Pattern, GreaterOrEqual, LessOrEqual
Username = Annotated[
str,
MinLength(3),
MaxLength(32),
]
Age = Annotated[
int,
GreaterOrEqual(18),
LessOrEqual(120),
]
@dataclass
class User:
username: Username
email: Annotated[str, Pattern(r"^[^\s@]+@[^\s@]+\.[^\s@]+$")]
age: Age
bio: Optional[Annotated[str, MaxLength(160)]] = None
Generate valid data:
user = case(User, valid=True)
# -> {"username": "Abc", "email": "x@y.z", "age": 42, "bio": None}
Generate an invalid case for a specific field:
bad_user = case(User, valid=False, strategy="age")
# bad_user["age"] is outside 18..120 (either < 18 or > 120)
# All other field remain valid
Generate many cases:
items = cases(User, valid=True, count=10)
Use Cases
case(Model, ...) # single generated object
cases(Model, ...) # list of generated objects
strategy values:
<field_name>- target specific field for invalidation"random"- choose a random field/constraint to violate"all"- (forcases) produce all minimal invalid variations for the model"first"-violate the first constrained field (forcase) or take the first N constrained fields (forcases)
API Testing
# Valid payloads for happy-path tests
for _ in range(100):
payload = case(CreateUserRequest, valid=True)
response = client.post("/users", json=payload)
assert response.status_code == 201
# Invalid payloads for error handling tests
invalid = case(CreateUserRequest, valid=False, strategy="age")
response = client.post("/users", json=invalid)
assert response.status_code == 400
# As option create all possible invalid cases for payload in one only line
invalid_payloads = cases(CreateUserRequest, valid=False, strategy="all")
for payload in invalid_payloads:
response = client.post("/users", json=payload)
assert response.status_code == 400
Database Seeding
# Generate realistic test data respecting schema constraints
products = cases(Product, valid=True, count=1000)
db.insert_many("products", products)
Fuzzing & Property-Based Testing
Conformly is not a replacement of Hypothesis, but a complementary tool for schema-driven testing and negative case generation.
# Generate random invalid data to stress-test validation
for _ in range(500):
invalid = case(Model, valid=False, strategy="random")
assert validate(invalid) is False # Should always reject
Supported Constraints
String
MinLength(value: int)— minimum string lengthMaxLength(value: int)— maximum string lengthPattern(regex: str)— regex pattern (must match)
Integer / Float Bounds
GreaterThan(value: float | int)— strictly greater thanGreaterOrEqual(value: float | int)— greater than or equalLessThan(value: float | int)— strictly less thanLessOrEqual(value: float | int)— less than or equal
Boolean
- Basic boolean generation (no extra constraints)
Shorthand -> Constraint class mapping
"gt"->GreaterThan"ge"->GreaterOrEqual"lt"->LessThan"le"->LessOrEqual"min_length"->MinLength"max_length"->MaxLength"pattern"->Pattern
Defining Constraints
1) Annotated[..., Constraint(...)] (type-safe, recommended)
from typing import Annotated
from conformly.constraints import MinLength, GreaterOrEqual
username: Annotated[str, MinLength(3)]
age: Annotated[int, GreaterOrEqual(18)]
2) Annotated[..., "k=v"] (shorthand string syntax)
title: Annotated[str, "min_length=5", "max_length=200"]
views: Annotated[int, "ge=0"]
rating: Annotated[float, "ge=0", "le=5"]
3) field(metadata={...})
from dataclasses import field
sku: str = field(metadata={"pattern": r"^[A-Z0-9]{8}$"})
stock: int = field(metadata={"ge": 0})
price: float = field(metadata={"gt": 0})
All syntaxes are fully compatible - mix and match as needed.
Invalid Generation Contract (Important)
For case(Model, valid=False, strategy="<field>"):
- Exactly one field is targeted (the one specified by
strategy). - The generator will violate constraints for that field, making it invalid.
- If a field has multiple constraints, the violated constraint may be chosen by generator logic (not necessarily the one you expect).
- For numeric bounds, invalid values may violate the lower or upper bound (e.g.,
age > 120orage < 18). - For float bounds, invalid generation may produce
infwhen violating the upper boundary.
If you need deterministic control over which exact constraint to violate, that is not implemented in 0.0.1 (see Roadmap).
Optional Fields and Defaults
- If a field is optional (
Optional[T]), valid generation may produceNone. - If a field has a default value, valid generation returns the default.
- Invalid generation requires at least one constraint on the targeted field (raises
ValueErrorotherwise).
Development
Install dependencies:
uv sync
Run tests:
uv run -m pytest -q
Run with coverage:
uv run -m pytest --cov=conformly --cov-report=term-missing
Build & check package:
uv build
uv run -m twine check dist/*
Roadmap
- Nested data models
- Deterministic invalid generation - explicitly select which constraint to violate
- Better regex invalidation - guarantee that invalid strings don't match patterns
- More adapters - pydantic, TypedDict, attrs support
- More constraints and types -
multitiple_of,Literal,list[T],dict[T]etc. - Custom generators - allow per-field generator overrides
Changelog
See CHANGELOG.md for release notes and migration guidance.
License
MIT — see LICENSE file for details
Contributing
Contributions welcome! Please:
- Fork the repo
- Create a feature branch
- Add tests for new functionality
- Run
uv run -m pytestanduv run -m ruff check . - Submit a pull request
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file conformly-0.2.0.tar.gz.
File metadata
- Download URL: conformly-0.2.0.tar.gz
- Upload date:
- Size: 18.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.2.0 CPython/3.14.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d7900c6358d4006bc98950113f04e4a3c3cb3dc88e579ec171ffe9ae0bfed50f
|
|
| MD5 |
02cd20023ab32ca535da86330b66e20c
|
|
| BLAKE2b-256 |
92b33080e814c1d8d25d74e3d993a33862ed6e4ade94f8d5ec7ad173cbace9e6
|
File details
Details for the file conformly-0.2.0-py3-none-any.whl.
File metadata
- Download URL: conformly-0.2.0-py3-none-any.whl
- Upload date:
- Size: 20.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.2.0 CPython/3.14.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
74e769b81b48390d19a0d1fdbc10797e974cf3ff6770a3d013b16d8c518de3d8
|
|
| MD5 |
a80b02489c60a6b81e91a5f499ba46fc
|
|
| BLAKE2b-256 |
eb7276c39b2576a204906408ee294830a4baa1ce32ca86980a0fcd7818e90ceb
|