Skip to content

Generate

Generator functionality.

This module provides flexible value generators for use in Pact contracts. Generators allow you to specify dynamic values for contract testing, ensuring that your tests remain robust and non-deterministic where appropriate. These generators are typically used in conjunction with matchers to produce example data for consumer-driven contract tests.

Generators are essential for producing dynamic values in contract tests, such as random integers, dates, UUIDs, and more. This helps ensure that your contracts are resilient to changes and do not rely on hardcoded values, which can lead to brittle tests.

Warning

Do not import functions directly from pact.generate to avoid shadowing Python built-in types. Instead, import the generate module and use its functions as generate.int, generate.str, etc.

# Recommended
from pact import generate

generate.int(...)

# Not recommended
from pact.generate import int

int(...)

Many functions in this module are named after the type they generate (e.g., int, str, bool). Importing directly from this module may shadow Python built-in types, so always use the generate module.

Generators are typically used in conjunction with matchers, which allow Pact to validate values during contract tests. If a value is not provided within a matcher, a generator will produce a random value that conforms to the specified constraints.

Basic Types

Generate random values for basic types:

from pact import generate

random_bool = generate.bool()
random_int = generate.int(min=0, max=100)
random_float = generate.float(precision=2)
random_str = generate.str(size=12)

Dates, Times, and UUIDs

Produce values in specific formats:

random_date = generate.date(format="%Y-%m-%d")
random_time = generate.time(format="%H:%M:%S")
random_datetime = generate.datetime(format="%Y-%m-%dT%H:%M:%S%z")
random_uuid = generate.uuid(format="lowercase")

Regex and Hexadecimal

Generate values matching a pattern or hexadecimal format:

random_code = generate.regex(r"[A-Z]{3}-\d{4}")
random_hex = generate.hex(digits=8)

Provider State and Mock Server URLs

For advanced contract scenarios:

provider_value = generate.provider_state(expression="user_id")
mock_url = generate.mock_server_url(regex=r"http://localhost:\d+")

For more details and advanced usage, see the documentation for each function below.

Classes

AbstractGenerator

Bases: ABC

Abstract generator.

In Pact, a generator is used by Pact to generate data on-the-fly during the contract verification process. Generators are used in combination with matchers to provide more flexible matching of data.

This class is abstract and should not be used directly. Instead, use one of the concrete generator classes. Alternatively, you can create your own generator by subclassing this class

The matcher provides methods to convert into an integration JSON object and a matching rule. These methods are used internally by the Pact library when communicating with the FFI and generating the Pact file.

Functions

to_generator_json() -> dict[str, Any] abstractmethod

Convert the generator to a generator JSON object.

This method is used internally to convert the generator to a JSON object which can be embedded directly in a number of places in the Pact FFI.

For more information about this format, refer to the Pact specification and the matchers section

RETURNS DESCRIPTION
dict[str, Any]

The generator as a generator JSON object.

Source code in src/pact/generate/generator.py
@abstractmethod
def to_generator_json(self) -> dict[str, Any]:
    """
    Convert the generator to a generator JSON object.

    This method is used internally to convert the generator to a JSON object
    which can be embedded directly in a number of places in the Pact FFI.

    For more information about this format, refer to the [Pact
    specification](https://github.com/pact-foundation/pact-specification/tree/version-4)
    and the [matchers
    section](https://github.com/pact-foundation/pact-specification/tree/version-2?tab=readme-ov-file#matchers)

    Returns:
        The generator as a generator JSON object.
    """
to_integration_json() -> dict[str, Any] abstractmethod

Convert the generator to an integration JSON object.

See AbstractGenerator.to_integration_json for more information.

Source code in src/pact/generate/generator.py
@abstractmethod
def to_integration_json(self) -> dict[str, Any]:
    """
    Convert the generator to an integration JSON object.

    See
    [`AbstractGenerator.to_integration_json`][pact.generate.generator.AbstractGenerator.to_integration_json]
    for more information.
    """

Functions

bool() -> AbstractGenerator

Generate a random boolean value.

RETURNS DESCRIPTION
AbstractGenerator

Generator producing random boolean values.

Source code in src/pact/generate/__init__.py
def bool() -> AbstractGenerator:
    """
    Generate a random boolean value.

    Returns:
        Generator producing random boolean values.
    """
    return GenericGenerator("RandomBoolean")

boolean() -> AbstractGenerator

Alias for generate.bool.

RETURNS DESCRIPTION
AbstractGenerator

Generator producing random boolean values.

