Skip to main content

A library for generating fake Pydantic models for testing and development purposes

Project description

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fauxdantic-0.1.15.tar.gz (13.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fauxdantic-0.1.15-py3-none-any.whl (16.0 kB view details)

Uploaded Python 3

File details

Details for the file fauxdantic-0.1.15.tar.gz.

File metadata

  • Download URL: fauxdantic-0.1.15.tar.gz
  • Upload date:
  • Size: 13.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.11.12 Darwin/24.6.0

File hashes

Hashes for fauxdantic-0.1.15.tar.gz
Algorithm Hash digest
SHA256 2e3fc9e5c14537887fae649ab41af6756d902bc09f84be43025aa10d81812ed5
MD5 31ce8302656e61866addaa6b1c233f7c
BLAKE2b-256 af14b45396d2f6c7ce98174b8db9f30153c34b909659ebe968e8a99adcf8bd43

See more details on using hashes here.

File details

Details for the file fauxdantic-0.1.15-py3-none-any.whl.

File metadata

  • Download URL: fauxdantic-0.1.15-py3-none-any.whl
  • Upload date:
  • Size: 16.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.11.12 Darwin/24.6.0

File hashes

Hashes for fauxdantic-0.1.15-py3-none-any.whl
Algorithm Hash digest
SHA256 2b7e088db8b904fd121c32c2f8b1f43dde5f63c17fc4c8e5b8c917a9061f22cf
MD5 7384ddda20bb90360d75666d23be919b
BLAKE2b-256 9b6292b7e51fdf92e8e80a578c6a52d14e5e14dbd7544a40fc458f73222eb191

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page