Skip to content

Generate

Generator module.

Classes

Generator

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, see the docs:

https://github.com/pact-foundation/pact-specification/tree/version-4

and

https://github.com/pact-foundation/pact-specification/tree/version-2?tab=readme-ov-file#matchers

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, see the docs:

    > https://github.com/pact-foundation/pact-specification/tree/version-4

    and

    > 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 matcher to an integration JSON object.

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

For more information about this format, see the docs:

https://docs.pact.io/implementation_guides/rust/pact_ffi/integrationjson

RETURNS DESCRIPTION
dict[str, Any]

The matcher as an integration JSON object.

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

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

    For more information about this format, see the docs:

    > https://docs.pact.io/implementation_guides/rust/pact_ffi/integrationjson

    Returns:
        The matcher as an integration JSON object.
    """

Functions

bool() -> Generator

Create a random boolean generator.

RETURNS DESCRIPTION
Generator

A generator that produces random boolean values.

Source code in src/pact/generate/__init__.py
def bool() -> Generator:
    """
    Create a random boolean generator.

    Returns:
        A generator that produces random boolean values.
    """
    return GenericGenerator("RandomBoolean")

boolean() -> Generator

Alias for generate.bool.

RETURNS DESCRIPTION
Generator

A generator that produces random boolean values.

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

    Returns:
        A generator that produces random boolean values.
    """
    return bool()

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

Create a date generator.

Info

Pact internally uses the Java's SimpleDateFormat. To ensure compatibility with the rest of the Python ecosystem, this function accepts Python's strftime format and performs the conversion to Java's format internally.

PARAMETER DESCRIPTION
format

Expected format of the date.

If not provided, an ISO 8601 date format is used: %Y-%m-%d.

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

disable_conversion

If True, the conversion from Python's strftime format to Java's SimpleDateFormat format will be disabled, and the format must be in Java's SimpleDateFormat format. As a result, the value must be a string as Python cannot format the date in the target format.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Generator

A generator that produces 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,
) -> Generator:
    """
    Create a date generator.

    !!! info

        Pact internally uses the Java's
        [`SimpleDateFormat`](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html).
        To ensure compatibility with the rest of the Python ecosystem, this
        function accepts Python's [`strftime`](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)
        format and performs the conversion to Java's format internally.

    Args:
        format:
            Expected format of the date.

            If not provided, an ISO 8601 date format is used: `%Y-%m-%d`.

        disable_conversion:
            If True, the conversion from Python's `strftime` format to Java's
            `SimpleDateFormat` format will be disabled, and the format must
            be in Java's `SimpleDateFormat` format. As a result, the value must
            be a string as Python cannot format the date in the target format.

    Returns:
        A generator that produces 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) -> Generator

Create a datetime generator.

Info

Pact internally uses the Java's SimpleDateFormat. To ensure compatibility with the rest of the Python ecosystem, this function accepts Python's strftime format and performs the conversion to Java's format internally.

PARAMETER DESCRIPTION
format

Expected format of the timestamp.

If not provided, an ISO 8601 timestamp format will be used: %Y-%m-%dT%H:%M:%S%z.

TYPE: str

disable_conversion

If True, the conversion from Python's strftime format to Java's SimpleDateFormat format will be disabled, and the format must be in Java's SimpleDateFormat format. As a result, the value must be

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Generator

A generator that produces datetimes in the specified format.

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

    !!! info

        Pact internally uses the Java's
        [`SimpleDateFormat`](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html).
        To ensure compatibility with the rest of the Python ecosystem, this
        function accepts Python's
        [`strftime`](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)
        format and performs the conversion to Java's format internally.

    Args:
        format:
            Expected format of the timestamp.

            If not provided, an ISO 8601 timestamp format will be used:
            `%Y-%m-%dT%H:%M:%S%z`.

        disable_conversion:
            If True, the conversion from Python's `strftime` format to Java's
            `SimpleDateFormat` format will be disabled, and the format must be
            in Java's `SimpleDateFormat` format. As a result, the value must be

    Returns:
        A generator that produces 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) -> Generator

Alias for generate.float.

PARAMETER DESCRIPTION
precision

The number of digits to generate.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
Generator

A generator that produces random decimal values.

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

    Args:
        precision:
            The number of digits to generate.

    Returns:
        A generator that produces random decimal values.
    """
    return float(precision=precision)

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

Create a random decimal generator.

Note that the precision is the number of digits to generate in total, not the number of decimal places. Therefore a precision of 3 will generate numbers like 0.123 and 12.3.

PARAMETER DESCRIPTION
precision

The number of digits to generate.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
Generator

A generator that produces random decimal values.

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

    Note that the precision is the number of digits to generate _in total_, not
    the number of decimal places. Therefore a precision of `3` will generate
    numbers like `0.123` and `12.3`.

    Args:
        precision:
            The number of digits to generate.

    Returns:
        A generator that produces 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) -> Generator

Create a random hexadecimal generator.

PARAMETER DESCRIPTION
digits

The number of digits to generate.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
Generator

A generator that produces random hexadecimal values.

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

    Args:
        digits:
            The number of digits to generate.

    Returns:
        A generator that produces 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) -> Generator

Alias for generate.hex.

PARAMETER DESCRIPTION
digits

The number of digits to generate.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
Generator