Source code in src/pact/generate/__init__.py
def boolean() -> AbstractGenerator:
    """
    Alias for [`generate.bool`][pact.generate.bool].

    Returns:
        Generator producing random boolean values.
    """
    return bool()

date(format: builtins.str = '%Y-%m-%d', *, disable_conversion: builtins.bool = False) -> AbstractGenerator

Generate a date value.

Uses Python's strftime format, converted to Java SimpleDateFormat for Pact compatibility.

PARAMETER DESCRIPTION
format

Expected format of the date. Defaults to ISO 8601: %Y-%m-%d.

TYPE: str DEFAULT: '%Y-%m-%d'

disable_conversion

If True, disables conversion from Python's format to Java's format. The value must then be a Java format string.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
AbstractGenerator

Generator producing dates in the specified format.

Source code in src/pact/generate/__init__.py
def date(
    format: builtins.str = "%Y-%m-%d",
    *,
    disable_conversion: builtins.bool = False,
) -> AbstractGenerator:
    """
    Generate a date value.

    Uses Python's
    [strftime](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)
    format, converted to [Java
    `SimpleDateFormat`](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)
    for Pact compatibility.

    Args:
        format:
            Expected format of the date. Defaults to ISO 8601: `%Y-%m-%d`.

        disable_conversion:
            If True, disables conversion from Python's format to Java's format.
            The value must then be a Java format string.

    Returns:
        Generator producing dates in the specified format.
    """
    if not disable_conversion:
        format = strftime_to_simple_date_format(format or "%Y-%m-%d")
    return GenericGenerator("Date", {"format": format or "%yyyy-MM-dd"})

datetime(format: builtins.str, *, disable_conversion: builtins.bool = False) -> AbstractGenerator

Generate a datetime value.

Uses Python's strftime format, converted to Java SimpleDateFormat for Pact compatibility.

PARAMETER DESCRIPTION
format

Expected format of the timestamp. Defaults to ISO 8601: %Y-%m-%dT%H:%M:%S%z.

TYPE: str

disable_conversion

If True, disables conversion from Python's format to Java's format. The value must then be a Java format string.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
AbstractGenerator

Generator producing datetimes in the specified format.

Source code in src/pact/generate/__init__.py
def datetime(
    format: builtins.str,
    *,
    disable_conversion: builtins.bool = False,
) -> AbstractGenerator:
    """
    Generate a datetime value.

    Uses Python's
    [strftime](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)
    format, converted to [Java
    `SimpleDateFormat`](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)
    for Pact compatibility.

    Args:
        format:
            Expected format of the timestamp. Defaults to ISO 8601:
            `%Y-%m-%dT%H:%M:%S%z`.

        disable_conversion:
            If True, disables conversion from Python's format to Java's format.
            The value must then be a Java format string.

    Returns:
        Generator producing datetimes in the specified format.
    """
    if not disable_conversion:
        format = strftime_to_simple_date_format(format or "%Y-%m-%dT%H:%M:%S%z")
    return GenericGenerator("DateTime", {"format": format or "yyyy-MM-dd'T'HH:mm:ssZ"})

decimal(precision: builtins.int | None = None) -> AbstractGenerator

Alias for generate.float.

PARAMETER DESCRIPTION
precision

Number of digits to generate.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
AbstractGenerator

Generator producing random decimal values.

Source code in src/pact/generate/__init__.py
def decimal(precision: builtins.int | None = None) -> AbstractGenerator:
    """
    Alias for [`generate.float`][pact.generate.float].

    Args:
        precision:
            Number of digits to generate.

    Returns:
        Generator producing random decimal values.
    """
    return float(precision=precision)

float(precision: builtins.int | None = None) -> AbstractGenerator

Generate a random decimal number.

Precision refers to the total number of digits (excluding leading zeros), not decimal places. For example, precision of 3 may yield 0.123 or 12.3.

PARAMETER DESCRIPTION
precision

Number of digits to generate.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
AbstractGenerator

Generator producing random decimal values.

Source code in src/pact/generate/__init__.py
def float(precision: builtins.int | None = None) -> AbstractGenerator:
    """
    Generate a random decimal number.

    Precision refers to the total number of digits (excluding leading zeros),
    not decimal places. For example, precision of 3 may yield `0.123` or `12.3`.

    Args:
        precision:
            Number of digits to generate.

    Returns:
        Generator producing random decimal values.
    """
    params: dict[builtins.str, builtins.int] = {}
    if precision is not None:
        params["digits"] = precision
    return GenericGenerator("RandomDecimal", extra_fields=params)

