Skip to main content

Fauxdantic

Generate realistic fake data for Pydantic models. Fauxdantic automatically creates test data that respects your model's structure, field types, and constraints.

Installation

poetry add fauxdantic

Quick Start

from pydantic import BaseModel
from fauxdantic import faux

class User(BaseModel):
    name: str
    email: str
    age: int

# Generate a fake user instance
fake_user = faux(User)
# User(name='Jennifer Wilson', email='wilson@example.com', age=42)

Features

  • Smart field detection - Recognizes email, phone, address, and other common fields
  • Constraint-aware - Respects string lengths, number ranges, and other Pydantic constraints
  • Zero configuration - Works immediately with any Pydantic model
  • Nested models - Handles complex model hierarchies
  • Custom values - Override specific fields while generating others
  • Deterministic testing - Seedable for reproducible test data
  • Clear error messages - Helpful feedback when things go wrong

Basic Usage

Generate Model Instances

from fauxdantic import faux

fake_user = faux(User)
# Returns a User instance with generated data

Generate Dictionaries

from fauxdantic import faux_dict

fake_data = faux_dict(User)
# Returns: {'name': 'John Doe', 'email': 'doe@example.com', 'age': 28}

Override Specific Fields

fake_user = faux(User, name="Alice", age=30)
# User(name='Alice', email='generated@example.com', age=30)

Smart Field Detection

Fauxdantic recognizes field names and generates appropriate data:

class Contact(BaseModel):
    email: str          # Generates valid email addresses
    phone: str          # Generates phone numbers
    website: str        # Generates URLs
    street: str         # Generates street addresses
    city: str           # Generates city names
    state: str          # Generates state names/abbreviations
    zip_code: str       # Generates postal codes
    description: str    # Generates longer text (50+ chars)

contact = faux(Contact)
# All fields get contextually appropriate fake data

FastAPI Testing

Fauxdantic pairs well with FastAPI endpoint testing:

from fastapi.testclient import TestClient

@app.post("/users", response_model=User)
def create_user(user: User):
    return user

def test_create_user():
    # Generate realistic test data
    user_data = faux_dict(User)

    response = client.post("/users", json=user_data)
    assert response.status_code == 200
    assert response.json()["email"] == user_data["email"]

Advanced Features

Constraint Support

Fauxdantic respects Pydantic Field constraints:

from pydantic import Field

class Product(BaseModel):
    name: str = Field(min_length=5, max_length=50)
    price: float = Field(gt=0, le=1000)
    category: str = Field(max_length=20)

product = faux(Product)
# Generated data respects all constraints

Configuration

Configure generation behavior globally:

from fauxdantic import config

# Set collection size ranges
config.set_collection_size_range(2, 5)  # Lists/dicts will have 2-5 items

# Deterministic generation for tests
config.set_seed(42)

# Change faker locale
config.set_locale('ja_JP')

Unique String Generation

Generate unique identifiers with the <unique> pattern:

class Order(BaseModel):
    order_id: str = Field(max_length=20)

# Generate unique order IDs
order1 = faux(Order, order_id="ORD<unique>")
order2 = faux(Order, order_id="ORD<unique>")
# order1.order_id: "ORD1734567890_a1b2c3"
# order2.order_id: "ORD1734567891_d4e5f6"

Error Handling

Fauxdantic provides clear error messages:

# Invalid field names are caught
try:
    faux(User, invalid_field="test")
except InvalidKwargsError as e:
    print(e)
    # Invalid field(s) for User: invalid_field
    # Valid fields: name, email, age

# Unsupported types get helpful suggestions
from typing import Callable

class BadModel(BaseModel):
    callback: Callable[[int], str]

try:
    faux(BadModel)
except UnsupportedTypeError as e:
    print(e)
    # Unsupported type 'Callable' for field 'callback'
    # Suggestions: Functions/callables are not supported

Supported Types

  • Basic types: str, int, float, bool
  • Temporal: datetime, date
  • Identifiers: UUID, Pydantic UUID4
  • Collections: List[T], Dict[K,V], Set[T], Tuple
  • Optional: Optional[T], Union[T, None]
  • Enums: All enum types
  • Nested models: Other Pydantic models
  • Literals: Literal["option1", "option2"]

Examples

Nested Models

class Address(BaseModel):
    street: str
    city: str
    zip_code: str

class User(BaseModel):
    name: str
    email: str
    address: Address
    tags: List[str]

user = faux(User)
# Generates realistic data for all nested fields

Complex Collections

class Order(BaseModel):
    items: List[Dict[str, Union[str, int]]]
    metadata: Dict[str, Any]

order = faux(Order)
# Generates appropriate nested structures

Testing with Factories

def user_factory(**kwargs):
    """Factory function for consistent test users."""
    defaults = {
        "name": "Test User",
        "email": "test@example.com"
    }
    defaults.update(kwargs)
    return faux(User, **defaults)

# Use in tests
def test_user_creation():
    user = user_factory(age=25)
    assert user.age == 25
    assert "@" in user.email

Development

# Install dependencies
poetry install

# Run tests
poetry run pytest

# Run tests with coverage
poetry run pytest --cov=src/fauxdantic

# Format code
poetry run black .
poetry run isort .

# Type checking
poetry run mypy src/fauxdantic

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Metadata

Release files for fauxdantic 0.1.15

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fauxdantic 0.1.15
File Size Uploaded Provenance Actions
fauxdantic-0.1.15.tar.gz 13.1 kB Without provenance Details for fauxdantic-0.1.15.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fauxdantic 0.1.15
File Interpreter ABI Platform Actions
fauxdantic-0.1.15-py3-none-any.whl Python 3 none any Details for fauxdantic-0.1.15-py3-none-any.whl

Total release size: 29.2 kB

Release files / fauxdantic-0.1.15.tar.gz

Download URL fauxdantic-0.1.15.tar.gz
Size 13.1 kB
Tags Source
SHA-256 checksum
How to use checksums
2e3fc9e5c14537887fae649ab41af6756d902bc09f84be43025aa10d81812ed5
BLAKE2b-256 checksum
How to use checksums
af14b45396d2f6c7ce98174b8db9f30153c34b909659ebe968e8a99adcf8bd43
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.1.3 CPython/3.11.12 Darwin/24.6.0

Release files / fauxdantic-0.1.15-py3-none-any.whl

Download URL fauxdantic-0.1.15-py3-none-any.whl
Size 16.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2b7e088db8b904fd121c32c2f8b1f43dde5f63c17fc4c8e5b8c917a9061f22cf
BLAKE2b-256 checksum
How to use checksums
9b6292b7e51fdf92e8e80a578c6a52d14e5e14dbd7544a40fc458f73222eb191
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.1.3 CPython/3.11.12 Darwin/24.6.0

Security for fauxdantic 0.1.15

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page