A generator that produces random hexadecimal values.

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

    Args:
        digits:
            The number of digits to generate.

    Returns:
        A generator that produces random hexadecimal values.
    """
    return hex(digits=digits)

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

Create a random integer generator.

PARAMETER DESCRIPTION
min

The minimum value for the integer.

TYPE: int | None DEFAULT: None

max

The maximum value for the integer.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
Generator

A generator that produces random integers.

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

    Args:
        min:
            The minimum value for the integer.

        max:
            The maximum value for the integer.

    Returns:
        A generator that produces 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) -> Generator

Alias for generate.int.

PARAMETER DESCRIPTION
min

The minimum value for the integer.

TYPE: int | None DEFAULT: None

max

The maximum value for the integer.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
Generator

A generator that produces random integers.

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

    Args:
        min:
            The minimum value for the integer.

        max:
            The maximum value for the integer.

    Returns:
        A generator that produces random integers.
    """
    return int(min=min, max=max)

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

Create a mock server URL generator.

Generates a URL with the mock server as the base URL.

PARAMETER DESCRIPTION
regex

The regex pattern to match.

TYPE: str | None DEFAULT: None

example

An example URL to use.

TYPE: str | None DEFAULT: None

RETURNS DESCRIPTION
Generator

A generator that produces 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,
) -> Generator:
    """
    Create a mock server URL generator.

    Generates a URL with the mock server as the base URL.

    Args:
        regex:
            The regex pattern to match.

        example:
            An example URL to use.

    Returns:
        A generator that produces 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) -> Generator

Create a provider state generator.

Generates a value that is looked up from the provider state context using the given expression.

PARAMETER DESCRIPTION
expression

The expression to use to look up the provider state.

TYPE: str | None DEFAULT: None

RETURNS DESCRIPTION
Generator

A generator that produces values from the provider state context.

Source code in src/pact/generate/__init__.py
def provider_state(expression: builtins.str | None = None) -> Generator:
    """
    Create a provider state generator.

    Generates a value that is looked up from the provider state context
    using the given expression.

    Args:
        expression:
            The expression to use to look up the provider state.

    Returns:
        A generator that produces values from the 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) -> Generator

Create a regex generator.

The generator will generate a string that matches the given regex pattern.

PARAMETER DESCRIPTION
regex

The regex pattern to match.

TYPE: str

RETURNS DESCRIPTION
Generator

A generator that produces strings matching the given regex pattern.

Source code in src/pact/generate/__init__.py
def regex(regex: builtins.str) -> Generator:
    """
    Create a regex generator.

    The generator will generate a string that matches the given regex pattern.

    Args:
        regex:
            The regex pattern to match.

    Returns:
        A generator that produces strings matching the given regex pattern.
    """
    return GenericGenerator("Regex", {"regex": regex})

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

Create a random string generator.

PARAMETER DESCRIPTION
size

The size of the string to generate.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
Generator

A generator that produces random strings.

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

    Args:
        size:
            The size of the string to generate.

    Returns:
        A generator that produces 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) -> Generator

Alias for generate.str.

PARAMETER DESCRIPTION
size

The size of the string to generate.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
Generator

A generator that produces random strings.

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

    Args:
        size:
            The size of the string to generate.

    Returns:
        A generator that produces random strings.
    """
    return str(size=size)

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

Create a time generator.

Info

Pact internally uses the Java's SimpleDateFormat. To ensure compatibility with the rest of the Python ecosystem, this function accepts Python's strftime format and performs the conversion to Java's format internally.

PARAMETER DESCRIPTION
format

Expected format of the time.

If not provided, an ISO 8601 time format will be used: %H:%M:%S.

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

disable_conversion

If True, the conversion from Python's strftime format to Java's SimpleDateFormat format will be disabled, and the format must be in Java's SimpleDateFormat format. As a result, the value must be a string as Python cannot format the time in the target format.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Generator

A generator that produces 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,
) -> Generator:
    """
    Create a time generator.

    !!! info

        Pact internally uses the Java's
        [`SimpleDateFormat`](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html).
        To ensure compatibility with the rest of the Python ecosystem, this
        function accepts Python's
        [`strftime`](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)
        format and performs the conversion to Java's format internally.

    Args:
        format:
            Expected format of the time.

            If not provided, an ISO 8601 time format will be used: `%H:%M:%S`.

        disable_conversion:
            If True, the conversion from Python's `strftime` format to Java's
            `SimpleDateFormat` format will be disabled, and the format must be
            in Java's `SimpleDateFormat` format. As a result, the value must be
            a string as Python cannot format the time in the target format.

    Returns:
        A generator that produces 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) -> Generator

Alias for generate.datetime.

RETURNS DESCRIPTION
Generator

A generator that produces datetimes in the specified format.

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

    Returns:
        A generator that produces datetimes in the specified format.
    """
    return datetime(format=format, disable_conversion=disable_conversion)

uuid(format: Literal['simple', 'lowercase', 'uppercase', 'urn'] = 'lowercase') -> Generator

Create a UUID generator.

PARAMETER DESCRIPTION
format

The format of the UUID to generate. This parameter is only supported under the V4 specification.

TYPE: Literal['simple', 'lowercase', 'uppercase', 'urn'] DEFAULT: 'lowercase'

RETURNS DESCRIPTION
Generator

A generator that produces UUIDs in the specified format.

Source code in src/pact/generate/__init__.py
def uuid(
    format: Literal["simple", "lowercase", "uppercase", "urn"] = "lowercase",
) -> Generator:
    """
    Create a UUID generator.

    Args:
        format:
            The format of the UUID to generate. This parameter is only supported
            under the V4 specification.

    Returns:
        A generator that produces UUIDs in the specified format.
    """
    return GenericGenerator("Uuid", {"format": format})