hex(digits: builtins.int | None = None) -> AbstractGenerator

Generate a random hexadecimal value.

PARAMETER DESCRIPTION
digits

Number of digits to generate.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
AbstractGenerator

Generator producing random hexadecimal values.

Source code in src/pact/generate/__init__.py
def hex(digits: builtins.int | None = None) -> AbstractGenerator:
    """
    Generate a random hexadecimal value.

    Args:
        digits:
            Number of digits to generate.

    Returns:
        Generator producing random hexadecimal values.
    """
    params: dict[builtins.str, builtins.int] = {}
    if digits is not None:
        params["digits"] = digits
    return GenericGenerator("RandomHexadecimal", extra_fields=params)

hexadecimal(digits: builtins.int | None = None) -> AbstractGenerator

Alias for generate.hex.

PARAMETER DESCRIPTION
digits

Number of digits to generate.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
AbstractGenerator

Generator producing random hexadecimal values.

Source code in src/pact/generate/__init__.py
def hexadecimal(digits: builtins.int | None = None) -> AbstractGenerator:
    """
    Alias for [`generate.hex`][pact.generate.hex].

    Args:
        digits:
            Number of digits to generate.

    Returns:
        Generator producing random hexadecimal values.
    """
    return hex(digits=digits)

int(*, min: builtins.int | None = None, max: builtins.int | None = None) -> AbstractGenerator

Generate a random integer.

PARAMETER DESCRIPTION
min

Minimum value for the integer.

TYPE: int | None DEFAULT: None

max

Maximum value for the integer.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
AbstractGenerator

Generator producing random integers.

Source code in src/pact/generate/__init__.py
def int(
    *,
    min: builtins.int | None = None,
    max: builtins.int | None = None,
) -> AbstractGenerator:
    """
    Generate a random integer.

    Args:
        min:
            Minimum value for the integer.

        max:
            Maximum value for the integer.

    Returns:
        Generator producing random integers.
    """
    params: dict[builtins.str, builtins.int] = {}
    if min is not None:
        params["min"] = min
    if max is not None:
        params["max"] = max
    return GenericGenerator("RandomInt", extra_fields=params)

integer(*, min: builtins.int | None = None, max: builtins.int | None = None) -> AbstractGenerator

Alias for generate.int.

PARAMETER DESCRIPTION
min

Minimum value for the integer.

TYPE: int | None DEFAULT: None

max

Maximum value for the integer.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
AbstractGenerator

Generator producing random integers.

Source code in src/pact/generate/__init__.py
def integer(
    *,
    min: builtins.int | None = None,
    max: builtins.int | None = None,
) -> AbstractGenerator:
    """
    Alias for [`generate.int`][pact.generate.int].

    Args:
        min:
            Minimum value for the integer.

        max:
            Maximum value for the integer.

    Returns:
        Generator producing random integers.
    """
    return int(min=min, max=max)

mock_server_url(regex: builtins.str | None = None, example: builtins.str | None = None) -> AbstractGenerator

Generate a mock server URL.

PARAMETER DESCRIPTION
regex

Regex pattern to match.

TYPE: str | None DEFAULT: None

example

Example URL to use.

TYPE: str | None DEFAULT: None

RETURNS DESCRIPTION
AbstractGenerator

Generator producing mock server URLs.

Source code in src/pact/generate/__init__.py
def mock_server_url(
    regex: builtins.str | None = None,
    example: builtins.str | None = None,
) -> AbstractGenerator:
    """
    Generate a mock server URL.

    Args:
        regex:
            Regex pattern to match.

        example:
            Example URL to use.

    Returns:
        Generator producing mock server URLs.
    """
    params: dict[builtins.str, builtins.str] = {}
    if regex is not None:
        params["regex"] = regex
    if example is not None:
        params["example"] = example
    return GenericGenerator("MockServerURL", extra_fields=params)

provider_state(expression: builtins.str | None = None) -> AbstractGenerator

Generate a value from provider state context.

PARAMETER DESCRIPTION
expression

Expression to look up provider state.

TYPE: str | None DEFAULT: None

RETURNS DESCRIPTION
AbstractGenerator

Generator producing values from provider state context.

Source code in src/pact/generate/__init__.py
def provider_state(expression: builtins.str | None = None) -> AbstractGenerator:
    """
    Generate a value from provider state context.

    Args:
        expression:
            Expression to look up provider state.

    Returns:
        Generator producing values from provider state context.
    """
    params: dict[builtins.str, builtins.str] = {}
    if expression is not None:
        params["expression"] = expression
    return GenericGenerator("ProviderState", extra_fields=params)

