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/v3/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/v3/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.

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

boolean() -> Generator

Alias for generate.bool.

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

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

Create a date generator.

PARAMETER DESCRIPTION
format

Expected format of the date. This uses Python's strftime format

Pact internally uses the Java SimpleDateFormat and the conversion from Python's strftime format to Java's SimpleDateFormat format is done in [strftime_to_simple_date_format][pact.v3.util.strftime_to_simple_date_format].

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

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

    Args:
        format:
            Expected format of the date. This uses Python's [`strftime`
            format](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes)

            Pact internally uses the [Java
            SimpleDateFormat](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)
            and the conversion from Python's `strftime` format to Java's
            `SimpleDateFormat` format is done in
            [`strftime_to_simple_date_format`][pact.v3.util.strftime_to_simple_date_format].

            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.
    """
    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 date-time generator.

PARAMETER DESCRIPTION
format

Expected format of the timestamp. This uses Python's strftime format

Pact internally uses the Java SimpleDateFormat and the conversion from Python's strftime format to Java's SimpleDateFormat format is done in [strftime_to_simple_date_format][pact.v3.util.strftime_to_simple_date_format].

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

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

    Args:
        format:
            Expected format of the timestamp. This uses Python's [`strftime`
            format](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes)

            Pact internally uses the [Java
            SimpleDateFormat](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)
            and the conversion from Python's `strftime` format to Java's
            `SimpleDateFormat` format is done in
            [`strftime_to_simple_date_format`][pact.v3.util.strftime_to_simple_date_format].

            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
    """
    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.

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

Source code in src/pact/v3/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.
    """
    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

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

    Args:
        digits:
            The number of digits to generate.
    """
    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.

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

Source code in src/pact/v3/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.
    """
    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.

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

Source code in src/pact/v3/generate/__init__.py
def mock_server_url(  # noqa: D417 (false positive)
    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.
    """  # noqa: D214, D405  (false positive)
    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

Source code in src/pact/v3/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.
    """
    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

Source code in src/pact/v3/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.
    """
    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

Source code in src/pact/v3/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.
    """
    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.

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

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

Create a time generator.

PARAMETER DESCRIPTION
format

Expected format of the time. This uses Python's strftime format

Pact internally uses the Java SimpleDateFormat and the conversion from Python's strftime format to Java's SimpleDateFormat format is done in [strftime_to_simple_date_format][pact.v3.util.strftime_to_simple_date_format].

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

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

    Args:
        format:
            Expected format of the time. This uses Python's [`strftime`
            format](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes)

            Pact internally uses the [Java
            SimpleDateFormat](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)
            and the conversion from Python's `strftime` format to Java's
            `SimpleDateFormat` format is done in
            [`strftime_to_simple_date_format`][pact.v3.util.strftime_to_simple_date_format].

            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.
    """
    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.

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

Source code in src/pact/v3/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.
    """
    return GenericGenerator("Uuid", {"format": format})