### Install pydantic-fixturegen CLI and verify setup Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/quickstart.md Install pydantic-fixturegen package via pip, upgrade pip first, and verify the CLI entry point is accessible. Optional extras can be installed to match your technology stack (openapi, fastapi, dataset, polyfactory, seed). ```bash python -m pip install --upgrade pip pip install "pydantic-fixturegen" pfg --version ``` ```bash pip install "pydantic-fixturegen[openapi,fastapi,dataset]" ``` -------------------------------- ### Generate Examples from OpenAPI with pfg Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/quickstart.md Generates example YAML data from an OpenAPI specification. This is useful for creating mock data or test cases. ```bash pfg gen examples api.yaml --out api.examples.yaml ``` -------------------------------- ### Install and Generate Datasets/Strategies (Bash) Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/example-projects/customer-analytics/README.md This snippet demonstrates how to set up a Python virtual environment, regenerate a JSONL dataset, and refresh Hypothesis strategies for the customer analytics example. It relies on Makefiles for execution. ```bash cd docs/example-projects/customer-analytics make install # set up .venv pinned to the repo make datasets # regenerate samples/segments.jsonl make strategies # refresh samples/segments_strategies.py ``` -------------------------------- ### Serve FastAPI Application with Mock Server using pfg Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/quickstart.md Starts a mock server for a FastAPI application on a specified port. It supports deterministic settings and seeding. ```bash pfg fastapi serve app.main:app --port 8050 --seed 7 ``` -------------------------------- ### Example Generation Console Output Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-gen-examples.md Displays the command output after successful example generation. The output confirms the number of schemas processed, the seed value used for deterministic generation, and the destination path where the enriched specification was written. ```text [openapi_examples] schemas=24 seed=123 Examples written to build/openapi.with-examples.yaml ``` -------------------------------- ### Generate OpenAPI Examples with Seed Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-gen-examples.md Generates deterministic examples for all component schemas in an OpenAPI document using a fixed seed value. The command reads the input spec, processes all referenced schemas through the InstanceGenerator, and writes the enriched YAML to the specified output path with examples populated under each schema's example key. ```bash pfg gen examples openapi.yaml --out build/openapi.with-examples.yaml --seed 123 ``` -------------------------------- ### Quickstart: Generate User model, JSON, and pytest fixtures Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/README.md Demonstrates a 60-second quickstart for pydantic-fixturegen. It involves creating a Pydantic model, listing models, generating JSON samples, and emitting pytest fixtures. The process uses deterministic seeds for reproducibility. ```bash # 1) Create a minimal model file cat > models.py <<'PY' from pydantic import BaseModel, EmailStr class User(BaseModel): id: int email: EmailStr tags: list[str] PY # 2) Discover models pfg list models.py # 3) Emit JSON samples (2 records) to ./out/User.json pfg gen json models.py \ --include models.User \ --n 2 --indent 2 \ --seed 7 --freeze-seeds \ --out out/{model}.json # 4) Emit pytest fixtures with 3 deterministic cases pfg gen fixtures models.py \ --include models.User \ --cases 3 \ --seed 7 --freeze-seeds \ --out tests/fixtures/{model}_fixtures.py ``` -------------------------------- ### Visualize Heuristic Choices with Explain Flag Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/quickstart.md Visualizes the heuristic and provider choices made during deterministic output generation. Useful for debugging and understanding how fixtures are created. ```bash pfg gen explain ./models.py --tree --include models.User ``` -------------------------------- ### Check CLI Version - Bash Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/install.md Prints the installed version of pydantic-fixturegen and verifies the entry point is correctly declared in project.scripts. This command confirms the CLI is properly installed and accessible. ```bash pfg --version ``` -------------------------------- ### Export Wrapper Factories for Polyfactory with pfg Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/quickstart.md Exports wrapper factories that utilize fixturegen internally, specifically for integration with Polyfactory. This allows controlling seeds and presets through fixturegen. ```bash pfg gen polyfactory ./models.py --out tests/factories_pfg.py --seed 15 ``` -------------------------------- ### pfg Configuration Example Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/README.md Provides an example of configuring pydantic-fixturegen using a TOML file (`pyproject.toml`). Shows how to set global seed, JSON indentation, and other common settings. ```toml [tool.pydantic_fixturegen] seed = 42 [tool.pydantic_fixturegen.json] indent = 2 ``` -------------------------------- ### Import all pydantic-fixturegen API functions Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/examples.md Import core functions from pydantic_fixturegen.api to access the complete Python API for data generation. Each function returns result dataclasses containing resolved configuration, warnings, and constraint summaries. ```python from pydantic_fixturegen.api import ( generate_dataset, generate_fixtures, generate_json, persist_samples, ) from pydantic_fixturegen.core.path_template import OutputTemplate ``` -------------------------------- ### Generate FastAPI Smoke Tests with pfg Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/quickstart.md Creates smoke test files for a FastAPI application. It takes the application instance path and outputs the test file. ```bash pfg fastapi smoke app.main:app --out tests/test_fastapi_smoke.py ``` -------------------------------- ### OpenAPI Schema Example Output Format Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-gen-examples.md Shows the resulting YAML structure after example generation. The example key under a schema component contains generated deterministic values matching the schema definition, such as UUIDs for ID fields, formatted email addresses, and ISO 8601 timestamps. ```yaml example: id: 203abed2-66ea-4d1c-8a8b-7bd55cba3e41 email: avery@example.org created_at: '2025-11-08T12:00:00Z' ``` -------------------------------- ### Extended Quickstart: Generate JSON and fixtures from models Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/README.md Provides extended quickstart steps for generating JSON and pytest fixtures from Pydantic, dataclass, or TypedDict models. It covers listing models, generating JSON with specified output paths and sample counts, and creating fixtures with a defined number of cases. ```bash # 1. Create a small model file (Pydantic v2, `@dataclass`, or `TypedDict`). # 2. List models: `pfg list ./models.py` # 3. Generate JSON: `pfg gen json ./models.py --include models.User --n 2 --indent 2 --out ./out/User` # 4. Generate fixtures: `pfg gen fixtures ./models.py --out tests/fixtures/test_user.py --cases 3` ``` -------------------------------- ### Install pydantic-fixturegen Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/README.md Installs the pydantic-fixturegen package using pip. Optional extras can be installed with a separate command. This is the primary method for setting up the tool in a project. ```bash pip install pydantic-fixturegen # Extras: orjson, regex, hypothesis, watch pip install 'pydantic-fixturegen[all]' ``` -------------------------------- ### AST-only Discovery Example Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-list.md Demonstrates how to use `pfg list` with the `--ast` flag to perform pure-AST discovery. This method avoids executing any imports, making it suitable for models with optional dependencies. The example filters discovered models using an include glob pattern. ```bash pfg list ./app/models.py --ast --include app.schemas.* ``` -------------------------------- ### Example Polyfactory Factory Output Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-gen-polyfactory.md This is a sample of the generated Python code when using `pfg gen polyfactory`. It demonstrates a `UserFactory` class inheriting from `ModelFactory` and using `_GENERATOR.generate_one` to build instances, delegating the actual generation logic to fixturegen. ```python class UserFactory(ModelFactory[models.User]): @classmethod def build(cls, **kwargs): return _GENERATOR.generate_one(models.User, overrides=kwargs) ``` -------------------------------- ### Hybrid Discovery with Guardrails Example Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-list.md Illustrates using `pfg list` with the `--hybrid` flag for a combination of AST and safe-import discovery. This example tightens resource constraints by setting a lower timeout and memory limit, suitable for CI environments. It also uses `--public-only` to filter for models intended for external use. ```bash pfg list ./app/models.py --hybrid --timeout 2 --memory-limit-mb 128 --public-only ``` -------------------------------- ### Live Fixture Regeneration with Watch Flag Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/quickstart.md Enables live regeneration of fixtures as code changes. The `--watch` flag activates this feature, while `--watch-debounce` controls the delay before regeneration occurs. ```bash pfg gen --watch --watch-debounce 0.5 ./models.py ``` -------------------------------- ### Diff and Snapshot Fixture Generation with pfg Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/quickstart.md Generates fixtures and diffs them against existing files. It can output JSON, Python fixtures, schemas, and manage snapshots for deterministic reviews. Supports seeding and freezing seeds for reproducible results. ```bash pfg diff ./models.py \ --json-out artifacts/users.json \ --fixtures-out tests/fixtures/test_users.py \ --schema-out schema \ --show-diff \ --seed 42 \ --freeze-seeds pfg snapshot verify ./models.py \ --json-out artifacts/users.json \ --fixtures-out tests/fixtures/test_users.py \ --seed 42 pfg snapshot write ./models.py \ --json-out artifacts/users.json \ --fixtures-out tests/fixtures/test_users.py \ --seed 42 ``` -------------------------------- ### YAML Configuration Example for pydantic-fixturegen Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/configuration.md This is an example of a pydantic-fixturegen YAML configuration file, typically generated with `pfg init --yaml`. The structure mirrors the TOML configuration and allows for setting presets, seeds, JSON formatting options (indentation, orjson usage), and emitter configurations (e.g., pytest style and scope). This file can be placed in the project root or specified via the `--yaml-path` argument. ```yaml preset: boundary seed: 42 json: indent: 2 orjson: false emitters: pytest: style: factory scope: module ``` -------------------------------- ### YAML-only setup with pfg init in a monorepo Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-init.md This workflow demonstrates initializing pydantic-fixturegen with only a YAML configuration file and a custom fixtures directory, omitting `pyproject.toml` edits. It's useful for monorepos or projects with alternative configuration management. ```bash pfg init services/payments --no-pyproject --yaml --yaml-path config/pfg.yaml --fixtures-dir tests/pfg ``` -------------------------------- ### Generate JSON Fixtures with Model Inclusion and Seed Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/quickstart.md Generates JSON fixtures for specified models from a Python file. It includes specific models and uses a seed for deterministic generation. ```bash pfg gen json ./models.py --include models.User --seed 15 ``` -------------------------------- ### Lock and Verify Fixture Manifests with pfg Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/quickstart.md Captures a coverage manifest using 'pfg lock' and enforces it in CI using 'pfg verify'. This ensures consistency and prevents regressions by comparing against a locked state. ```bash pfg lock ./models.py --lockfile .pfg-lock.json pfg verify ./models.py --lockfile .pfg-lock.json ``` -------------------------------- ### Mock Server Startup Log Output Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-fastapi-serve.md Example console output from the `pfg fastapi serve` command showing the fastapi_mock_start event log with host and port metadata, followed by Uvicorn startup information indicating successful server initialization. ```text [fastapi_mock_start] host=0.0.0.0 port=8050 seed=7 INFO: Started server process [93845] INFO: Waiting for application startup. INFO: Application startup complete. ``` -------------------------------- ### Generate JSON for selected routes with OpenAPI Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-gen-openapi.md Filters OpenAPI schemas to generate JSON payloads only for schemas referenced by specific routes (e.g., 'GET /users', 'POST /orders'). This example uses a profile for privacy-safe data and custom output templating with a timestamp. ```bash pfg gen openapi openapi.yaml \ --route "GET /users" --route "POST /orders" \ --out artifacts/{model}/{timestamp}.json --profile pii-safe ``` -------------------------------- ### Example Generated Pytest Smoke Test (Python) Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-fastapi-smoke.md This is an excerpt from a generated pytest module, demonstrating a smoke test for a 'GET /users' route. It uses a `smoke_client` to make a request, asserts a 200 status code, and validates the JSON response against the expected payload generated by fixturegen. ```python def test_get_users_returns_200(smoke_client): payload = generate_payload("GET /users") response = smoke_client.get("/users", params=payload.query, headers=payload.headers) assert response.status_code == 200 assert response.json() == payload.expected ``` -------------------------------- ### Git Diff of Generated Examples Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-gen-examples.md Demonstrates how generated examples appear in version control. The diff shows the replacement of null or missing example values with populated deterministic data including UUIDs, numeric values, and enum statuses. ```diff components: schemas: Order: type: object - example: null + example: + id: 8df5c2fa-98e1-4a34-a842-6a6b04fc91ed + total_cents: 1999 + status: CAPTURED ``` -------------------------------- ### Update OpenAPI Spec In-Place with Examples Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-gen-examples.md Regenerates and overwrites examples directly in the source OpenAPI file using a specific seed. This approach is useful for CI automation workflows where the spec is version-controlled in git, allowing tracking of example changes through git diffs. ```bash pfg gen examples openapi.json --out openapi.json --seed 202 ``` -------------------------------- ### Discover and validate Pydantic models with pfg list Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/quickstart.md Use the pfg list command to inspect model discovery in a Python module and confirm that specific models are found. Optionally initialize a config file to persist CLI defaults like seed, presets, and emitters. ```bash pfg list models.py --include models.User ``` ```bash pfg init --seed 42 --json-indent 2 ``` -------------------------------- ### Sample plugin scaffold output Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-plugin.md Shows the typical output structure created by the `pfg plugin` command, displaying file creation messages and the hierarchical organization of generated files including configuration, source code, and tests. ```text [plugin_scaffold] target=acme-pfg-colorizer files=9 created pyproject.toml created src/acme/plugins/acme_colorizer/__init__.py created tests/test_plugin.py ``` -------------------------------- ### Debug Strategies with Explain Trees Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/cookbook.md Exposes provider choices for debugging constraint handling using explain trees. The `--tree` option prints an indented diagram of providers and presets. `--json` provides a machine-readable payload for targeted checks with tools like `jq`. ```bash pfg gen explain ./models.py --tree --max-depth 2 --include app.models.User ``` ```bash pfg gen explain ./models.py --json | jq '.models["app.models.User"].fields.nickname' ``` -------------------------------- ### Output JSON Example after Anonymization Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-anonymize.md An example of a JSON output after `pfg anonymize` has processed the input. The sensitive 'email' field has been replaced with a SHA256 hash, while other fields like 'account.id' remain the same or are replaced based on rules. A new field 'name' has been added using a faker strategy. ```json {"email":"sha256:3e6c...","account":{"id":"acct-001"},"name":"Perry Evans"} ``` -------------------------------- ### Migrate Polyfactory Factories to Fixturegen Configuration Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-polyfactory-migrate.md This command-line usage example demonstrates how to run the `pfg polyfactory migrate` command to convert Polyfactory overrides into pydantic-fixturegen configuration. It specifies the target Pydantic models module, includes specific models, points to the factory module, and designates an output file for the generated overrides. ```bash pfg polyfactory migrate ./app/models.py \ --include app.models.User \ --factory-module app.factories \ --overrides-out overrides-polyfactory.toml ``` -------------------------------- ### JSON Output and CI Gating Example for pfg coverage Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-coverage.md Illustrates how to use `pfg coverage` to generate a JSON report, suitable for CI pipelines, and to fail the build if specific risks like overrides are detected. The `--format json` flag enables JSON output, `--fail-on overrides` sets the gating condition, and `--out coverage.json` directs the output to a file. The example shows an abridged JSON payload. ```bash pfg coverage ./app/models.py --format json --fail-on overrides --out coverage.json ``` -------------------------------- ### Basic pfg CLI Commands Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/README.md Lists essential pydantic-fixturegen CLI commands for discovering models, generating JSON, fixtures, schemas, and auditing code coverage. Includes flags for customization and reproducibility. ```bash pfg list pfg gen json [--n --jsonl --indent --out] pfg gen fixtures [--style --scope --cases --out] pfg gen schema --out pfg doctor ``` -------------------------------- ### Initialize Project Configuration with pfg init Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/cli.md Scaffolds configuration files and optional fixture directories for a new project. It can create `pyproject.toml` and YAML configuration files, with options to control seeding, union/enum policies, JSON indentation, and pytest style/scope. It also adds `.gitkeep` to fixture directories by default. ```bash pfg init \ --pyproject-path pyproject.toml \ --yaml \ --yaml-path config/pydantic-fixturegen.yaml \ --seed 42 \ --union-policy weighted \ --enum-policy random \ --json-indent 2 \ --pytest-style functions \ --pytest-scope module ``` -------------------------------- ### Generate JSON from Schema with pfg Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/quickstart.md Generates JSON data based on a provided JSON schema file. The output files are named according to the '{model}' placeholder. ```bash pfg gen json --schema contracts/user.schema.json --out artifacts/{model}.json ``` -------------------------------- ### Start Local-Only Mock Server with Billing Service Override Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-fastapi-serve.md Launches a mock server on localhost with a dependency override that replaces the billing client with a fake implementation. This prevents outbound calls to real services during testing or local development. ```bash pfg fastapi serve app.main:app \ --host 127.0.0.1 --port 9000 \ --dependency-override "app.services.billing:get_client=fakes.billing_client" ``` -------------------------------- ### Minimal pyproject scaffold with pfg init Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/commands/pfg-init.md This command scaffolds pydantic-fixturegen configuration into `pyproject.toml` and creates a `.gitkeep` file in the default fixtures directory (`tests/fixtures`). It sets specific values for seed, locale, union policy, enum policy, and pytest emitter style/scope. ```bash pfg init . \ --seed 42 --locale en_US \ --union-policy weighted --enum-policy random \ --pytest-style functions --pytest-scope module ``` -------------------------------- ### Example pyproject.toml Configuration for Pydantic Fixturegen Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/configuration.md This TOML snippet demonstrates how to configure pydantic-fixturegen within a pyproject.toml file. It covers global settings like seed and locale, JSON output specific settings, and emitter settings for pytest. ```toml [tool.pydantic_fixturegen] seed = 42 locale = "en_US" union_policy = "weighted" enum_policy = "random" [tool.pydantic_fixturegen.json] indent = 2 orjson = false [tool.pydantic_fixturegen.emitters.pytest] style = "functions" scope = "module" ``` -------------------------------- ### Seed SQLModel database with deterministic test data Source: https://github.com/casperkristiansson/pydantic-fixturegen/blob/main/docs/quickstart.md Populate a SQLModel database with deterministic generated data using pfg gen seed sqlmodel. Supports schema creation, table truncation, and transaction rollback. Honors determinism knobs like seed, preset, and validator respect. ```bash pfg gen seed sqlmodel ./models.py \ --database sqlite:///seed.db \ --include models.User \ --n 25 \ --create-schema \ --truncate \ --rollback ```