Sparse oneOf Seeds: Untested Contract Branches
Your Pact or OpenAPI contract tests are green, but only because every seed you wrote happened to resolve to the same oneOf branch. The majority variant — say, a card payment — gets exercised a hundred times a run. The bank_transfer and crypto_wallet branches get exercised zero times. The contract isn't protecting you; it's giving you a false sense of coverage while minority-branch bugs ship quietly to production.
This is the sparse-seed problem in discriminated unions. It's structural, not accidental — most fixture factories default to the first or most-common variant, and nobody adds an explicit assertion that all branches were exercised. The JSON Schema oneOf keyword (and its OpenAPI 3.x equivalent) makes this especially dangerous because validators accept any single valid branch, so a test suite that never generates branch 2 or 3 still reports 100% schema compliance.
By the end of this article you'll know how to audit which branches your seeds actually hit, how to build a generator that guarantees full branch rotation, and how to gate that coverage in CI so the gap can't reopen silently.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
What "Minority Branch" Actually Means in a oneOf Schema
A oneOf schema declares a set of mutually exclusive sub-schemas, each valid in isolation. In OpenAPI 3.1 (which aligns with JSON Schema 2020-12), a discriminator property — typically a string enum — routes validators to the correct sub-schema. The contract says: exactly one of these shapes is valid for a given payload. In practice, teams write seeds that reflect real traffic distributions: 90% of payments are cards, so 90% of seeds are card-shaped. The other branches become minority branches — valid by spec, invisible in tests.
This matters architecturally because each branch often exercises a different code path in the consumer and a different serialization/deserialization path in the provider. A bank_transfer payload might carry a nullable routing_number field that the card branch never touches, meaning the null-handling logic on that field has never been tested under contract. The failure mode isn't a schema validation error — it's a runtime exception or silent data corruption that only surfaces when real traffic hits the minority path. This is closely related to how valid payloads can ghost past contract checks entirely when branch coverage is uneven.
Auditing and Enforcing Full Branch Coverage in Practice
Start with an audit. Parse your OpenAPI spec, extract every oneOf block and its discriminator values, then cross-reference against your existing seed files. The following script does that in under a minute against a real spec:
import json, pathlib, collections
spec = json.loads(pathlib.Path("openapi.json").read_text())
seeds = [json.loads(p.read_text()) for p in pathlib.Path("seeds/").glob("*.json")]
def extract_discriminator_values(schema, disc_field):
return {s["properties"][disc_field]["const"]
for s in schema.get("oneOf", [])
if "properties" in s and disc_field in s["properties"]}
payment_schema = spec["components"]["schemas"]["Payment"]
disc_field = payment_schema["discriminator"]["propertyName"]
all_branches = extract_discriminator_values(payment_schema, disc_field)
covered = {s[disc_field] for s in seeds if disc_field in s}
print("Missing branches:", all_branches - covered)
# Missing branches: {'bank_transfer', 'crypto_wallet'}
Once you know the gaps, generate a seed for every branch programmatically. Faker 24.x alone won't help here — it has no schema awareness. Use Hypothesis with its from_schema() strategy from the hypothesis-jsonschema package, or use Schemathesis which already understands oneOf discriminators and can be pointed at your spec directly:
# schemathesis run openapi.json \
# --checks all \
# --hypothesis-seed 42 \
# --hypothesis-deriving=positive \
# --validate-schema true \
# -E /payments POST
Schemathesis will generate payloads across all oneOf branches automatically. The problem is it doesn't guarantee deterministic branch rotation in a fixed seed — minority branches can still be skipped if the shrinker converges on the majority shape. For deterministic coverage, build a factory that explicitly iterates branches:
from hypothesis_jsonschema import from_schema
from hypothesis import given, settings, HealthCheck
import pytest, json, pathlib
SPEC = json.loads(pathlib.Path("openapi.json").read_text())
PAYMENT_SCHEMA = SPEC["components"]["schemas"]["Payment"]
DISC = PAYMENT_SCHEMA["discriminator"]["propertyName"]
BRANCHES = {s["properties"][DISC]["const"]: s
for s in PAYMENT_SCHEMA["oneOf"]
if "properties" in s}
@pytest.mark.parametrize("branch_schema", BRANCHES.values(),
ids=BRANCHES.keys())
@given(payload=from_schema(lambda bs: bs)) # one strategy per branch
@settings(max_examples=25, suppress_health_check=[HealthCheck.too_slow])
def test_payment_branch_roundtrip(branch_schema, payload):
resp = client.post("/payments", json=payload)
assert resp.status_code in (200, 201, 422)
Parametrizing over branches — not over a combined oneOf — guarantees each variant gets 25 examples. On a real payments service, switching from a single combined strategy to per-branch parametrization surfaced a missing iban validator on the bank_transfer branch that had been absent for four months. The fix took 20 minutes; finding it took that long only because the test had never run that branch before. For a deeper look at how discriminator-based routing compounds this gap, see the analysis of when discriminator seeds skip minority branches.
Where Senior Engineers Still Drop the Ball on Branch Seeds
The most common mistake is treating a passing Pact verification as proof of branch coverage. Pact verifies that the provider can satisfy the interactions the consumer recorded — but if the consumer never recorded a bank_transfer interaction because its own test data was sparse, the provider is never asked to prove it handles that branch. Both sides pass; neither side is tested. The fix is a consumer-side factory that enforces one interaction per discriminator value before the Pact file is published, enforced in CI with a branch-count assertion on the generated pact JSON.
A subtler mistake is relying on production traffic replay as a substitute for synthetic minority-branch seeds. Prod snapshots reflect actual distribution — which is exactly the problem. Rare but valid branches (refunds via crypto, zero-amount authorization holds) appear once in ten thousand records. Seeding from a prod snapshot without stratified sampling guarantees those branches are absent from most test runs. This is the same structural gap that causes hotspot collapse when sparse seeds starve low-frequency enum paths — the majority signal drowns out everything else.
Myths That Keep Minority Branches Invisible
Myth 1: JSON Schema validation proves branch coverage. It doesn't. A validator confirms that a given payload satisfies at least one branch; it says nothing about whether your test suite has ever produced a payload that satisfies branch 2 or 3. Schema compliance and branch coverage are orthogonal metrics. You need an explicit coverage assertion — a set comparison between known discriminator values and values observed in the test run — not just a green schema check.
Myth 2: Randomized generation solves the distribution problem. Raw randomness with Faker or random.choice() over a combined schema will, over thousands of runs, eventually hit every branch — but "eventually" isn't a CI guarantee, and Hypothesis's shrinker actively steers toward simpler (majority) shapes. Myth 3: Adding more seeds is enough. Volume without stratification is noise. Twenty card seeds and one bank-transfer seed is not coverage; it's a weighted lottery. The correct mental model is: every discriminator value is a required test class, and each class needs independent seed coverage, just as you'd treat distinct equivalence partitions in unit testing.
Sparse oneOf seeds are a structural gap, not a careless oversight — the tooling defaults push you toward majority-branch fixtures. The practical path forward: run the audit script above against your live spec, add per-branch parametrization to your contract test suite, and add a CI gate that fails if any discriminator value has zero coverage. If you're also seeing drift in optional fields across branches, the patterns around referential nullability drift in sparse seeds are worth reading next.
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.