regex(regex: builtins.str) -> AbstractGenerator

Generate a string matching a regex pattern.

PARAMETER DESCRIPTION
regex

Regex pattern to match.

TYPE: str

RETURNS DESCRIPTION
AbstractGenerator

Generator producing strings matching the pattern.

Source code in src/pact/generate/__init__.py
def regex(regex: builtins.str) -> AbstractGenerator:
    """
    Generate a string matching a regex pattern.

    Args:
        regex:
            Regex pattern to match.

    Returns:
        Generator producing strings matching the pattern.
    """
    return GenericGenerator("Regex", {"regex": regex})

str(size: builtins.int | None = None) -> AbstractGenerator

Generate a random string.

PARAMETER DESCRIPTION
size

Size of the string to generate.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
AbstractGenerator

Generator producing random strings.

Source code in src/pact/generate/__init__.py
def str(size: builtins.int | None = None) -> AbstractGenerator:
    """
    Generate a random string.

    Args:
        size:
            Size of the string to generate.

    Returns:
        Generator producing random strings.
    """
    params: dict[builtins.str, builtins.int] = {}
    if size is not None:
        params["size"] = size
    return GenericGenerator("RandomString", extra_fields=params)

string(size: builtins.int | None = None) -> AbstractGenerator

Alias for generate.str.

PARAMETER DESCRIPTION
size

Size of the string to generate.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
AbstractGenerator

Generator producing random strings.

Source code in src/pact/generate/__init__.py
def string(size: builtins.int | None = None) -> AbstractGenerator:
    """
    Alias for [`generate.str`][pact.generate.str].

    Args:
        size:
            Size of the string to generate.

    Returns:
        Generator producing random strings.
    """
    return str(size=size)

time(format: builtins.str = '%H:%M:%S', *, disable_conversion: builtins.bool = False) -> AbstractGenerator

Generate a time value.

Uses Python's strftime format, converted to Java SimpleDateFormat

PARAMETER DESCRIPTION
format

Expected format of the time. Defaults to ISO 8601: %H:%M:%S.

TYPE: str DEFAULT: '%H:%M:%S'

disable_conversion

If True, disables conversion from Python's format to Java's format. The value must then be a Java format string.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
AbstractGenerator

Generator producing times in the specified format.

Source code in src/pact/generate/__init__.py
def time(
    format: builtins.str = "%H:%M:%S",
    *,
    disable_conversion: builtins.bool = False,
) -> AbstractGenerator:
    """
    Generate a time value.

    Uses Python's
    [strftime](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)
    format, converted to [Java
    `SimpleDateFormat`](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)

    Args:
        format:
            Expected format of the time. Defaults to ISO 8601: `%H:%M:%S`.

        disable_conversion:
            If True, disables conversion from Python's format to Java's format.
            The value must then be a Java format string.

    Returns:
        Generator producing times in the specified format.
    """
    if not disable_conversion:
        format = strftime_to_simple_date_format(format or "%H:%M:%S")
    return GenericGenerator("Time", {"format": format or "HH:mm:ss"})

timestamp(format: builtins.str, *, disable_conversion: builtins.bool = False) -> AbstractGenerator

Alias for generate.datetime.

RETURNS DESCRIPTION
AbstractGenerator

Generator producing datetimes in the specified format.

Source code in src/pact/generate/__init__.py
def timestamp(
    format: builtins.str,
    *,
    disable_conversion: builtins.bool = False,
) -> AbstractGenerator:
    """
    Alias for [`generate.datetime`][pact.generate.datetime].

    Returns:
        Generator producing datetimes in the specified format.
    """
    return datetime(format=format, disable_conversion=disable_conversion)

uuid(format: _UUID_FORMAT_NAMES = 'lowercase') -> AbstractGenerator

Generate a UUID.

PARAMETER DESCRIPTION
format

Format of the UUID to generate. Only supported under the V4 specification.

TYPE: _UUID_FORMAT_NAMES DEFAULT: 'lowercase'

RETURNS DESCRIPTION
AbstractGenerator

Generator producing UUIDs in the specified format.

Source code in src/pact/generate/__init__.py
def uuid(
    format: _UUID_FORMAT_NAMES = "lowercase",
) -> AbstractGenerator:
    """
    Generate a UUID.

    Args:
        format:
            Format of the UUID to generate. Only supported under the V4 specification.

    Returns:
        Generator producing UUIDs in the specified format.
    """
    return GenericGenerator("Uuid", {"format": format})