Skip to content

Contract Gate

Category: Gate Pattern

Overview

A contract gate asserts that a stand-in matches the thing it stands in for. Test doubles drift from the real collaborator silently: a parameter is added to the real client and not to the double, or an asynchronous method becomes synchronous in the substitute. Both cases leave the suite green while every test runs against an interface the production code no longer has.

Concepts

Signature Correspondence

The parameter names and order of a substitute method compared against the real one. Comparing names rather than counts catches reordering and renaming, which are the changes that pass a count check and break callers.

Asynchrony as Part of the Contract

Whether a method is a coroutine function is part of its signature. A double that quietly becomes synchronous satisfies every assertion about return values and matches nothing the runtime does.

Eliminating the Substitute

The stronger form of the pattern. Where hand-written doubles set derived attributes directly, tests assert against a value shape the real system never produces. Returning genuine value objects makes that class of drift impossible rather than merely detectable, which is better than any gate.

Usage Guidelines

Use when:

  • A test double, stub, or fake stands in for a real collaborator
  • Two implementations must remain interface-compatible across versions
  • A protocol or interface has implementations maintained separately from it

Avoid when:

  • The substitute can be removed entirely in favour of the real value type
  • The double intentionally implements a narrower interface, documented as such
  • The real object is itself unstable and the double encodes a deliberate target shape

Implementation

import inspect
from collections.abc import Sequence


def signature_mismatches(
    real: type,
    substitute: type,
    covered: Sequence[str],
) -> list[str]:
    """Differences between a substitute's methods and the real ones."""
    problems = []
    for name in covered:
        real_method = getattr(real, name, None)
        fake_method = getattr(substitute, name, None)
        if real_method is None:
            problems.append(
                f"{name}: absent from {real.__name__}. Remove it from the "
                f"covered set or restore it."
            )
            continue
        if fake_method is None:
            problems.append(
                f"{name}: {substitute.__name__} does not implement it; "
                f"add it or narrow the covered set."
            )
            continue

        real_params = list(inspect.signature(real_method).parameters)
        fake_params = list(inspect.signature(fake_method).parameters)
        if real_params != fake_params:
            problems.append(
                f"{name}: {substitute.__name__} takes {fake_params}, "
                f"{real.__name__} takes {real_params}."
            )

        real_async = inspect.iscoroutinefunction(real_method)
        fake_async = inspect.iscoroutinefunction(fake_method)
        if real_async != fake_async:
            expected = "asynchronous" if real_async else "synchronous"
            problems.append(
                f"{name}: {real.__name__} is {expected} and "
                f"{substitute.__name__} is not."
            )
    return problems


class ContractGate:
    """Fails when a substitute has drifted from the real collaborator."""

    def __init__(self, real: type, substitute: type, covered: Sequence[str]) -> None:
        self._real = real
        self._substitute = substitute
        self._covered = list(covered)

    def violations(self) -> list[str]:
        """Messages for every method that does not correspond."""
        return signature_mismatches(self._real, self._substitute, self._covered)

    def check(self) -> None:
        """Raise AssertionError describing every drifted method."""
        violations = self.violations()
        if violations:
            raise AssertionError("\n".join(violations))

Usage

COVERED = ("get", "create")

gate = ContractGate(RealClient, FakeClient, COVERED)
gate.check()  # raises when a parameter list or asynchrony diverges

Parametrising over the covered methods gives one failure per drifted method rather than one aggregate failure:

@pytest.mark.parametrize("name", COVERED)
def test_the_signature_matches_the_real_client(name):
    """A double whose signature drifts passes every test and matches nothing."""
    assert not signature_mismatches(RealClient, FakeClient, [name])

Trade-offs

Benefits:

  1. Catches drift at the point of change rather than in production
  2. Covers asynchrony, which return-value assertions cannot detect
  3. Names the specific method and the specific difference

Drawbacks:

  1. Verifies shape, not behaviour: a matching signature can still do the wrong thing
  2. Needs an explicit covered set, which can fall behind the real interface
  3. Encourages keeping a double that would be better deleted

Real-World Examples

  • Fake API clients checked against the real client class in a test suite
  • Protocol conformance tests comparing implementations against a reference
  • Mock frameworks offering signature-checked autospec doubles

API Reference

design_patterns.gates.contract

Contract Gate: assert that a substitute matches what it substitutes for.

Test doubles drift from the real collaborator silently. A parameter is added to the real client and not to the double, or an asynchronous method becomes synchronous in the substitute. Both leave the suite green while every test runs against an interface the production code no longer has.

The module also carries the example classes the documentation refers to: a real client, a double that still corresponds to it, and a double that drifted in the two ways this gate detects.

ContractGate

Fails when a substitute has drifted from the real collaborator.

