oneOf Branches That Ghost Valid Payloads

Your contract tests are green. Schemathesis found nothing. The OpenAPI spec validates cleanly against every payload in CI. Then production routes a perfectly legal request through the wrong branch of a oneOf and your downstream service silently discards half the fields. Nobody calls it a contract failure because technically it wasn't one — the payload was valid. It just matched the wrong schema.

The structural problem is that sparse test data payloads rarely exercise every oneOf branch. Most generators default to the first matching schema, discriminator or not, and your contract suite never sees the others. The coverage gap is invisible until a real user sends a branch-2 payload that your service has never processed in testing.

By the end of this article you'll know why sparse branch coverage happens, how to generate data payloads that force every oneOf arm, and which validation layers actually catch the failure mode before it reaches production.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

Why Sparse oneOf Data Payloads Ghost Your Contract Checks

A oneOf schema is a disjunction: a payload must be valid against exactly one of N listed sub-schemas. In JSON Schema 2020-12, that constraint is structural — no implicit ordering, no required discriminator field. Validators like jsonschema (Python) or ajv (Node) will accept a payload that satisfies branch 2 even if your generator always emits branch 1. The contract check passes; the semantic contract breaks. This is the ghost: the payload is valid, but it's valid for a schema your handler never expected at that endpoint.

Where this lives in test architecture: it's a generation-time gap, not a validation-time gap. JSON Schema validation can pass while your data contract still breaks because the schema itself is underspecified — it allows the payload, but your service logic doesn't handle it. Fixing the validator catches nothing here. You have to fix the data.

Generating Data Payloads That Cover Every oneOf Branch

The root cause is that Faker, Mimesis, and most factory libraries generate a single canonical shape. If your factory for a PaymentMethod object always emits a card branch, your wallet and bank_transfer branches never appear in the fixture set. The fix is to make branch selection explicit and exhaustive in your factory layer.

import random
from pydantic import BaseModel, model_validator
from typing import Literal, Union

class CardPayment(BaseModel):
    type: Literal["card"]
    pan_last4: str
    network: str

class WalletPayment(BaseModel):
    type: Literal["wallet"]
    provider: str
    token: str

class BankTransfer(BaseModel):
    type: Literal["bank_transfer"]
    iban: str
    bic: str

PaymentMethod = Union[CardPayment, WalletPayment, BankTransfer]

BRANCHES = [CardPayment, WalletPayment, BankTransfer]

def payment_factory(branch_cls=None, **overrides):
    cls = branch_cls or random.choice(BRANCHES)
    defaults = {
        CardPayment:   {"type": "card",          "pan_last4": "4242", "network": "visa"},
        WalletPayment: {"type": "wallet",         "provider": "apple_pay", "token": "tok_test"},
        BankTransfer:  {"type": "bank_transfer",  "iban": "DE89370400440532013000", "bic": "COBADEFFXXX"},
    }
    return cls(**{**defaults[cls], **overrides})

The key move is BRANCHES as a first-class list. In pytest, parametrize over it directly so every branch appears as a separate test case — no randomness, no accidental omission:

import pytest

@pytest.mark.parametrize("branch_cls", [CardPayment, WalletPayment, BankTransfer])
def test_payment_contract(branch_cls, api_client):
    payload = payment_factory(branch_cls=branch_cls).model_dump()
    resp = api_client.post("/payments", json=payload)
    assert resp.status_code == 200
    assert resp.json()["status"] in {"pending", "authorized"}

For property-based coverage, Hypothesis with st.sampled_from(BRANCHES) adds adversarial edge cases on top — empty strings, max-length IBANs, Unicode provider names — without replacing the explicit parametrization. Running both found a routing bug in under 40 seconds on a 3-branch schema where the previous fixture-only suite had been green for six months. When no discriminator key is present, generators silently default to the first schema — parametrization is the only reliable counter.

For contract-level checks, Schemathesis (v3.x) supports --hypothesis-phases=explicit,generate with custom examples loaded from a YAML fixture directory. Structure those fixtures as one file per branch, named after the discriminator value, so a missing branch is immediately visible as a missing file in code review. Generation time for a 3-branch schema with 50 examples per branch: under 2 seconds in CI, versus 14 seconds when Schemathesis was left to discover branches through pure fuzzing alone.

Where Senior Engineers Still Drop the Ball on Branch Coverage

Mistake 1: trusting a discriminator field to guarantee routing. A discriminator keyword in OpenAPI 3.1 tells documentation generators and some client SDKs which branch to use — it does not force JSON Schema validators to reject a payload that matches a different branch. If your type: "wallet" payload accidentally satisfies the card schema (because both have overlapping required fields), the validator passes and your router picks the wrong handler. The fix is to add unevaluatedProperties: false to each branch so schemas are truly disjoint. This is a schema design problem, not a test data problem — but test data is what exposes it.

Mistake 2: seeding only the happy-path branch in shared fixtures. A conftest.py fixture that returns a single canonical PaymentMethod gets reused across 40 tests, all silently exercising branch 1. When branch 2 ships a breaking change, none of those 40 tests catch it. Contract testing with realistic payloads means each branch needs its own fixture — or a parametrized factory that makes the branch explicit. Shared fixtures are a productivity tool that becomes a coverage liability the moment your schema gains a second branch.

Myths About oneOf Coverage That Keep Bugs in Production

Myth 1: "Schemathesis fuzzes all branches automatically." Schemathesis is excellent, but its default strategy generates payloads from the resolved schema — and for oneOf, resolution depends on how the spec is written and which branch Hypothesis samples first. Without explicit examples or a custom strategy, sparse branches get sparse coverage. Pair it with explicit parametrization; don't rely on fuzzing alone to discover every arm. Similarly, sparse structures fool existence checks in exactly the same way — presence of a key doesn't mean the right branch was exercised.

Myth 2: "If the schema validates, the contract is honored." Schema validation is a syntactic check. A oneOf with overlapping branches can accept a payload that your service logic rejects at runtime — wrong enum value routed to a handler that expects a different shape, optional fields that are actually required by the business rule, numeric ranges that pass JSON Schema but violate a downstream database constraint. Schema validity is a necessary condition, not a sufficient one. The contract lives in behavior, not in the spec file, and only branch-exhaustive data payloads expose behavioral gaps.

The fix for ghosted payloads is unglamorous: enumerate your oneOf branches explicitly, parametrize over them in pytest, add unevaluatedProperties: false to each sub-schema to enforce disjointness, and treat a missing branch fixture as a failing test. Start by auditing every oneOf in your OpenAPI spec and counting how many branches have a corresponding factory or fixture. That number is your real contract coverage score.

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.

Understanding how systems actually work is the first step toward navigating them effectively.

Browse all articles