Python: Synthetic JSON Test Data from a Form Model
A form model is already a machine-readable contract: a JSON Schema that names every field, its type, its limits and whether it is required. Yet fixture JSON is still often made by copying last week's payload and editing three values. That fixture drifts until the API adds a required field, and the suite fails with a KeyError instead of a useful assertion.
When coding agents write the tests, the drift gets faster. An agent asked for "a valid registration payload" writes one inline, from whatever it saw last in the codebase, and the next agent writes a slightly different one. A generator driven by the schema gives both people and agents a single way to get valid, varied records, and it updates the moment the schema does.
This article builds a small Python generator that walks a form model in JSON Schema, dispatches to Faker by type and format, wires related fields to shared pools, validates every record against the same schema, and writes seeded, reproducible JSON. It also covers where model-generated text belongs in such a pipeline and where it does not.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
What a form model schema gives you
A form model in JSON Schema is a typed, traversable tree. Each property has a type and may have a format, enum values, bounds and length limits; required says which fields must appear; $ref pointers compose reusable blocks such as an address or a contact method. That is everything a generator needs to produce valid records without a person in the loop.
The form model sits between the UI contract and the API contract: it is what the frontend posts and the backend validates. Generating test data from it keeps fixtures aligned with both. The general relationship is covered in JSON Schema and test data: a complete guide.
The generator: schema walk and Faker dispatch
The walker below handles local references (#/$defs/...), enums, constants, common formats, numeric and length bounds, arrays, objects, and oneOf/anyOf branches. It takes a seeded random generator and a seeded Faker instance, so the same seed always produces the same file.
import random
import uuid
from faker import Faker
class FormDataGenerator:
def __init__(self, schema: dict, seed: int, pools: dict | None = None):
self.root = schema
self.rng = random.Random(seed)
self.fake = Faker()
self.fake.seed_instance(seed)
self.pools = pools or {} # field name -> list of allowed values (shared references)
def resolve(self, node: dict) -> dict:
ref = node.get("$ref")
if ref is None:
return node
if not ref.startswith("#/"):
raise ValueError(f"only local refs are supported: {ref}")
target = self.root
for part in ref[2:].split("/"):
target = target[part]
return self.resolve(target)
def value(self, node: dict, name: str = ""):
node = self.resolve(node)
if name in self.pools:
return self.rng.choice(self.pools[name])
if "const" in node:
return node["const"]
if "enum" in node:
return self.rng.choice(node["enum"])
for key in ("oneOf", "anyOf"):
if key in node:
return self.value(self.rng.choice(node[key]), name)
kind = node.get("type", "string")
if kind == "object":
return self.obj(node)
if kind == "array":
count = self.rng.randint(node.get("minItems", 0), node.get("maxItems", 3))
return [self.value(node.get("items", {}), name) for _ in range(count)]
if kind == "integer":
return self.rng.randint(node.get("minimum", 0), node.get("maximum", 10_000))
if kind == "number":
low, high = node.get("minimum", 0), node.get("maximum", 10_000)
return round(self.rng.uniform(low, high), 2)
if kind == "boolean":
return self.rng.random() < 0.5
return self.string(node)
def string(self, node: dict) -> str:
fmt = node.get("format")
if fmt == "email":
return f"user{self.rng.randint(1, 10**6)}@example.test"
if fmt == "date":
return self.fake.date_between(start_date="-80y", end_date="-18y").isoformat()
if fmt == "uuid":
return str(uuid.UUID(int=self.rng.getrandbits(128), version=4))
low, high = node.get("minLength", 1), node.get("maxLength", 40)
text = self.fake.text(max_nb_chars=max(high, 5)).replace("\n", " ")
return text[:high].ljust(low, "x")
def obj(self, node: dict) -> dict:
required = set(node.get("required", []))
record = {}
for key, sub in node.get("properties", {}).items():
if key not in required and self.rng.random() < 0.3:
continue # exercise absent optional fields
record[key] = self.value(sub, key)
return record
A few choices are deliberate. Emails use the reserved example.test domain so no generated record can reach a real inbox. UUIDs come from the seeded generator rather than uuid.uuid4(), which would break reproducibility. Optional fields are left out about 30% of the time, because fully populated fixtures never exercise the assertion gaps when optional fields are missing. And branches of oneOf/anyOf are chosen at random, so a contact field that can be a phone or an email object gets both, rather than the first branch every time.
The walker ignores pattern, exclusive bounds and conditionals. Rather than pretending otherwise, the next step validates every record and fails loudly when the generator cannot satisfy a schema.
Shared pools for related fields
Fields that reference other entities, such as a lab_id, must come from a pool of IDs that actually exist, not independent random values. Generate or load the parent records first and pass their IDs in:
pool_rng = random.Random(7)
lab_ids = [str(uuid.UUID(int=pool_rng.getrandbits(128), version=4)) for _ in range(20)]
generator = FormDataGenerator(form_schema, seed=20261129, pools={"lab_id": lab_ids})
Sampling from a shared pool keeps references valid across a whole batch. Fields with uniqueness constraints need the opposite treatment, a counter or a consumed pool, or large batches will collide; composite key collisions in synthetic data shows how those collisions arise.
Validate against the same schema and write the file
import json
import os
from pathlib import Path
from jsonschema import Draft202012Validator
form_schema = json.loads(Path("schemas/registration_form.json").read_text())
validator = Draft202012Validator(form_schema)
seed = int(os.environ.get("TEST_DATA_SEED", "20261129"))
generator = FormDataGenerator(form_schema, seed=seed, pools={"lab_id": lab_ids})
records = [generator.value(form_schema) for _ in range(500)]
failures = [(i, e.message) for i, r in enumerate(records) for e in validator.iter_errors(r)]
if failures:
raise SystemExit(f"{len(failures)} schema errors, first: {failures[:3]}")
Path("tests/data/registration_forms.json").write_text(
json.dumps({"seed": seed, "records": records}, indent=2)
)
Validating against the schema itself, rather than a separately maintained Pydantic model, avoids a second definition that drifts. Storing the seed in the file means anyone can regenerate it and get the same bytes. If a schema change makes generation fail, the error names the record and the rule, which tells you which part of the walker to extend.
Where model-generated text and agents fit
Faker produces filler text, which is fine for most fields and poor for free-text fields whose content matters: a "reason for visit" box feeding a triage classifier, or a comments field that a summarisation feature reads. A language model writes far more realistic content for those. Use it offline: generate candidate values for the free-text fields only, validate length and character rules, review them, and commit them as a pool the generator samples from. Never call a model during test runs, and never seed the prompt with real form submissions; the risks are covered in privacy-safe synthetic data with LLMs.
For coding agents, the generator is the instruction. Add to your repository guidance: "Form payloads in tests come from tests/data/registration_forms.json or FormDataGenerator with an explicit seed. Do not write payload dictionaries inline. If the generator cannot produce a case you need, extend the generator and its tests." Agents follow a clear, single route reliably, and reviewers only need to check one place when the form changes.
The same records are useful when the system under test is itself an agent, for example one that fills in forms from user messages. The generated records become expected outputs: write the user message that should produce each record, run the agent several times per case, and score how often its submitted payload matches.
Limits to know
Valid is not meaningful. A record with status: "active" and a deleted_at date passes structural validation and breaks consumers that treat them as exclusive. Add cross-field rules in code after generation, one at a time, each with a test.
Random is not boundary coverage. The walker rarely produces exactly minLength or the maximum value. For boundary exploration, use Hypothesis with hypothesis-jsonschema; use this generator for realistic, reproducible bulk fixtures.
Start with the structural layer working against your real form schema, fix the seed in CI, validate every record, and add semantic rules as the form's behaviour demands them.
Note: This article is for informational purposes only and is not a substitute for professional advice. If you need guidance on specific situations described in this article, consider consulting a qualified professional.