Example
ContractGate(RealClient, FaithfulDouble, ("get", "create")).check()
Source code in src/design_patterns/gates/contract.py
class ContractGate:
    """Fails when a substitute has drifted from the real collaborator.

    Example:
        ```python
        ContractGate(RealClient, FaithfulDouble, ("get", "create")).check()
        ```
    """

    def __init__(self, real: type, substitute: type, covered: Sequence[str]) -> None:
        """Pair a substitute with the class it stands in for.

        Args:
            real: The class being stood in for.
            substitute: The stand-in to check.
            covered: Method names the substitute claims to provide.
        """
        self._real = real
        self._substitute = substitute
        self._covered = list(covered)

    def violations(self) -> list[str]:
        """Find every method that no longer corresponds.

        Returns:
            list[str]: One message per divergent method.
        """
        return signature_mismatches(self._real, self._substitute, self._covered)

    def check(self) -> None:
        """Assert that every covered method still corresponds.

        Raises:
            AssertionError: If any covered method diverges. The message
                describes each divergence separately.
        """
        violations = self.violations()
        if violations:
            report = "\n".join(violations)
            raise AssertionError(report)

__init__(real, substitute, covered)

Pair a substitute with the class it stands in for.

Parameters:

Name Type Description Default
real type

The class being stood in for.

required
substitute type

The stand-in to check.

required
covered Sequence[str]

Method names the substitute claims to provide.

required
Source code in src/design_patterns/gates/contract.py
def __init__(self, real: type, substitute: type, covered: Sequence[str]) -> None:
    """Pair a substitute with the class it stands in for.

    Args:
        real: The class being stood in for.
        substitute: The stand-in to check.
        covered: Method names the substitute claims to provide.
    """
    self._real = real
    self._substitute = substitute
    self._covered = list(covered)

check()

Assert that every covered method still corresponds.

Raises:

Type Description
AssertionError

If any covered method diverges. The message describes each divergence separately.

Source code in src/design_patterns/gates/contract.py
def check(self) -> None:
    """Assert that every covered method still corresponds.

    Raises:
        AssertionError: If any covered method diverges. The message
            describes each divergence separately.
    """
    violations = self.violations()
    if violations:
        report = "\n".join(violations)
        raise AssertionError(report)

violations()

Find every method that no longer corresponds.

Returns:

Type Description
list[str]

list[str]: One message per divergent method.

Source code in src/design_patterns/gates/contract.py
def violations(self) -> list[str]:
    """Find every method that no longer corresponds.

    Returns:
        list[str]: One message per divergent method.
    """
    return signature_mismatches(self._real, self._substitute, self._covered)

DriftedDouble

A stand-in that drifted in the two ways this gate detects.

get stopped being a coroutine function and create renamed its second parameter. Both changes keep every existing assertion passing.

Source code in src/design_patterns/gates/contract.py
class DriftedDouble:
    """A stand-in that drifted in the two ways this gate detects.

    ``get`` stopped being a coroutine function and ``create`` renamed its second
    parameter. Both changes keep every existing assertion passing.
    """

    def get(self, resource: str, identifier: int) -> dict[str, Any]:
        """Return a canned record synchronously, unlike the real client.

        Args:
            resource: Collection name.
            identifier: Record identifier.

        Returns:
            dict[str, Any]: A record built without a network call.
        """
        return {"resource": resource, "id": identifier}

    async def create(self, resource: str, body: dict[str, Any]) -> dict[str, Any]:
        """Record a creation, naming its payload parameter differently.

        Args:
            resource: Collection name.
            body: Field values for the new record.

        Returns:
            dict[str, Any]: The record that would have been created.
        """
        return {"resource": resource, **body}

create(resource, body) async

Record a creation, naming its payload parameter differently.

Parameters:

Name Type Description Default
resource str

Collection name.

required
body dict[str, Any]

Field values for the new record.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The record that would have been created.

Source code in src/design_patterns/gates/contract.py
async def create(self, resource: str, body: dict[str, Any]) -> dict[str, Any]:
    """Record a creation, naming its payload parameter differently.

    Args:
        resource: Collection name.
        body: Field values for the new record.

    Returns:
        dict[str, Any]: The record that would have been created.
    """
    return {"resource": resource, **body}

get(resource, identifier)

Return a canned record synchronously, unlike the real client.

Parameters:

Name Type Description Default
resource str

Collection name.

required
identifier int

Record identifier.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: A record built without a network call.

Source code in src/design_patterns/gates/contract.py
def get(self, resource: str, identifier: int) -> dict[str, Any]:
    """Return a canned record synchronously, unlike the real client.

    Args:
        resource: Collection name.
        identifier: Record identifier.

    Returns:
        dict[str, Any]: A record built without a network call.
    """
    return {"resource": resource, "id": identifier}

FaithfulDouble

A stand-in whose signatures still correspond to RealClient.

Source code in src/design_patterns/gates/contract.py
class FaithfulDouble:
    """A stand-in whose signatures still correspond to RealClient."""

    async def get(self, resource: str, identifier: int) -> dict[str, Any]:
        """Return a canned record.

        Args:
            resource: Collection name.
            identifier: Record identifier.

        Returns:
            dict[str, Any]: A record built without a network call.
        """
        return {"resource": resource, "id": identifier}

    async def create(self, resource: str, payload: dict[str, Any]) -> dict[str, Any]:
        """Record a creation without performing one.

        Args:
            resource: Collection name.
            payload: Field values for the new record.

        Returns:
            dict[str, Any]: The record that would have been created.
        """
        return {"resource": resource, **payload}

create(resource, payload) async

Record a creation without performing one.

Parameters:

Name Type Description Default
resource str

Collection name.

required
payload dict[str, Any]

Field values for the new record.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The record that would have been created.

Source code in src/design_patterns/gates/contract.py
async def create(self, resource: str, payload: dict[str, Any]) -> dict[str, Any]:
    """Record a creation without performing one.

    Args:
        resource: Collection name.
        payload: Field values for the new record.

    Returns:
        dict[str, Any]: The record that would have been created.
    """
    return {"resource": resource, **payload}

get(resource, identifier) async

Return a canned record.

Parameters:

Name Type Description Default
resource str

Collection name.

required
identifier int

Record identifier.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: A record built without a network call.

Source code in src/design_patterns/gates/contract.py
async def get(self, resource: str, identifier: int) -> dict[str, Any]:
    """Return a canned record.

    Args:
        resource: Collection name.
        identifier: Record identifier.

    Returns:
        dict[str, Any]: A record built without a network call.
    """
    return {"resource": resource, "id": identifier}

RealClient

The collaborator a test double stands in for.

Source code in src/design_patterns/gates/contract.py
class RealClient:
    """The collaborator a test double stands in for."""

    async def get(self, resource: str, identifier: int) -> dict[str, Any]:
        """Fetch one record.

        Args:
            resource: Collection name.
            identifier: Record identifier.

        Returns:
            dict[str, Any]: The stored record.
        """
        return {"resource": resource, "id": identifier}

    async def create(self, resource: str, payload: dict[str, Any]) -> dict[str, Any]:
        """Create one record.

        Args:
            resource: Collection name.
            payload: Field values for the new record.

        Returns:
            dict[str, Any]: The created record.
        """
        return {"resource": resource, **payload}

create(resource, payload) async

Create one record.

Parameters:

Name Type Description Default
resource str

Collection name.

required
payload dict[str, Any]

Field values for the new record.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The created record.

Source code in src/design_patterns/gates/contract.py
async def create(self, resource: str, payload: dict[str, Any]) -> dict[str, Any]:
    """Create one record.

    Args:
        resource: Collection name.
        payload: Field values for the new record.

    Returns:
        dict[str, Any]: The created record.
    """
    return {"resource": resource, **payload}

get(resource, identifier) async

Fetch one record.

Parameters:

Name Type Description Default
resource str

Collection name.

required
identifier int

Record identifier.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The stored record.

Source code in src/design_patterns/gates/contract.py
async def get(self, resource: str, identifier: int) -> dict[str, Any]:
    """Fetch one record.

    Args:
        resource: Collection name.
        identifier: Record identifier.

    Returns:
        dict[str, Any]: The stored record.
    """
    return {"resource": resource, "id": identifier}

signature_mismatches(real, substitute, covered)

Compare a substitute's methods against the real ones.

Parameter names are compared rather than counts, because reordering and renaming pass a count check and break callers. Whether a method is a coroutine function is treated as part of its signature.

Parameters:

Name Type Description Default
real type

The class being stood in for.

required
substitute type

The stand-in to check.

required
covered Sequence[str]

Method names the substitute claims to provide.

required

Returns:

Type Description
list[str]

list[str]: One message per difference found, naming the method and the specific divergence.

Source code in src/design_patterns/gates/contract.py
def signature_mismatches(
    real: type,
    substitute: type,
    covered: Sequence[str],
) -> list[str]:
    """Compare a substitute's methods against the real ones.

    Parameter names are compared rather than counts, because reordering and
    renaming pass a count check and break callers. Whether a method is a
    coroutine function is treated as part of its signature.

    Args:
        real: The class being stood in for.
        substitute: The stand-in to check.
        covered: Method names the substitute claims to provide.

    Returns:
        list[str]: One message per difference found, naming the method and
            the specific divergence.
    """
    problems = []
    for name in covered:
        real_method = getattr(real, name, None)
        fake_method = getattr(substitute, name, None)

        if real_method is None:
            problems.append(
                f"{name}: absent from {real.__name__}. Remove it from the "
                f"covered set or restore it."
            )
            continue
        if fake_method is None:
            problems.append(
                f"{name}: {substitute.__name__} does not implement it; add it "
                f"or narrow the covered set."
            )
            continue

        real_params = list(inspect.signature(real_method).parameters)
        fake_params = list(inspect.signature(fake_method).parameters)
        if real_params != fake_params:
            problems.append(
                f"{name}: {substitute.__name__} takes {fake_params}, "
                f"{real.__name__} takes {real_params}."
            )

        real_async = inspect.iscoroutinefunction(real_method)
        if real_async != inspect.iscoroutinefunction(fake_method):
            expected = "asynchronous" if real_async else "synchronous"
            problems.append(
                f"{name}: {real.__name__} is {expected} and "
                f"{substitute.__name__} is not."
            )
    return problems