Skip to content

Ffi

Python bindings for the Pact FFI.

This module provides a Python interface to the Pact FFI. It is a thin wrapper around the C API, and is intended to be used by the Pact Python client library to provide a Pythonic interface to Pact.

Warning

This module is not intended to be used directly by Pact users. Pact users should use the Pact Python client library instead. No guarantees are made about the stability of this module's API.

Developer Notes

This modules should provide the following only:

  • Basic Enum classes
  • Simple wrappers around functions, including the casting of input and output values between the high level Python types and the low level C types.
  • Simple wrappers around some of the low-level types. Specifically designed to automatically handle the freeing of memory when the Python object is destroyed.

These low-level functions may then be combined into higher level classes and modules. Ideally, all code outside of this module should be written in pure Python and not worry about allocating or freeing memory.

During initial implementation, a lot of these functions will simply raise a NotImplementedError.

For those unfamiliar with CFFI, please make sure to read the CFFI documentation.

Handles

The Rust library exposes a number of handles to internal data structures. This is done to avoid exposing the internal implementation details of the library to users of the library, and avoid unnecessarily casting to and from possibly complicated structs.

In the Rust library, the handles are thin wrappers around integers, and unfortunately the CFFI interface sees this and automatically unwraps them, exposing the underlying integer. As a result, we must re-wrap the integer returned by the CFFI interface. This unfortunately means that we may be subject to changes in private implementation details upstream.

Freeing Memory

Python has a garbage collector, and as a result, we don't need to worry about manually freeing memory. Having said that, Python's garbace collector is only aware of Python objects, and not of any memory allocated by the Rust library.

To ensure that the memory allocated by the Rust library is freed, we must make sure to define the __del__ method to call the appropriate free function whenever the Python object is destroyed.

Note that there are some rather subtle details as to when this is called, when it may never be called, and what global variables are accessible. This is explained in the documentation for __del__ above, and in Python's garbage collection module.

Error Handling

The FFI function should handle all errors raised by the function call, and raise an appropriate Python exception. The exception should be raised using the appropriate Python exception class, and should be documented in the function's docstring.

Attributes

GeneratorCategoryOptions = Literal['METHOD', 'method', 'PATH', 'path', 'HEADER', 'header', 'QUERY', 'query', 'BODY', 'body', 'STATUS', 'status', 'METADATA', 'metadata'] module-attribute

Generator Category Options.

Type alias for the string literals which represent the Generator Category Options.

MatchingRuleCategoryOptions = Literal['METHOD', 'method', 'PATH', 'path', 'HEADER', 'header', 'QUERY', 'query', 'BODY', 'body', 'STATUS', 'status', 'CONTENTS', 'contents', 'METADATA', 'metadata'] module-attribute

logger = logging.getLogger(__name__) module-attribute

Classes

AsynchronousMessage(ptr: cffi.FFI.CData, *, owned: bool = False)

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

owned

Whether the message is owned by something else or not. This determines whether the message should be freed when the Python object is destroyed.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
TypeError

If the ptr is not a struct AsynchronousMessage.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData, *, owned: bool = False) -> None:
    """
    Initialise a new Asynchronous Message.

    Args:
        ptr:
            CFFI data structure.

        owned:
            Whether the message is owned by something else or not. This
            determines whether the message should be freed when the Python
            object is destroyed.

    Raises:
        TypeError:
            If the `ptr` is not a `struct AsynchronousMessage`.
    """
    if ffi.typeof(ptr).cname != "struct AsynchronousMessage *":
        msg = (
            f"ptr must be a struct AsynchronousMessage, got {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr
    self._owned = owned

Attributes

contents: MessageContents | None property

The contents of the message.

This may be None if the message has no contents.

description: str property

Description of this message interaction.

This needs to be unique in the pact file.

Functions

provider_states() -> GeneratorType[ProviderState, None, None]

Optional provider state for the interaction.

Source code in src/pact/v3/ffi.py
def provider_states(self) -> GeneratorType[ProviderState, None, None]:
    """
    Optional provider state for the interaction.
    """
    yield from async_message_get_provider_state_iter(self)
    return  # Ensures that the parent object outlives the generator

Consumer

ExpressionValueType

Bases: Enum

Expression Value Type.

Rust ExpressionValueType

Attributes

BOOLEAN = lib.ExpressionValueType_Boolean class-attribute instance-attribute
DECIMAL = lib.ExpressionValueType_Decimal class-attribute instance-attribute
INTEGER = lib.ExpressionValueType_Integer class-attribute instance-attribute
NUMBER = lib.ExpressionValueType_Number class-attribute instance-attribute
STRING = lib.ExpressionValueType_String class-attribute instance-attribute
UNKNOWN = lib.ExpressionValueType_Unknown class-attribute instance-attribute

Generator(ptr: cffi.FFI.CData)

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct Generator.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a generator value.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct Generator`.
    """
    if ffi.typeof(ptr).cname != "struct Generator *":
        msg = f"ptr must be a struct Generator, got {ffi.typeof(ptr).cname}"
        raise TypeError(msg)
    self._ptr = ptr

Attributes

json: dict[str, Any] property

Dictionary representation of the generator.

Functions

generate_integer(context: dict[str, Any] | None = None) -> int

Generate an integer from the generator.

PARAMETER DESCRIPTION
context

JSON payload containing any generator context. For example:

  • The context for a ProviderStateGenerator should contain the values returned from the provider state callback function.

TYPE: dict[str, Any] | None DEFAULT: None

Source code in src/pact/v3/ffi.py
def generate_integer(self, context: dict[str, Any] | None = None) -> int:
    """
    Generate an integer from the generator.

    Args:
        context:
            JSON payload containing any generator context. For example:

            -   The context for a `ProviderStateGenerator` should contain
                the values returned from the provider state callback
                function.
    """
    return generator_generate_integer(self, json.dumps(context or {}))
generate_string(context: dict[str, Any] | None = None) -> str

Generate a string from the generator.

PARAMETER DESCRIPTION
context

JSON payload containing any generator context. For example:

  • The context for a MockServerURL generator should contain details about the running mock server.
  • The context for a ProviderStateGenerator should contain the values returned from the provider state callback function.

TYPE: dict[str, Any] | None DEFAULT: None

Source code in src/pact/v3/ffi.py
def generate_string(self, context: dict[str, Any] | None = None) -> str:
    """
    Generate a string from the generator.

    Args:
        context:
            JSON payload containing any generator context. For example:

            -   The context for a `MockServerURL` generator should contain
                details about the running mock server.
            -   The context for a `ProviderStateGenerator` should contain
                the values returned from the provider state callback
                function.
    """
    return generator_generate_string(self, json.dumps(context or {}))

GeneratorCategory

Bases: Enum

Generator Category.

Rust GeneratorCategory

Attributes

BODY = lib.GeneratorCategory_BODY class-attribute instance-attribute
HEADER = lib.GeneratorCategory_HEADER class-attribute instance-attribute
METADATA = lib.GeneratorCategory_METADATA class-attribute instance-attribute
METHOD = lib.GeneratorCategory_METHOD class-attribute instance-attribute
PATH = lib.GeneratorCategory_PATH class-attribute instance-attribute
QUERY = lib.GeneratorCategory_QUERY class-attribute instance-attribute
STATUS = lib.GeneratorCategory_STATUS class-attribute instance-attribute

GeneratorCategoryIterator(ptr: cffi.FFI.CData)

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct GeneratorCategoryIterator.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new generator category iterator.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct GeneratorCategoryIterator`.
    """
    if ffi.typeof(ptr).cname != "struct GeneratorCategoryIterator *":
        msg = (
            "ptr must be a struct GeneratorCategoryIterator, got"
            f" {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr

GeneratorKeyValuePair(ptr: cffi.FFI.CData)

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct GeneratorKeyValuePair.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new key-value generator pair.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct GeneratorKeyValuePair`.
    """
    if ffi.typeof(ptr).cname != "struct GeneratorKeyValuePair *":
        msg = (
            "ptr must be a struct GeneratorKeyValuePair, got"
            f" {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr

Attributes

generator: Generator property

Generator value.

path: str property

Generator path.

HttpRequest

HttpResponse

InteractionHandle(ref: int)

Handle to a HTTP Interaction.

Rust InteractionHandle

PARAMETER DESCRIPTION
ref

Reference to the Interaction Handle.

TYPE: int

Source code in src/pact/v3/ffi.py
def __init__(self, ref: int) -> None:
    """
    Initialise a new Interaction Handle.

    Args:
        ref:
            Reference to the Interaction Handle.
    """
    self._ref: int = ref

InteractionPart

Bases: Enum

Interaction Part.

Rust InteractionPart

Attributes

REQUEST = lib.InteractionPart_Request class-attribute instance-attribute
RESPONSE = lib.InteractionPart_Response class-attribute instance-attribute

LevelFilter

Bases: Enum

Level Filter.

Attributes

DEBUG = lib.LevelFilter_Debug class-attribute instance-attribute
ERROR = lib.LevelFilter_Error class-attribute instance-attribute
INFO = lib.LevelFilter_Info class-attribute instance-attribute
OFF = lib.LevelFilter_Off class-attribute instance-attribute
TRACE = lib.LevelFilter_Trace class-attribute instance-attribute
WARN = lib.LevelFilter_Warn class-attribute instance-attribute

MatchingRule(ptr: cffi.FFI.CData)

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct MatchingRule.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new key-value generator pair.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct MatchingRule`.
    """
    if ffi.typeof(ptr).cname != "struct MatchingRule *":
        msg = f"ptr must be a struct MatchingRule, got {ffi.typeof(ptr).cname}"
        raise TypeError(msg)
    self._ptr = ptr

Attributes

json: dict[str, Any] property

Dictionary representation of the matching rule.

MatchingRuleCategory

Bases: Enum

Matching Rule Category.

Rust MatchingRuleCategory

Attributes

BODY = lib.MatchingRuleCategory_BODY class-attribute instance-attribute
CONTENTS = lib.MatchingRuleCategory_CONTENTS class-attribute instance-attribute
HEADER = lib.MatchingRuleCategory_HEADER class-attribute instance-attribute
METADATA = lib.MatchingRuleCategory_METADATA class-attribute instance-attribute
METHOD = lib.MatchingRuleCategory_METHOD class-attribute instance-attribute
PATH = lib.MatchingRuleCategory_PATH class-attribute instance-attribute
QUERY = lib.MatchingRuleCategory_QUERY class-attribute instance-attribute
STATUS = lib.MatchingRuleCategory_STATUS class-attribute instance-attribute

MatchingRuleCategoryIterator(ptr: cffi.FFI.CData)

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct MatchingRuleCategoryIterator.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new key-value generator pair.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct MatchingRuleCategoryIterator`.
    """
    if ffi.typeof(ptr).cname != "struct MatchingRuleCategoryIterator *":
        msg = (
            "ptr must be a struct MatchingRuleCategoryIterator, got"
            f" {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr

MatchingRuleDefinitionResult

MatchingRuleIterator

MatchingRuleKeyValuePair(ptr: cffi.FFI.CData)

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct MatchingRuleKeyValuePair.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new key-value generator pair.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct MatchingRuleKeyValuePair`.
    """
    if ffi.typeof(ptr).cname != "struct MatchingRuleKeyValuePair *":
        msg = (
            "ptr must be a struct MatchingRuleKeyValuePair, got"
            f" {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr

Attributes

matching_rule: MatchingRule property

Matching Rule value.

path: str property

Matching Rule path.

MatchingRuleResult

MessageContents(ptr: cffi.FFI.CData, *, owned: bool = True)

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

owned

Whether the message is owned by something else or not. This determines whether the message should be freed when the Python object is destroyed.

TYPE: bool DEFAULT: True

RAISES DESCRIPTION
TypeError

If the ptr is not a struct MessageContents.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData, *, owned: bool = True) -> None:
    """
    Initialise a Message Contents.

    Args:
        ptr:
            CFFI data structure.

        owned:
            Whether the message is owned by something else or not. This
            determines whether the message should be freed when the Python
            object is destroyed.

    Raises:
        TypeError:
            If the `ptr` is not a `struct MessageContents`.
    """
    if ffi.typeof(ptr).cname != "struct MessageContents *":
        msg = f"ptr must be a struct MessageContents, got {ffi.typeof(ptr).cname}"
        raise TypeError(msg)
    self._ptr = ptr
    self._owned = owned

Attributes

contents: str | bytes | None property

Get the contents of the message.

metadata: GeneratorType[MessageMetadataPair, None, None] property

Get the metadata for the message contents.

Functions

generators(category: GeneratorCategoryOptions | GeneratorCategory) -> GeneratorType[GeneratorKeyValuePair, None, None]

Get the generators for the message contents.

Source code in src/pact/v3/ffi.py
def generators(
    self,
    category: GeneratorCategoryOptions | GeneratorCategory,
) -> GeneratorType[GeneratorKeyValuePair, None, None]:
    """
    Get the generators for the message contents.
    """
    if isinstance(category, str):
        category = GeneratorCategory(category.upper())
    yield from message_contents_get_generators_iter(self, category)
    return  # Ensures that the parent object outlives the generator
matching_rules(category: MatchingRuleCategoryOptions | MatchingRuleCategory) -> GeneratorType[MatchingRuleKeyValuePair, None, None]

Get the matching rules for the message contents.

Source code in src/pact/v3/ffi.py
def matching_rules(
    self,
    category: MatchingRuleCategoryOptions | MatchingRuleCategory,
) -> GeneratorType[MatchingRuleKeyValuePair, None, None]:
    """
    Get the matching rules for the message contents.
    """
    if isinstance(category, str):
        category = MatchingRuleCategory(category.upper())
    yield from message_contents_get_matching_rule_iter(self, category)
    return  # Ensures that the parent object outlives the generator

MessageMetadataIterator(ptr: cffi.FFI.CData)

Iterator over an interaction's metadata.

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct MessageMetadataIterator.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new Message Metadata Iterator.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct MessageMetadataIterator`.
    """
    if ffi.typeof(ptr).cname != "struct MessageMetadataIterator *":
        msg = (
            "ptr must be a struct MessageMetadataIterator, got"
            f" {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr

MessageMetadataPair(ptr: cffi.FFI.CData)

A metadata key-value pair.

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct MessageMetadataPair.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new Message Metadata Pair.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct MessageMetadataPair`.
    """
    if ffi.typeof(ptr).cname != "struct MessageMetadataPair *":
        msg = (
            f"ptr must be a struct MessageMetadataPair, got {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr

Attributes

key: str property

Metadata key.

value: str property

Metadata value.

Mismatch

Mismatches

MismatchesIterator

OwnedString(ptr: cffi.FFI.CData)

Bases: str

A string that owns its own memory.

This is used to ensure that the memory is freed when the string is destroyed.

As this is subclassed from str, it can be used in place of a normal string in most cases.

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new Owned String.

    Args:
        ptr:
            CFFI data structure.
    """
    self._ptr = ptr
    s = ffi.string(ptr)
    self._string = s if isinstance(s, str) else s.decode("utf-8")

Pact

PactAsyncMessageIterator(ptr: cffi.FFI.CData)

Iterator over a Pact's asynchronous messages.

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct PactAsyncMessageIterator.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new Pact Asynchronous Message Iterator.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct PactAsyncMessageIterator`.
    """
    if ffi.typeof(ptr).cname != "struct PactAsyncMessageIterator *":
        msg = (
            "ptr must be a struct PactAsyncMessageIterator, got"
            f" {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr

PactHandle(ref: int)

Handle to a Pact.

Rust PactHandle

PARAMETER DESCRIPTION
ref

Rust library reference to the Pact Handle.

TYPE: int

Source code in src/pact/v3/ffi.py
def __init__(self, ref: int) -> None:
    """
    Initialise a new Pact Handle.

    Args:
        ref:
            Rust library reference to the Pact Handle.
    """
    self._ref: int = ref

PactInteraction

PactInteractionIterator(ptr: cffi.FFI.CData)

Iterator over a Pact's interactions.

Interactions encompasses all types of interactions, including HTTP interactions and messages.

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct PactInteractionIterator.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new Pact Interaction Iterator.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct PactInteractionIterator`.
    """
    if ffi.typeof(ptr).cname != "struct PactInteractionIterator *":
        msg = (
            "ptr must be a struct PactInteractionIterator, got"
            f" {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr

PactServerHandle(ref: int)

Handle to a Pact Server.

This does not have an exact correspondence in the Rust library. It is used to manage the lifecycle of the mock server.

Implementation Notes

The Rust library uses the port number as a unique identifier, in much the same was as it uses a wrapped integer for the Pact handle.

PARAMETER DESCRIPTION
ref

Rust library reference to the Pact Server.

TYPE: int

Source code in src/pact/v3/ffi.py
def __init__(self, ref: int) -> None:
    """
    Initialise a new Pact Server Handle.

    Args:
        ref:
            Rust library reference to the Pact Server.
    """
    self._ref: int = ref

Attributes

port: int property

Port on which the Pact Server is running.

PactSpecification

Bases: Enum

Pact Specification.

Rust PactSpecification

Attributes

UNKNOWN = lib.PactSpecification_Unknown class-attribute instance-attribute
V1 = lib.PactSpecification_V1 class-attribute instance-attribute
V1_1 = lib.PactSpecification_V1_1 class-attribute instance-attribute
V2 = lib.PactSpecification_V2 class-attribute instance-attribute
V3 = lib.PactSpecification_V3 class-attribute instance-attribute
V4 = lib.PactSpecification_V4 class-attribute instance-attribute

Functions

from_str(version: str) -> PactSpecification classmethod

Instantiate a Pact Specification from a string.

This method is case-insensitive, and allows for the version to be specified with or without a leading "V", and with either a dot or an underscore as the separator.

PARAMETER DESCRIPTION
version

The version of the Pact Specification.

TYPE: str

RETURNS DESCRIPTION
PactSpecification

The Pact Specification.

Source code in src/pact/v3/ffi.py
@classmethod
def from_str(cls, version: str) -> PactSpecification:
    """
    Instantiate a Pact Specification from a string.

    This method is case-insensitive, and allows for the version to be
    specified with or without a leading "V", and with either a dot or an
    underscore as the separator.

    Args:
        version:
            The version of the Pact Specification.

    Returns:
        The Pact Specification.
    """
    version = version.upper().replace(".", "_")
    if version.startswith("V"):
        return cls[version]
    return cls["V" + version]

PactSyncHttpIterator(ptr: cffi.FFI.CData)

Iterator over a Pact's synchronous HTTP interactions.

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct PactSyncHttpIterator.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new Pact Synchronous HTTP Iterator.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct PactSyncHttpIterator`.
    """
    if ffi.typeof(ptr).cname != "struct PactSyncHttpIterator *":
        msg = (
            "ptr must be a struct PactSyncHttpIterator, got"
            f" {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr

PactSyncMessageIterator(ptr: cffi.FFI.CData)

Iterator over a Pact's synchronous messages.

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct PactSyncMessageIterator.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new Pact Synchronous Message Iterator.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct PactSyncMessageIterator`.
    """
    if ffi.typeof(ptr).cname != "struct PactSyncMessageIterator *":
        msg = (
            "ptr must be a struct PactSyncMessageIterator, got"
            f" {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr

Provider

ProviderState(ptr: cffi.FFI.CData)

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct ProviderState.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new ProviderState.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct ProviderState`.
    """
    if ffi.typeof(ptr).cname != "struct ProviderState *":
        msg = f"ptr must be a struct ProviderState, got {ffi.typeof(ptr).cname}"
        raise TypeError(msg)
    self._ptr = ptr

Attributes

name: str property

Provider State name.

Functions

parameters() -> GeneratorType[tuple[str, str], None, None]

Provider State parameters.

This is a generator that yields key-value pairs.

Source code in src/pact/v3/ffi.py
def parameters(self) -> GeneratorType[tuple[str, str], None, None]:
    """
    Provider State parameters.

    This is a generator that yields key-value pairs.
    """
    for p in provider_state_get_param_iter(self):
        yield p.key, p.value
    return  # Ensures that the parent object outlives the generator

ProviderStateIterator(ptr: cffi.FFI.CData)

Iterator over an interactions ProviderStates.

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct ProviderStateIterator.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new Provider State Iterator.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct ProviderStateIterator`.
    """
    if ffi.typeof(ptr).cname != "struct ProviderStateIterator *":
        msg = (
            "ptr must be a struct ProviderStateIterator, got"
            f" {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr

ProviderStateParamIterator(ptr: cffi.FFI.CData)

Iterator over a Provider States Parameters.

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct ProviderStateParamIterator.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new Provider State Param Iterator.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct ProviderStateParamIterator`.
    """
    if ffi.typeof(ptr).cname != "struct ProviderStateParamIterator *":
        msg = (
            "ptr must be a struct ProviderStateParamIterator, got"
            f" {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr

ProviderStateParamPair(ptr: cffi.FFI.CData)

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the ptr is not a struct ProviderStateParamPair.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData) -> None:
    """
    Initialise a new ProviderStateParamPair.

    Args:
        ptr:
            CFFI data structure.

    Raises:
        TypeError:
            If the `ptr` is not a `struct ProviderStateParamPair`.
    """
    if ffi.typeof(ptr).cname != "struct ProviderStateParamPair *":
        msg = (
            "ptr must be a struct ProviderStateParamPair, got"
            f" {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr

Attributes

key: str property

Provider State Param key.

value: str property

Provider State Param value.

StringResult(cdata: cffi.FFI.CData)

String result.

PARAMETER DESCRIPTION
cdata

CFFI data structure.

TYPE: CData

RAISES DESCRIPTION
TypeError

If the cdata is not a struct StringResult.

Source code in src/pact/v3/ffi.py
def __init__(self, cdata: cffi.FFI.CData) -> None:
    """
    Initialise a new String Result.

    Args:
        cdata:
            CFFI data structure.

    Raises:
        TypeError:
            If the `cdata` is not a `struct StringResult`.
    """
    if ffi.typeof(cdata).cname != "struct StringResult":
        msg = f"cdata must be a struct StringResult, got {ffi.typeof(cdata).cname}"
        raise TypeError(msg)
    self._cdata = typing.cast(StringResult._StringResultCData, cdata)

Attributes

is_failed: bool property

Whether the result is an error.

is_ok: bool property

Whether the result is ok.

text: str property

The text of the result.

Functions

raise_exception() -> None

Raise an exception with the text of the result.

RAISES DESCRIPTION
RuntimeError

If the result is an error.

RAISES DESCRIPTION
RuntimeError

If the result is an error.

Source code in src/pact/v3/ffi.py
def raise_exception(self) -> None:
    """
    Raise an exception with the text of the result.

    Raises:
        RuntimeError:
            If the result is an error.

    Raises:
        RuntimeError:
            If the result is an error.
    """
    if self.is_failed:
        raise RuntimeError(self.text)

SynchronousHttp(ptr: cffi.FFI.CData, *, owned: bool = False)

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

owned

Whether the message is owned by something else or not. This determines whether the message should be freed when the Python object is destroyed.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
TypeError

If the ptr is not a struct SynchronousHttp.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData, *, owned: bool = False) -> None:
    """
    Initialise a new Synchronous HTTP Interaction.

    Args:
        ptr:
            CFFI data structure.

        owned:
            Whether the message is owned by something else or not. This
            determines whether the message should be freed when the Python
            object is destroyed.

    Raises:
        TypeError:
            If the `ptr` is not a `struct SynchronousHttp`.
    """
    if ffi.typeof(ptr).cname != "struct SynchronousHttp *":
        msg = f"ptr must be a struct SynchronousHttp, got {ffi.typeof(ptr).cname}"
        raise TypeError(msg)
    self._ptr = ptr
    self._owned = owned

Attributes

description: str property

Description of this message interaction.

This needs to be unique in the pact file.

request_contents: str | bytes | None property

The contents of the request.

response_contents: str | bytes | None property

The contents of the response.

Functions

provider_states() -> GeneratorType[ProviderState, None, None]

Optional provider state for the interaction.

Source code in src/pact/v3/ffi.py
def provider_states(self) -> GeneratorType[ProviderState, None, None]:
    """
    Optional provider state for the interaction.
    """
    yield from sync_http_get_provider_state_iter(self)
    return  # Ensures that the parent object outlives the generator

SynchronousMessage(ptr: cffi.FFI.CData, *, owned: bool = False)

PARAMETER DESCRIPTION
ptr

CFFI data structure.

TYPE: CData

owned

Whether the message is owned by something else or not. This determines whether the message should be freed when the Python object is destroyed.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
TypeError

If the ptr is not a struct SynchronousMessage.

Source code in src/pact/v3/ffi.py
def __init__(self, ptr: cffi.FFI.CData, *, owned: bool = False) -> None:
    """
    Initialise a new Synchronous Message.

    Args:
        ptr:
            CFFI data structure.

        owned:
            Whether the message is owned by something else or not. This
            determines whether the message should be freed when the Python
            object is destroyed.

    Raises:
        TypeError:
            If the `ptr` is not a `struct SynchronousMessage`.
    """
    if ffi.typeof(ptr).cname != "struct SynchronousMessage *":
        msg = (
            f"ptr must be a struct SynchronousMessage, got {ffi.typeof(ptr).cname}"
        )
        raise TypeError(msg)
    self._ptr = ptr
    self._owned = owned

Attributes

description: str property

Description of this message interaction.

This needs to be unique in the pact file.

request_contents: MessageContents property

The contents of the message.

response_contents: GeneratorType[MessageContents, None, None] property

The contents of the responses.

Functions

provider_states() -> GeneratorType[ProviderState, None, None]

Optional provider state for the interaction.

Source code in src/pact/v3/ffi.py
def provider_states(self) -> GeneratorType[ProviderState, None, None]:
    """
    Optional provider state for the interaction.
    """
    yield from sync_message_get_provider_state_iter(self)
    return  # Ensures that the parent object outlives the generator

VerifierHandle(ref: cffi.FFI.CData)

Handle to a Verifier.

Rust VerifierHandle

PARAMETER DESCRIPTION
ref

Rust library reference to the Verifier Handle.

TYPE: CData

Source code in src/pact/v3/ffi.py
def __init__(self, ref: cffi.FFI.CData) -> None:
    """
    Initialise a new Verifier Handle.

    Args:
        ref:
            Rust library reference to the Verifier Handle.
    """
    self._ref = ref

Functions

add_text_comment(interaction: InteractionHandle, comment: str) -> None

Add a text comment to the interaction.

Rust pactffi_add_text_comment

PARAMETER DESCRIPTION
interaction

Interaction handle to set the comments for.

TYPE: InteractionHandle

comment

Comment value. This is a regular string value.

TYPE: str

RAISES DESCRIPTION
RuntimeError

If the comment could not be added.

Source code in src/pact/v3/ffi.py
def add_text_comment(interaction: InteractionHandle, comment: str) -> None:
    """
    Add a text comment to the interaction.

    [Rust
    `pactffi_add_text_comment`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_add_text_comment)

    Args:
        interaction:
            Interaction handle to set the comments for.

        comment:
            Comment value. This is a regular string value.

    Raises:
        RuntimeError:
            If the comment could not be added.
    """
    success: bool = lib.pactffi_add_text_comment(
        interaction._ref,
        comment.encode("utf-8"),
    )
    if not success:
        msg = f"Failed to add text comment for {interaction}."
        raise RuntimeError(msg)

async_message_delete(message: AsynchronousMessage) -> None

Destroy the AsynchronousMessage being pointed to.

Rust pactffi_async_message_delete

Source code in src/pact/v3/ffi.py
def async_message_delete(message: AsynchronousMessage) -> None:
    """
    Destroy the `AsynchronousMessage` being pointed to.

    [Rust `pactffi_async_message_delete`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_async_message_delete)
    """
    lib.pactffi_async_message_delete(message._ptr)

async_message_generate_contents(message: AsynchronousMessage) -> MessageContents | None

Get the message contents of an AsynchronousMessage as a MessageContents pointer.

This function differs from async_message_get_contents in that it will process the message contents for any generators or matchers that are present in the message in order to generate the actual message contents as would be received by the consumer.

Rust pactffi_async_message_generate_contents

If the message contents are missing, this function will return None.

Source code in src/pact/v3/ffi.py
def async_message_generate_contents(
    message: AsynchronousMessage,
) -> MessageContents | None:
    """
    Get the message contents of an `AsynchronousMessage` as a `MessageContents` pointer.

    This function differs from `async_message_get_contents` in
    that it will process the message contents for any generators or matchers
    that are present in the message in order to generate the actual message
    contents as would be received by the consumer.

    [Rust
    `pactffi_async_message_generate_contents`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_async_message_generate_contents)

    If the message contents are missing, this function will return `None`.
    """
    return MessageContents(
        lib.pactffi_async_message_generate_contents(message._ptr),
        owned=False,
    )

async_message_get_contents(message: AsynchronousMessage) -> MessageContents | None

Get the message contents of an AsynchronousMessage as a MessageContents pointer.

Rust pactffi_async_message_get_contents

If the message contents are missing, this function will return None.

Source code in src/pact/v3/ffi.py
def async_message_get_contents(message: AsynchronousMessage) -> MessageContents | None:
    """
    Get the message contents of an `AsynchronousMessage` as a `MessageContents` pointer.

    [Rust
    `pactffi_async_message_get_contents`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_async_message_get_contents)

    If the message contents are missing, this function will return `None`.
    """
    return MessageContents(lib.pactffi_async_message_get_contents(message._ptr))

async_message_get_contents_bin(message: AsynchronousMessage) -> str

Get the contents of an AsynchronousMessage as bytes.

Rust pactffi_async_message_get_contents_bin

Safety

The number of bytes in the buffer will be returned by pactffi_async_message_get_contents_length. It is safe to use the pointer while the message is not deleted or changed. Using the pointer after the message is mutated or deleted may lead to undefined behaviour.

Error Handling

If the message is NULL, returns NULL. If the body of the message is missing, then this function also returns NULL.

Source code in src/pact/v3/ffi.py
def async_message_get_contents_bin(message: AsynchronousMessage) -> str:
    """
    Get the contents of an `AsynchronousMessage` as bytes.

    [Rust
    `pactffi_async_message_get_contents_bin`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_async_message_get_contents_bin)

    # Safety

    The number of bytes in the buffer will be returned by
    `pactffi_async_message_get_contents_length`. It is safe to use the pointer
    while the message is not deleted or changed. Using the pointer after the
    message is mutated or deleted may lead to undefined behaviour.

    # Error Handling

    If the message is NULL, returns NULL. If the body of the message is missing,
    then this function also returns NULL.
    """
    raise NotImplementedError

async_message_get_contents_length(message: AsynchronousMessage) -> int

Get the length of the contents of a AsynchronousMessage.

Rust pactffi_async_message_get_contents_length

Safety

This function is safe.

Error Handling

If the message is NULL, returns 0. If the body of the request is missing, then this function also returns 0.

Source code in src/pact/v3/ffi.py
def async_message_get_contents_length(message: AsynchronousMessage) -> int:
    """
    Get the length of the contents of a `AsynchronousMessage`.

    [Rust
    `pactffi_async_message_get_contents_length`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_async_message_get_contents_length)

    # Safety

    This function is safe.

    # Error Handling

    If the message is NULL, returns 0. If the body of the request is missing,
    then this function also returns 0.
    """
    raise NotImplementedError

async_message_get_contents_str(message: AsynchronousMessage) -> str

Get the message contents of an AsynchronousMessage in string form.

Rust pactffi_async_message_get_contents_str

Safety

The returned string must be deleted with pactffi_string_delete.

The returned string can outlive the message.

Error Handling

If the message is NULL, returns NULL. If the body of the message is missing, then this function also returns NULL. This means there's no mechanism to differentiate with this function call alone between a NULL message and a missing message body.

Source code in src/pact/v3/ffi.py
def async_message_get_contents_str(message: AsynchronousMessage) -> str:
    """
    Get the message contents of an `AsynchronousMessage` in string form.

    [Rust `pactffi_async_message_get_contents_str`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_async_message_get_contents_str)

    # Safety

    The returned string must be deleted with `pactffi_string_delete`.

    The returned string can outlive the message.

    # Error Handling

    If the message is NULL, returns NULL. If the body of the message
    is missing, then this function also returns NULL. This means there's
    no mechanism to differentiate with this function call alone between
    a NULL message and a missing message body.
    """
    raise NotImplementedError

async_message_get_description(message: AsynchronousMessage) -> str

Get a copy of the description.

Rust pactffi_async_message_get_description

RAISES DESCRIPTION
RuntimeError

If the description cannot be retrieved.

Source code in src/pact/v3/ffi.py
def async_message_get_description(message: AsynchronousMessage) -> str:
    r"""
    Get a copy of the description.

    [Rust
    `pactffi_async_message_get_description`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_async_message_get_description)

    Raises:
        RuntimeError:
            If the description cannot be retrieved.
    """
    ptr = lib.pactffi_async_message_get_description(message._ptr)
    if ptr == ffi.NULL:
        msg = "Unable to get the description from the message."
        raise RuntimeError(msg)
    return OwnedString(ptr)

async_message_get_provider_state(message: AsynchronousMessage, index: int) -> ProviderState

Get a copy of the provider state at the given index from this message.

Rust pactffi_async_message_get_provider_state

RAISES DESCRIPTION
RuntimeError

If the provider state cannot be retrieved.

Source code in src/pact/v3/ffi.py
def async_message_get_provider_state(
    message: AsynchronousMessage,
    index: int,
) -> ProviderState:
    r"""
    Get a copy of the provider state at the given index from this message.

    [Rust
    `pactffi_async_message_get_provider_state`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_async_message_get_provider_state)

    Raises:
        RuntimeError:
            If the provider state cannot be retrieved.
    """
    ptr = lib.pactffi_async_message_get_provider_state(message._ptr, index)
    if ptr == ffi.NULL:
        msg = "Unable to get the provider state from the message."
        raise RuntimeError(msg)
    return ProviderState(ptr)

async_message_get_provider_state_iter(message: AsynchronousMessage) -> ProviderStateIterator

Get an iterator over provider states.

Rust pactffi_async_message_get_provider_state_iter

Safety

The underlying data must not change during iteration.

Source code in src/pact/v3/ffi.py
def async_message_get_provider_state_iter(
    message: AsynchronousMessage,
) -> ProviderStateIterator:
    """
    Get an iterator over provider states.

    [Rust `pactffi_async_message_get_provider_state_iter`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_async_message_get_provider_state_iter)

    # Safety

    The underlying data must not change during iteration.
    """
    return ProviderStateIterator(
        lib.pactffi_async_message_get_provider_state_iter(message._ptr)
    )

async_message_new() -> AsynchronousMessage

Get a mutable pointer to a newly-created default message on the heap.

Rust pactffi_async_message_new

Safety

This function is safe.

Error Handling

Returns NULL on error.

Source code in src/pact/v3/ffi.py
def async_message_new() -> AsynchronousMessage:
    """
    Get a mutable pointer to a newly-created default message on the heap.

    [Rust `pactffi_async_message_new`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_async_message_new)

    # Safety

    This function is safe.

    # Error Handling

    Returns NULL on error.
    """
    raise NotImplementedError

async_message_set_contents_bin(message: AsynchronousMessage, contents: str, len: int, content_type: str) -> None

Sets the contents of the message as an array of bytes.

Rust pactffi_async_message_set_contents_bin

  • message - the message to set the contents for
  • contents - pointer to contents to copy from
  • len - number of bytes to copy from the contents pointer
  • content_type - pointer to the NULL-terminated UTF-8 string containing the content type of the data.

Safety

The contents pointer must be valid for reads of len bytes, and it must be properly aligned and consecutive. Otherwise behaviour is undefined.

Error Handling

If the contents is a NULL pointer, it will set the message contents as null. If the content type is a null pointer, or can't be parsed, it will set the content type as unknown.

Source code in src/pact/v3/ffi.py
def async_message_set_contents_bin(
    message: AsynchronousMessage,
    contents: str,
    len: int,
    content_type: str,
) -> None:
    """
    Sets the contents of the message as an array of bytes.

    [Rust
    `pactffi_async_message_set_contents_bin`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_async_message_set_contents_bin)

    * `message` - the message to set the contents for
    * `contents` - pointer to contents to copy from
    * `len` - number of bytes to copy from the contents pointer
    * `content_type` - pointer to the NULL-terminated UTF-8 string containing
      the content type of the data.

    # Safety

    The contents pointer must be valid for reads of `len` bytes, and it must be
    properly aligned and consecutive. Otherwise behaviour is undefined.

    # Error Handling

    If the contents is a NULL pointer, it will set the message contents as null.
    If the content type is a null pointer, or can't be parsed, it will set the
    content type as unknown.
    """
    raise NotImplementedError

async_message_set_contents_str(message: AsynchronousMessage, contents: str, content_type: str) -> None

Sets the contents of the message as a string.

Rust pactffi_async_message_set_contents_str

  • message - the message to set the contents for
  • contents - pointer to contents to copy from. Must be a valid NULL-terminated UTF-8 string pointer.
  • content_type - pointer to the NULL-terminated UTF-8 string containing the content type of the data.

Safety

The message contents and content type must either be NULL pointers, or point to valid UTF-8 encoded NULL-terminated strings. Otherwise behaviour is undefined.

Error Handling

If the contents is a NULL pointer, it will set the message contents as null. If the content type is a null pointer, or can't be parsed, it will set the content type as unknown.

Source code in src/pact/v3/ffi.py
def async_message_set_contents_str(
    message: AsynchronousMessage,
    contents: str,
    content_type: str,
) -> None:
    """
    Sets the contents of the message as a string.

    [Rust
    `pactffi_async_message_set_contents_str`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_async_message_set_contents_str)

    - `message` - the message to set the contents for
    - `contents` - pointer to contents to copy from. Must be a valid
      NULL-terminated UTF-8 string pointer.
    - `content_type` - pointer to the NULL-terminated UTF-8 string containing
      the content type of the data.

    # Safety

    The message contents and content type must either be NULL pointers, or point
    to valid UTF-8 encoded NULL-terminated strings. Otherwise behaviour is
    undefined.

    # Error Handling

    If the contents is a NULL pointer, it will set the message contents as null.
    If the content type is a null pointer, or can't be parsed, it will set the
    content type as unknown.
    """
    raise NotImplementedError

async_message_set_description(message: AsynchronousMessage, description: str) -> int

Write the description field on the AsynchronousMessage.

Rust pactffi_async_message_set_description

Safety

description must contain valid UTF-8. Invalid UTF-8 will be replaced with U+FFFD REPLACEMENT CHARACTER.

This function will only reallocate if the new string does not fit in the existing buffer.

Error Handling

Errors will be reported with a non-zero return value.

Source code in src/pact/v3/ffi.py
def async_message_set_description(
    message: AsynchronousMessage,
    description: str,
) -> int:
    """
    Write the `description` field on the `AsynchronousMessage`.

    [Rust `pactffi_async_message_set_description`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_async_message_set_description)

    # Safety

    `description` must contain valid UTF-8. Invalid UTF-8
    will be replaced with U+FFFD REPLACEMENT CHARACTER.

    This function will only reallocate if the new string
    does not fit in the existing buffer.

    # Error Handling

    Errors will be reported with a non-zero return value.
    """
    raise NotImplementedError

check_regex(regex: str, example: str) -> bool

Checks that the example string matches the given regex.

Rust pactffi_check_regex

Safety

Both the regex and example pointers must be valid pointers to NULL-terminated strings. Invalid pointers will result in undefined behaviour.

Source code in src/pact/v3/ffi.py
def check_regex(regex: str, example: str) -> bool:
    """
    Checks that the example string matches the given regex.

    [Rust
    `pactffi_check_regex`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_check_regex)

    # Safety

    Both the regex and example pointers must be valid pointers to
    NULL-terminated strings. Invalid pointers will result in undefined
    behaviour.
    """
    raise NotImplementedError

cleanup_mock_server(mock_server_handle: PactServerHandle) -> None

External interface to cleanup a mock server.

This function will try terminate the mock server with the given port number and cleanup any memory allocated for it.

Rust pactffi_cleanup_mock_server

PARAMETER DESCRIPTION
mock_server_handle

Handle to the mock server to cleanup.

TYPE: PactServerHandle

RAISES DESCRIPTION
RuntimeError

If the mock server could not be cleaned up.

Source code in src/pact/v3/ffi.py
def cleanup_mock_server(mock_server_handle: PactServerHandle) -> None:
    """
    External interface to cleanup a mock server.

    This function will try terminate the mock server with the given port number
    and cleanup any memory allocated for it.

    [Rust
    `pactffi_cleanup_mock_server`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_cleanup_mock_server)

    Args:
        mock_server_handle:
            Handle to the mock server to cleanup.

    Raises:
        RuntimeError:
            If the mock server could not be cleaned up.
    """
    success: bool = lib.pactffi_cleanup_mock_server(mock_server_handle._ref)
    if not success:
        msg = f"Could not cleanup mock server with port {mock_server_handle._ref}"
        raise RuntimeError(msg)

cleanup_plugins(pact: PactHandle) -> None

Decrement the access count on any plugins that are loaded for the Pact.

This will shutdown any plugins that are no longer required (access count is zero).

Rust pactffi_cleanup_plugins

Source code in src/pact/v3/ffi.py
def cleanup_plugins(pact: PactHandle) -> None:
    """
    Decrement the access count on any plugins that are loaded for the Pact.

    This will shutdown any plugins that are no longer required (access count is
    zero).

    [Rust
    `pactffi_cleanup_plugins`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_cleanup_plugins)
    """
    lib.pactffi_cleanup_plugins(pact._ref)

consumer_get_name(consumer: Consumer) -> str

Get a copy of this consumer's name.

Rust pactffi_consumer_get_name

The copy must be deleted with pactffi_string_delete.

Usage

// Assuming `file_name` and `json_str` are already defined.

MessagePact *message_pact = pactffi_message_pact_new_from_json(file_name, json_str);
if (message_pact == NULLPTR) {
    // handle error.
}

Consumer *consumer = pactffi_message_pact_get_consumer(message_pact);
if (consumer == NULLPTR) {
    // handle error.
}

char *name = pactffi_consumer_get_name(consumer);
if (name == NULL) {
    // handle error.
}

printf("%s\n", name);

pactffi_string_delete(name);

Errors

This function will fail if it is passed a NULL pointer, or the Rust string contains an embedded NULL byte. In the case of error, a NULL pointer will be returned.

Source code in src/pact/v3/ffi.py
def consumer_get_name(consumer: Consumer) -> str:
    r"""
    Get a copy of this consumer's name.

    [Rust `pactffi_consumer_get_name`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_consumer_get_name)

    The copy must be deleted with `pactffi_string_delete`.

    # Usage

    ```c
    // Assuming `file_name` and `json_str` are already defined.

    MessagePact *message_pact = pactffi_message_pact_new_from_json(file_name, json_str);
    if (message_pact == NULLPTR) {
        // handle error.
    }

    Consumer *consumer = pactffi_message_pact_get_consumer(message_pact);
    if (consumer == NULLPTR) {
        // handle error.
    }

    char *name = pactffi_consumer_get_name(consumer);
    if (name == NULL) {
        // handle error.
    }

    printf("%s\n", name);

    pactffi_string_delete(name);
    ```

    # Errors

    This function will fail if it is passed a NULL pointer,
    or the Rust string contains an embedded NULL byte.
    In the case of error, a NULL pointer will be returned.
    """
    raise NotImplementedError

create_mock_server(pact_str: str, addr_str: str, *, tls: bool) -> int

[DEPRECATED] External interface to create a HTTP mock server.

A pointer to the pact JSON as a NULL-terminated C string is passed in, as well as the port for the mock server to run on. A value of 0 for the port will result in a port being allocated by the operating system. The port of the mock server is returned.

Rust pactffi_create_mock_server

  • pact_str - Pact JSON
  • addr_str - Address to bind to in the form name:port (i.e. 127.0.0.1:80)
  • tls - boolean flag to indicate of the mock server should use TLS (using a self-signed certificate)

This function is deprecated and replaced with pactffi_create_mock_server_for_transport.

Errors

Errors are returned as negative values.

Error Description
-1 A null pointer was received
-2 The pact JSON could not be parsed
-3 The mock server could not be started
-4 The method panicked
-5 The address is not valid
-6 Could not create the TLS configuration with the self-signed certificate
Source code in src/pact/v3/ffi.py
def create_mock_server(pact_str: str, addr_str: str, *, tls: bool) -> int:
    """
    [DEPRECATED] External interface to create a HTTP mock server.

    A pointer to the pact JSON as a NULL-terminated C string is passed in, as
    well as the port for the mock server to run on. A value of 0 for the port
    will result in a port being allocated by the operating system. The port of
    the mock server is returned.

    [Rust
    `pactffi_create_mock_server`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_create_mock_server)

    * `pact_str` - Pact JSON
    * `addr_str` - Address to bind to in the form name:port (i.e. 127.0.0.1:80)
    * `tls` - boolean flag to indicate of the mock server should use TLS (using
      a self-signed certificate)

    This function is deprecated and replaced with
    `pactffi_create_mock_server_for_transport`.

    # Errors

    Errors are returned as negative values.

    | Error | Description |
    |-------|-------------|
    | -1 | A null pointer was received |
    | -2 | The pact JSON could not be parsed |
    | -3 | The mock server could not be started |
    | -4 | The method panicked |
    | -5 | The address is not valid |
    | -6 | Could not create the TLS configuration with the self-signed certificate |
    """
    warnings.warn(
        "This function is deprecated, use create_mock_server_for_transport instead",
        DeprecationWarning,
        stacklevel=2,
    )
    raise NotImplementedError

create_mock_server_for_pact(pact: PactHandle, addr_str: str, *, tls: bool) -> int

[DEPRECATED] External interface to create a HTTP mock server.

A Pact handle is passed in, as well as the port for the mock server to run on. A value of 0 for the port will result in a port being allocated by the operating system. The port of the mock server is returned.

Rust pactffi_create_mock_server_for_pact

  • pact - Handle to a Pact model created with created with pactffi_new_pact.
  • addr_str - Address to bind to in the form name:port (i.e. 127.0.0.1:0). Must be a valid UTF-8 NULL-terminated string.
  • tls - boolean flag to indicate of the mock server should use TLS (using a self-signed certificate)

This function is deprecated and replaced with pactffi_create_mock_server_for_transport.

Errors

Errors are returned as negative values.

Error Description
-1 An invalid handle was received. Handles should be created with pactffi_new_pact
-3 The mock server could not be started
-4 The method panicked
-5 The address is not valid
-6 Could not create the TLS configuration with the self-signed certificate
Source code in src/pact/v3/ffi.py
def create_mock_server_for_pact(pact: PactHandle, addr_str: str, *, tls: bool) -> int:
    """
    [DEPRECATED] External interface to create a HTTP mock server.

    A Pact handle is passed in, as well as the port for the mock server to run
    on. A value of 0 for the port will result in a port being allocated by the
    operating system. The port of the mock server is returned.

    [Rust
    `pactffi_create_mock_server_for_pact`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_create_mock_server_for_pact)

    * `pact` - Handle to a Pact model created with created with
      `pactffi_new_pact`.
    * `addr_str` - Address to bind to in the form name:port (i.e. 127.0.0.1:0).
      Must be a valid UTF-8 NULL-terminated string.
    * `tls` - boolean flag to indicate of the mock server should use TLS (using
      a self-signed certificate)

    This function is deprecated and replaced with
    `pactffi_create_mock_server_for_transport`.

    # Errors

    Errors are returned as negative values.

    | Error | Description |
    |-------|-------------|
    | -1 | An invalid handle was received. Handles should be created with `pactffi_new_pact` |
    | -3 | The mock server could not be started |
    | -4 | The method panicked |
    | -5 | The address is not valid |
    | -6 | Could not create the TLS configuration with the self-signed certificate |
    """  # noqa: E501
    warnings.warn(
        "This function is deprecated, use create_mock_server_for_transport instead",
        DeprecationWarning,
        stacklevel=2,
    )
    raise NotImplementedError

create_mock_server_for_transport(pact: PactHandle, addr: str, port: int, transport: str, transport_config: str | None) -> PactServerHandle

Create a mock server for the provided Pact handle and transport.

Rust pactffi_create_mock_server_for_transport

PARAMETER DESCRIPTION
pact

Handle to the Pact model.

TYPE: PactHandle

addr

The address to bind to.

TYPE: str

port

The port number to bind to. A value of zero will result in the operating system allocating an available port.

TYPE: int

transport

The transport to use (i.e. http, https, grpc). The underlying Pact library will interpret this, typically in a case-sensitive way.

TYPE: str

transport_config

Configuration to be passed to the transport. This must be a valid JSON string, or None if not required.

TYPE: str | None

RETURNS DESCRIPTION
PactServerHandle

A handle to the mock server.

RAISES DESCRIPTION
RuntimeError

If the mock server could not be created. The error message will contain details of the error.

Source code in src/pact/v3/ffi.py
def create_mock_server_for_transport(
    pact: PactHandle,
    addr: str,
    port: int,
    transport: str,
    transport_config: str | None,
) -> PactServerHandle:
    """
    Create a mock server for the provided Pact handle and transport.

    [Rust
    `pactffi_create_mock_server_for_transport`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_create_mock_server_for_transport)

    Args:
        pact:
            Handle to the Pact model.

        addr:
            The address to bind to.

        port:
            The port number to bind to. A value of zero will result in the
            operating system allocating an available port.

        transport:
            The transport to use (i.e. http, https, grpc). The underlying Pact
            library will interpret this, typically in a case-sensitive way.

        transport_config:
            Configuration to be passed to the transport. This must be a valid
            JSON string, or `None` if not required.

    Returns:
        A handle to the mock server.

    Raises:
        RuntimeError:
            If the mock server could not be created. The error message will
            contain details of the error.
    """
    ret: int = lib.pactffi_create_mock_server_for_transport(
        pact._ref,
        addr.encode("utf-8"),
        port,
        transport.encode("utf-8"),
        (transport_config.encode("utf-8") if transport_config else ffi.NULL),
    )
    if ret > 0:
        return PactServerHandle(ret)

    if ret == -1:
        msg = f"An invalid Pact handle was received: {pact}."
    elif ret == -2:  # noqa: PLR2004
        msg = "Invalid transport_config JSON."
    elif ret == -3:  # noqa: PLR2004
        msg = f"Pact mock server could not be started for {pact}."
    elif ret == -4:  # noqa: PLR2004
        msg = f"Panick during Pact mock server creation for {pact}."
    elif ret == -5:  # noqa: PLR2004
        msg = f"Address is invalid: {addr}."
    else:
        msg = f"An unknown error occurred during Pact mock server creation for {pact}."
    raise RuntimeError(msg)

enable_ansi_support() -> None

Enable ANSI coloured output on Windows.

On non-Windows platforms, this function is a no-op.

Rust pactffi_enable_ansi_support

Safety

This function is safe.

Source code in src/pact/v3/ffi.py
def enable_ansi_support() -> None:
    """
    Enable ANSI coloured output on Windows.

    On non-Windows platforms, this function is a no-op.

    [Rust
    `pactffi_enable_ansi_support`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_enable_ansi_support)

    # Safety

    This function is safe.
    """
    raise NotImplementedError

fetch_log_buffer(log_id: str) -> str

Fetch the in-memory logger buffer contents.

Rust pactffi_fetch_log_buffer

This will only have any contents if the buffer sink has been configured to log to. The contents will be allocated on the heap and will need to be freed with pactffi_string_delete.

Fetches the logs associated with the provided identifier, or uses the "global" one if the identifier is not specified (i.e. NULL).

Returns a NULL pointer if the buffer can't be fetched. This can occur is there is not sufficient memory to make a copy of the contents or the buffer contains non-UTF-8 characters.

Safety

This function will fail if the log_id pointer is invalid or does not point to a NULL terminated string.

Source code in src/pact/v3/ffi.py
def fetch_log_buffer(log_id: str) -> str:
    """
    Fetch the in-memory logger buffer contents.

    [Rust
    `pactffi_fetch_log_buffer`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_fetch_log_buffer)

    This will only have any contents if the `buffer` sink has been configured to
    log to. The contents will be allocated on the heap and will need to be freed
    with `pactffi_string_delete`.

    Fetches the logs associated with the provided identifier, or uses the
    "global" one if the identifier is not specified (i.e. NULL).

    Returns a NULL pointer if the buffer can't be fetched. This can occur is
    there is not sufficient memory to make a copy of the contents or the buffer
    contains non-UTF-8 characters.

    # Safety

    This function will fail if the log_id pointer is invalid or does not point
    to a NULL terminated string.
    """
    raise NotImplementedError

free_pact_handle(pact: PactHandle) -> None

Delete a Pact handle and free the resources used by it.

Rust pactffi_free_pact_handle

RAISES DESCRIPTION
RuntimeError

If the handle could not be freed.

Source code in src/pact/v3/ffi.py
def free_pact_handle(pact: PactHandle) -> None:
    """
    Delete a Pact handle and free the resources used by it.

    [Rust
    `pactffi_free_pact_handle`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_free_pact_handle)

    Raises:
        RuntimeError:
            If the handle could not be freed.
    """
    ret: int = lib.pactffi_free_pact_handle(pact._ref)
    if ret == 0:
        return
    if ret == 1:
        msg = f"{pact} is not valid or does not refer to a valid Pact."
    else:
        msg = f"There was an unknown error freeing {pact}."
    raise RuntimeError(msg)

free_string(s: str) -> None

[DEPRECATED] Frees the memory allocated to a string by another function.

Rust pactffi_free_string

This function is deprecated. Use pactffi_string_delete instead.

Safety

The string pointer can be NULL (which is a no-op), but if it is not a valid pointer the call will result in undefined behaviour.

Source code in src/pact/v3/ffi.py
def free_string(s: str) -> None:
    """
    [DEPRECATED] Frees the memory allocated to a string by another function.

    [Rust
    `pactffi_free_string`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_free_string)

    This function is deprecated. Use `pactffi_string_delete` instead.

    # Safety

    The string pointer can be NULL (which is a no-op), but if it is not a valid
    pointer the call will result in undefined behaviour.
    """
    warnings.warn(
        "This function is deprecated, use string_delete instead",
        DeprecationWarning,
        stacklevel=2,
    )
    raise NotImplementedError

generate_datetime_string(format: str) -> StringResult

Generates a datetime value from the provided format string.

This uses the current system date and time NOTE: The memory for the returned string needs to be freed with the pactffi_string_delete function

Rust pactffi_generate_datetime_string

Safety

If the format string pointer is NULL or has invalid UTF-8 characters, an error result will be returned. If the format string pointer is not a valid pointer or is not a NULL-terminated string, this will lead to undefined behaviour.

Source code in src/pact/v3/ffi.py
def generate_datetime_string(format: str) -> StringResult:
    """
    Generates a datetime value from the provided format string.

    This uses the current system date and time NOTE: The memory for the returned
    string needs to be freed with the `pactffi_string_delete` function

    [Rust
    `pactffi_generate_datetime_string`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_generate_datetime_string)

    # Safety

    If the format string pointer is NULL or has invalid UTF-8 characters, an
    error result will be returned. If the format string pointer is not a valid
    pointer or is not a NULL-terminated string, this will lead to undefined
    behaviour.
    """
    raise NotImplementedError

generate_regex_value(regex: str) -> StringResult

Generates an example string based on the provided regex.

NOTE: The memory for the returned string needs to be freed with the pactffi_string_delete function.

Rust pactffi_generate_regex_value

Safety

The regex pointer must be a valid pointer to a NULL-terminated string. Invalid pointers will result in undefined behaviour.

Source code in src/pact/v3/ffi.py
def generate_regex_value(regex: str) -> StringResult:
    """
    Generates an example string based on the provided regex.

    NOTE: The memory for the returned string needs to be freed with the
    `pactffi_string_delete` function.

    [Rust
    `pactffi_generate_regex_value`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_generate_regex_value)

    # Safety

    The regex pointer must be a valid pointer to a NULL-terminated string.
    Invalid pointers will result in undefined behaviour.
    """
    raise NotImplementedError

generator_generate_integer(generator: Generator, context_json: str) -> int

Generate an integer value using the provided generator.

An optional JSON payload containing any generator context can be given. The context value is used for generators like ProviderStateGenerator (which should be the values returned from the Provider State callback function).

Rust pactffi_generator_generate_integer

If anything goes wrong or the generator is not a type that can generate an integer value, it will return a zero value.

Source code in src/pact/v3/ffi.py
def generator_generate_integer(generator: Generator, context_json: str) -> int:
    """
    Generate an integer value using the provided generator.

    An optional JSON payload containing any generator context can be given. The
    context value is used for generators like `ProviderStateGenerator` (which
    should be the values returned from the Provider State callback function).

    [Rust
    `pactffi_generator_generate_integer`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_generator_generate_integer)

    If anything goes wrong or the generator is not a type that can generate an
    integer value, it will return a zero value.
    """
    return lib.pactffi_generator_generate_integer(
        generator._ptr,
        context_json.encode("utf-8"),
    )

generator_generate_string(generator: Generator, context_json: str) -> str

Generate a string value using the provided generator.

An optional JSON payload containing any generator context ca be given. The context value is used for generators like MockServerURL (which should contain details about the running mock server) and ProviderStateGenerator (which should be the values returned from the Provider State callback function).

Rust pactffi_generator_generate_string

If anything goes wrong, it will return a NULL pointer.

Source code in src/pact/v3/ffi.py
def generator_generate_string(generator: Generator, context_json: str) -> str:
    """
    Generate a string value using the provided generator.

    An optional JSON payload containing any generator context ca be given. The
    context value is used for generators like `MockServerURL` (which should
    contain details about the running mock server) and `ProviderStateGenerator`
    (which should be the values returned from the Provider State callback
    function).

    [Rust
    `pactffi_generator_generate_string`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_generator_generate_string)

    If anything goes wrong, it will return a NULL pointer.
    """
    ptr = lib.pactffi_generator_generate_string(
        generator._ptr,
        context_json.encode("utf-8"),
    )
    s = ffi.string(ptr)
    if isinstance(s, bytes):
        s = s.decode("utf-8")
    return s

generator_to_json(generator: Generator) -> str

Get the JSON form of the generator.

Rust pactffi_generator_to_json

The returned string must be deleted with pactffi_string_delete.

Safety

This function will fail if it is passed a NULL pointer, or the owner of the generator has been deleted.

Source code in src/pact/v3/ffi.py
def generator_to_json(generator: Generator) -> str:
    """
    Get the JSON form of the generator.

    [Rust
    `pactffi_generator_to_json`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_generator_to_json)

    The returned string must be deleted with `pactffi_string_delete`.

    # Safety

    This function will fail if it is passed a NULL pointer, or the owner of the
    generator has been deleted.
    """
    return OwnedString(lib.pactffi_generator_to_json(generator._ptr))

generators_iter_delete(iter: GeneratorCategoryIterator) -> None

Free the iterator when you're done using it.

Rust pactffi_generators_iter_delete

Source code in src/pact/v3/ffi.py
def generators_iter_delete(iter: GeneratorCategoryIterator) -> None:
    """
    Free the iterator when you're done using it.

    [Rust
    `pactffi_generators_iter_delete`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_generators_iter_delete)
    """
    lib.pactffi_generators_iter_delete(iter._ptr)

generators_iter_next(iter: GeneratorCategoryIterator) -> GeneratorKeyValuePair

Get the next path and generator out of the iterator, if possible.

Rust pactffi_generators_iter_next

The returned pointer must be deleted with pactffi_generator_iter_pair_delete.

RAISES DESCRIPTION
StopIteration

If the iterator has reached the end.

Source code in src/pact/v3/ffi.py
def generators_iter_next(iter: GeneratorCategoryIterator) -> GeneratorKeyValuePair:
    """
    Get the next path and generator out of the iterator, if possible.

    [Rust
    `pactffi_generators_iter_next`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_generators_iter_next)

    The returned pointer must be deleted with
    `pactffi_generator_iter_pair_delete`.

    Raises:
        StopIteration:
            If the iterator has reached the end.
    """
    ptr = lib.pactffi_generators_iter_next(iter._ptr)
    if ptr == ffi.NULL:
        raise StopIteration
    return GeneratorKeyValuePair(ptr)

generators_iter_pair_delete(pair: GeneratorKeyValuePair) -> None

Free a pair of key and value returned from pactffi_generators_iter_next.

Rust pactffi_generators_iter_pair_delete

Source code in src/pact/v3/ffi.py
def generators_iter_pair_delete(pair: GeneratorKeyValuePair) -> None:
    """
    Free a pair of key and value returned from `pactffi_generators_iter_next`.

    [Rust
    `pactffi_generators_iter_pair_delete`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_generators_iter_pair_delete)
    """
    lib.pactffi_generators_iter_pair_delete(pair._ptr)

get_error_message(length: int = 1024) -> str | None

Provide the error message from LAST_ERROR to the calling C code.

Rust pactffi_get_error_message

This function should be called after any other function in the pact_matching FFI indicates a failure with its own error message, if the caller wants to get more context on why the error happened.

Do note that this error-reporting mechanism only reports the top-level error message, not any source information embedded in the original Rust error type. If you want more detailed information for debugging purposes, use the logging interface.

PARAMETER DESCRIPTION
length

The length of the buffer to allocate for the error message. If the error message is longer than this, it will be truncated.

TYPE: int DEFAULT: 1024

RETURNS DESCRIPTION
str | None

A string containing the error message, or None if there is no error

str | None

message.

RAISES DESCRIPTION
RuntimeError

If the error message could not be retrieved.

Source code in src/pact/v3/ffi.py
def get_error_message(length: int = 1024) -> str | None:
    """
    Provide the error message from `LAST_ERROR` to the calling C code.

    [Rust
    `pactffi_get_error_message`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_get_error_message)

    This function should be called after any other function in the pact_matching
    FFI indicates a failure with its own error message, if the caller wants to
    get more context on why the error happened.

    Do note that this error-reporting mechanism only reports the top-level error
    message, not any source information embedded in the original Rust error
    type. If you want more detailed information for debugging purposes, use the
    logging interface.

    Args:
        length:
            The length of the buffer to allocate for the error message. If the
            error message is longer than this, it will be truncated.

    Returns:
        A string containing the error message, or None if there is no error
        message.

    Raises:
        RuntimeError:
            If the error message could not be retrieved.
    """
    buffer = ffi.new("char[]", length)
    ret: int = lib.pactffi_get_error_message(buffer, length)

    if ret >= 0:
        # While the documentation says that the return value is the number of bytes
        # written, the actually return value is always 0 on success.
        if msg := ffi.string(buffer):
            if isinstance(msg, bytes):
                return msg.decode("utf-8")
            return msg
        return None
    if ret == -1:
        msg = "The provided buffer is a null pointer."
    elif ret == -2:  # noqa: PLR2004
        # Instead of returning an error here, we call the function again with a
        # larger buffer.
        return get_error_message(length * 32)
    elif ret == -3:  # noqa: PLR2004
        msg = "The write failed for some other reason."
    elif ret == -4:  # noqa: PLR2004
        msg = "The error message had an interior NULL."
    else:
        msg = "An unknown error occurred."
    raise RuntimeError(msg)

get_tls_ca_certificate() -> OwnedString

Fetch the CA Certificate used to generate the self-signed certificate.

Rust pactffi_get_tls_ca_certificate

NOTE: The string for the result is allocated on the heap, and will have to be freed by the caller using pactffi_string_delete.

Errors

An empty string indicates an error reading the pem file.

Source code in src/pact/v3/ffi.py
def get_tls_ca_certificate() -> OwnedString:
    """
    Fetch the CA Certificate used to generate the self-signed certificate.

    [Rust
    `pactffi_get_tls_ca_certificate`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_get_tls_ca_certificate)

    **NOTE:** The string for the result is allocated on the heap, and will have
    to be freed by the caller using pactffi_string_delete.

    # Errors

    An empty string indicates an error reading the pem file.
    """
    return OwnedString(lib.pactffi_get_tls_ca_certificate())

given(interaction: InteractionHandle, description: str) -> None

Adds a provider state to the Interaction.

Rust pactffi_given

PARAMETER DESCRIPTION
interaction

Handle to the Interaction.

TYPE: InteractionHandle

description

The provider state description. It needs to be unique.

TYPE: str

RAISES DESCRIPTION
RuntimeError

If the provider state could not be specified.

Source code in src/pact/v3/ffi.py
def given(interaction: InteractionHandle, description: str) -> None:
    """
    Adds a provider state to the Interaction.

    [Rust
    `pactffi_given`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_given)

    Args:
        interaction:
            Handle to the Interaction.

        description:
            The provider state description. It needs to be unique.

    Raises:
        RuntimeError:
            If the provider state could not be specified.
    """
    success: bool = lib.pactffi_given(interaction._ref, description.encode("utf-8"))
    if not success:
        msg = "The provider state could not be specified."
        raise RuntimeError(msg)

given_with_param(interaction: InteractionHandle, description: str, name: str, value: str) -> None

Adds a parameter key and value to a provider state to the Interaction.

If the provider state does not exist, a new one will be created, otherwise the parameter will be merged into the existing one. The parameter value will be parsed as JSON.

Rust pactffi_given_with_param

PARAMETER DESCRIPTION
interaction

Handle to the Interaction.

TYPE: InteractionHandle

description

The provider state description.

TYPE: str

name

Parameter name.

TYPE: str

value

Parameter value as JSON.

TYPE: str

RAISES DESCRIPTION
RuntimeError

If the interaction state could not be updated.

Source code in src/pact/v3/ffi.py
def given_with_param(
    interaction: InteractionHandle,
    description: str,
    name: str,
    value: str,
) -> None:
    """
    Adds a parameter key and value to a provider state to the Interaction.

    If the provider state does not exist, a new one will be created, otherwise
    the parameter will be merged into the existing one. The parameter value will
    be parsed as JSON.

    [Rust
    `pactffi_given_with_param`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_given_with_param)

    Args:
        interaction:
            Handle to the Interaction.

        description:
            The provider state description.

        name:
            Parameter name.

        value:
            Parameter value as JSON.

    Raises:
        RuntimeError:
            If the interaction state could not be updated.
    """
    success: bool = lib.pactffi_given_with_param(
        interaction._ref,
        description.encode("utf-8"),
        name.encode("utf-8"),
        value.encode("utf-8"),
    )
    if not success:
        msg = "The interaction state could not be updated."
        raise RuntimeError(msg)

given_with_params(interaction: InteractionHandle, description: str, params: str) -> None

Adds a provider state to the Interaction.

If the params is not an JSON object, it will add it as a single parameter with a value key.

Rust pactffi_given_with_params

PARAMETER DESCRIPTION
interaction

Handle to the Interaction.

TYPE: InteractionHandle

description

The provider state description.

TYPE: str

params

Parameter values as a JSON fragment.

TYPE: str

RAISES DESCRIPTION
RuntimeError

If the interaction state could not be updated.

Source code in src/pact/v3/ffi.py
def given_with_params(
    interaction: InteractionHandle,
    description: str,
    params: str,
) -> None:
    """
    Adds a provider state to the Interaction.

    If the params is not an JSON object, it will add it as a single parameter
    with a `value` key.

    [Rust
    `pactffi_given_with_params`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_given_with_params)

    Args:
        interaction:
            Handle to the Interaction.

        description:
            The provider state description.

        params:
            Parameter values as a JSON fragment.

    Raises:
        RuntimeError:
            If the interaction state could not be updated.
    """
    ret: int = lib.pactffi_given_with_params(
        interaction._ref,
        description.encode("utf-8"),
        params.encode("utf-8"),
    )
    if ret == 0:
        return
    if ret == 1:
        msg = "The interaction state could not be updated."
    elif ret == 2:  # noqa: PLR2004
        msg = f"Internal error: {get_error_message()}"
    elif ret == 3:  # noqa: PLR2004
        msg = "Invalid C string."
    else:
        msg = "Unknown error."
    raise RuntimeError(msg)

handle_get_pact_spec_version(handle: PactHandle) -> PactSpecification

Fetches the Pact specification version for the given Pact model.

Rust pactffi_handle_get_pact_spec_version

PARAMETER DESCRIPTION
handle

Handle to a Pact model.

TYPE: PactHandle

RETURNS DESCRIPTION
PactSpecification

The spec version for the Pact model.

Source code in src/pact/v3/ffi.py
def handle_get_pact_spec_version(handle: PactHandle) -> PactSpecification:
    """
    Fetches the Pact specification version for the given Pact model.

    [Rust
    `pactffi_handle_get_pact_spec_version`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_handle_get_pact_spec_version)

    Args:
        handle:
            Handle to a Pact model.

    Returns:
        The spec version for the Pact model.
    """
    return PactSpecification(lib.pactffi_handle_get_pact_spec_version(handle._ref))

init(log_env_var: str) -> None

Initialise the mock server library.

This can provide an environment variable name to use to set the log levels. This function should only be called once, as it tries to install a global tracing subscriber.

Rust pactffi_init

Safety

log_env_var must be a valid NULL terminated UTF-8 string.

Source code in src/pact/v3/ffi.py
def init(log_env_var: str) -> None:
    """
    Initialise the mock server library.

    This can provide an environment variable name to use to set the log levels.
    This function should only be called once, as it tries to install a global
    tracing subscriber.

    [Rust
    `pactffi_init`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_init)

    # Safety

    log_env_var must be a valid NULL terminated UTF-8 string.
    """
    raise NotImplementedError

init_with_log_level(level: str = 'INFO') -> None

Initialises logging, and sets the log level explicitly.

This function should only be called once, as it tries to install a global tracing subscriber.

Rust pactffi_init_with_log_level

PARAMETER DESCRIPTION
level

One of TRACE, DEBUG, INFO, WARN, ERROR, NONE/OFF. Case-insensitive.

TYPE: str DEFAULT: 'INFO'

Safety

Exported functions are inherently unsafe.

Source code in src/pact/v3/ffi.py
def init_with_log_level(level: str = "INFO") -> None:
    """
    Initialises logging, and sets the log level explicitly.

    This function should only be called once, as it tries to install a global
    tracing subscriber.

    [Rust
    `pactffi_init_with_log_level`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_init_with_log_level)

    Args:
        level:
            One of TRACE, DEBUG, INFO, WARN, ERROR, NONE/OFF. Case-insensitive.

    # Safety

    Exported functions are inherently unsafe.
    """
    raise NotImplementedError

interaction_contents(interaction: InteractionHandle, part: InteractionPart, content_type: str, contents: str) -> None

Setup the interaction part using a plugin.

The contents is a JSON string that will be passed on to the plugin to configure the interaction part. Refer to the plugin documentation on the format of the JSON contents.

Rust pactffi_interaction_contents

PARAMETER DESCRIPTION
interaction

Handle to the interaction to configure.

TYPE: InteractionHandle

part

The part of the interaction to configure (request or response). It is ignored for messages.

TYPE: InteractionPart

content_type

Mime type of the contents.

TYPE: str

contents

JSON contents that gets passed to the plugin.

TYPE: str

RAISES DESCRIPTION
RuntimeError

If the interaction could not be configured

Source code in src/pact/v3/ffi.py
def interaction_contents(
    interaction: InteractionHandle,
    part: InteractionPart,
    content_type: str,
    contents: str,
) -> None:
    """
    Setup the interaction part using a plugin.

    The contents is a JSON string that will be passed on to the plugin to
    configure the interaction part. Refer to the plugin documentation on the
    format of the JSON contents.

    [Rust
    `pactffi_interaction_contents`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_interaction_contents)

    Args:
        interaction:
            Handle to the interaction to configure.

        part:
            The part of the interaction to configure (request or response). It
            is ignored for messages.

        content_type:
            Mime type of the contents.

        contents:
            JSON contents that gets passed to the plugin.

    Raises:
        RuntimeError:
            If the interaction could not be configured
    """
    ret: int = lib.pactffi_interaction_contents(
        interaction._ref,
        part.value,
        content_type.encode("utf-8"),
        contents.encode("utf-8"),
    )
    if ret == 0:
        return
    if ret == 1:
        msg = f"A general panic was caught: {get_error_message()}"
    if ret == 2:  # noqa: PLR2004
        msg = "The mock server has already been started."
    if ret == 3:  # noqa: PLR2004
        msg = f"The interaction handle {interaction} is invalid."
    if ret == 4:  # noqa: PLR2004
        msg = f"The content type {content_type} is not valid."
    if ret == 5:  # noqa: PLR2004
        msg = "The content is not valid JSON."
    if ret == 6:  # noqa: PLR2004
        msg = f"The plugin returned an error: {get_error_message()}"
    else:
        msg = f"There was an unknown error configuring the interaction: {ret}"
    raise RuntimeError(msg)

interaction_test_name(interaction: InteractionHandle, test_name: str) -> None

Sets the test name annotation for the interaction.

This allows capturing the name of the test as metadata. This can only be used with V4 interactions.

Rust pactffi_interaction_test_name

PARAMETER DESCRIPTION
interaction

Handle to the Interaction.

TYPE: InteractionHandle

test_name

The test name to set.

TYPE: str

RAISES DESCRIPTION
RuntimeError

If the test name can not be set.

Source code in src/pact/v3/ffi.py
def interaction_test_name(interaction: InteractionHandle, test_name: str) -> None:
    """
    Sets the test name annotation for the interaction.

    This allows capturing the name of the test as metadata. This can only be
    used with V4 interactions.

    [Rust
    `pactffi_interaction_test_name`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_interaction_test_name)

    Args:
        interaction:
            Handle to the Interaction.

        test_name:
            The test name to set.

    Raises:
        RuntimeError:
            If the test name can not be set.

    """
    ret: int = lib.pactffi_interaction_test_name(
        interaction._ref,
        test_name.encode("utf-8"),
    )
    if ret == 0:
        return
    if ret == 1:
        msg = f"Function panicked: {get_error_message()}"
    elif ret == 2:  # noqa: PLR2004
        msg = f"Invalid handle: {interaction}."
    elif ret == 3:  # noqa: PLR2004
        msg = f"Mock server for {interaction} has already started."
    elif ret == 4:  # noqa: PLR2004
        msg = f"Interaction {interaction} is not a V4 interaction."
    else:
        msg = f"Unknown error setting test name for {interaction}."
    raise RuntimeError(msg)

log_message(message: str, log_level: LevelFilter | str = LevelFilter.ERROR, source: str | None = None) -> None

Log using the shared core logging facility.

Rust pactffi_log_message

This is useful for callers to have a single set of logs.

PARAMETER DESCRIPTION
message

The contents written to the log

TYPE: str

log_level

The verbosity at which this message should be logged.

TYPE: LevelFilter | str DEFAULT: ERROR

source

The source of the log, such as the class, module or caller.

TYPE: str | None DEFAULT: None

Source code in src/pact/v3/ffi.py
def log_message(
    message: str,
    log_level: LevelFilter | str = LevelFilter.ERROR,
    source: str | None = None,
) -> None:
    """
    Log using the shared core logging facility.

    [Rust
    `pactffi_log_message`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_log_message)

    This is useful for callers to have a single set of logs.

    Args:
        message:
            The contents written to the log

        log_level:
            The verbosity at which this message should be logged.

        source:
            The source of the log, such as the class, module or caller.
    """
    if isinstance(log_level, str):
        log_level = LevelFilter[log_level.upper()]
    if source is None:
        import inspect

        source = inspect.stack()[1].function
    lib.pactffi_log_message(
        source.encode("utf-8"),
        log_level.name.encode("utf-8"),
        message.encode("utf-8"),
    )

log_to_buffer(level_filter: LevelFilter | str = LevelFilter.ERROR) -> None

Convenience function to direct all logging to a task local memory buffer.

Rust pactffi_log_to_buffer

RAISES DESCRIPTION
RuntimeError

If there was an error setting the logger.

Source code in src/pact/v3/ffi.py
def log_to_buffer(level_filter: LevelFilter | str = LevelFilter.ERROR) -> None:
    """
    Convenience function to direct all logging to a task local memory buffer.

    [Rust `pactffi_log_to_buffer`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_log_to_buffer)

    Raises:
        RuntimeError:
            If there was an error setting the logger.
    """
    if isinstance(level_filter, str):
        level_filter = LevelFilter[level_filter.upper()]
    ret: int = lib.pactffi_log_to_buffer(level_filter.value)
    if ret != 0:
        msg = "There was an unknown error setting the logger."
        raise RuntimeError(msg)

log_to_file(file_name: str, level_filter: LevelFilter) -> int

Convenience function to direct all logging to a file.

Rust pactffi_log_to_file

Safety

This function will fail if the file_name pointer is invalid or does not point to a NULL terminated string.

Source code in src/pact/v3/ffi.py
def log_to_file(file_name: str, level_filter: LevelFilter) -> int:
    """
    Convenience function to direct all logging to a file.

    [Rust
    `pactffi_log_to_file`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_log_to_file)

    # Safety

    This function will fail if the file_name pointer is invalid or does not
    point to a NULL terminated string.
    """
    raise NotImplementedError

log_to_stderr(level_filter: LevelFilter | str = LevelFilter.ERROR) -> None

Convenience function to direct all logging to stderr.

Rust pactffi_log_to_stderr

PARAMETER DESCRIPTION
level_filter

The level of logs to filter to. If a string is given, it must match one of the LevelFilter values (case insensitive).

TYPE: LevelFilter | str DEFAULT: ERROR

RAISES DESCRIPTION
RuntimeError

If there was an error setting the logger.

Source code in src/pact/v3/ffi.py
def log_to_stderr(level_filter: LevelFilter | str = LevelFilter.ERROR) -> None:
    """
    Convenience function to direct all logging to stderr.

    [Rust
    `pactffi_log_to_stderr`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_log_to_stderr)

    Args:
        level_filter:
            The level of logs to filter to. If a string is given, it must match
            one of the [`LevelFilter`][pact.v3.ffi.LevelFilter] values (case
            insensitive).

    Raises:
        RuntimeError:
            If there was an error setting the logger.
    """
    if isinstance(level_filter, str):
        level_filter = LevelFilter[level_filter.upper()]
    ret: int = lib.pactffi_log_to_stderr(level_filter.value)
    if ret != 0:
        msg = "There was an unknown error setting the logger."
        raise RuntimeError(msg)

log_to_stdout(level_filter: LevelFilter) -> int

Convenience function to direct all logging to stdout.

Rust pactffi_log_to_stdout

Source code in src/pact/v3/ffi.py
def log_to_stdout(level_filter: LevelFilter) -> int:
    """
    Convenience function to direct all logging to stdout.

    [Rust `pactffi_log_to_stdout`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_log_to_stdout)
    """
    raise NotImplementedError

logger_apply() -> int

Apply the previously configured sinks and levels to the program.

Rust pactffi_logger_apply

If no sinks have been setup, will set the log level to info and the target to standard out.

This function will install a global tracing subscriber. Any attempts to modify the logger after the call to logger_apply will fail.

Source code in src/pact/v3/ffi.py
def logger_apply() -> int:
    """
    Apply the previously configured sinks and levels to the program.

    [Rust
    `pactffi_logger_apply`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_logger_apply)

    If no sinks have been setup, will set the log level to info and the target
    to standard out.

    This function will install a global tracing subscriber. Any attempts to
    modify the logger after the call to `logger_apply` will fail.
    """
    raise NotImplementedError

logger_attach_sink(sink_specifier: str, level_filter: LevelFilter) -> int

Attach an additional sink to the thread-local logger.

Rust pactffi_logger_attach_sink

This logger does nothing until pactffi_logger_apply has been called.

Types of sinks can be specified:

  • stdout (pactffi_logger_attach_sink("stdout", LevelFilter_Info))
  • stderr (pactffi_logger_attach_sink("stderr", LevelFilter_Debug))
  • file w/ file path (pactffi_logger_attach_sink("file /some/file/path", LevelFilter_Trace))
  • buffer (pactffi_logger_attach_sink("buffer", LevelFilter_Debug))

Usage

int result = pactffi_logger_attach_sink("file /some/file/path", LogLevel_Filter);

Error Handling

The return error codes are as follows:

  • -1: Can't set logger (applying the logger failed, perhaps because one is applied already).
  • -2: No logger has been initialized (call pactffi_logger_init before any other log function).
  • -3: The sink specifier was not UTF-8 encoded.
  • -4: The sink type specified is not a known type (known types: "stdout", "stderr", or "file /some/path").
  • -5: No file path was specified in a file-type sink specification.
  • -6: Opening a sink to the specified file path failed (check permissions).

Safety

This function checks the validity of the passed-in sink specifier, and errors out if the specifier isn't valid UTF-8. Passing in an invalid or NULL pointer will result in undefined behaviour.

Source code in src/pact/v3/ffi.py
def logger_attach_sink(sink_specifier: str, level_filter: LevelFilter) -> int:
    """
    Attach an additional sink to the thread-local logger.

    [Rust
    `pactffi_logger_attach_sink`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_logger_attach_sink)

    This logger does nothing until `pactffi_logger_apply` has been called.

    Types of sinks can be specified:

    - stdout (`pactffi_logger_attach_sink("stdout", LevelFilter_Info)`)
    - stderr (`pactffi_logger_attach_sink("stderr", LevelFilter_Debug)`)
    - file w/ file path (`pactffi_logger_attach_sink("file /some/file/path",
      LevelFilter_Trace)`)
    - buffer (`pactffi_logger_attach_sink("buffer", LevelFilter_Debug)`)

    # Usage

    ```c
    int result = pactffi_logger_attach_sink("file /some/file/path", LogLevel_Filter);
    ```

    # Error Handling

    The return error codes are as follows:

    - `-1`: Can't set logger (applying the logger failed, perhaps because one is
      applied already).
    - `-2`: No logger has been initialized (call `pactffi_logger_init` before
      any other log function).
    - `-3`: The sink specifier was not UTF-8 encoded.
    - `-4`: The sink type specified is not a known type (known types: "stdout",
      "stderr", or "file /some/path").
    - `-5`: No file path was specified in a file-type sink specification.
    - `-6`: Opening a sink to the specified file path failed (check
      permissions).

    # Safety

    This function checks the validity of the passed-in sink specifier, and
    errors out if the specifier isn't valid UTF-8. Passing in an invalid or NULL
    pointer will result in undefined behaviour.
    """
    raise NotImplementedError

logger_init() -> None

Initialize the FFI logger with no sinks.

Rust pactffi_logger_init

This initialized logger does nothing until pactffi_logger_apply has been called.

Usage

pactffi_logger_init();

Safety

This function is always safe to call.

Source code in src/pact/v3/ffi.py
def logger_init() -> None:
    """
    Initialize the FFI logger with no sinks.

    [Rust `pactffi_logger_init`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_logger_init)

    This initialized logger does nothing until `pactffi_logger_apply` has been called.

    # Usage

    ```c
    pactffi_logger_init();
    ```

    # Safety

    This function is always safe to call.
    """
    raise NotImplementedError

matcher_definition_delete(definition: MatchingRuleDefinitionResult) -> None

Frees the memory used by the result of parsing the matching definition expression.

Rust pactffi_matcher_definition_delete

Source code in src/pact/v3/ffi.py
def matcher_definition_delete(definition: MatchingRuleDefinitionResult) -> None:
    """
    Frees the memory used by the result of parsing the matching definition expression.

    [Rust `pactffi_matcher_definition_delete`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_matcher_definition_delete)
    """
    raise NotImplementedError

matcher_definition_error(definition: MatchingRuleDefinitionResult) -> str

Returns any error message from parsing a matching definition expression.

If there is no error, it will return a NULL pointer, otherwise returns the error message as a NULL-terminated string. The returned string must be freed using the pactffi_string_delete function once done with it.

Rust pactffi_matcher_definition_error

Source code in src/pact/v3/ffi.py
def matcher_definition_error(definition: MatchingRuleDefinitionResult) -> str:
    """
    Returns any error message from parsing a matching definition expression.

    If there is no error, it will return a NULL pointer, otherwise returns the
    error message as a NULL-terminated string. The returned string must be freed
    using the `pactffi_string_delete` function once done with it.

    [Rust
    `pactffi_matcher_definition_error`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_matcher_definition_error)
    """
    raise NotImplementedError

matcher_definition_generator(definition: MatchingRuleDefinitionResult) -> Generator

Returns the generator from parsing a matching definition expression.

If there was an error or there is no associated generator, it will return a NULL pointer, otherwise returns the generator as a pointer.

Rust pactffi_matcher_definition_generator

The generator pointer will be a valid pointer as long as pactffi_matcher_definition_delete has not been called on the definition. Using the generator pointer after the definition has been deleted will result in undefined behaviour.

Source code in src/pact/v3/ffi.py
def matcher_definition_generator(definition: MatchingRuleDefinitionResult) -> Generator:
    """
    Returns the generator from parsing a matching definition expression.

    If there was an error or there is no associated generator, it will return a
    NULL pointer, otherwise returns the generator as a pointer.

    [Rust
    `pactffi_matcher_definition_generator`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_matcher_definition_generator)

    The generator pointer will be a valid pointer as long as
    `pactffi_matcher_definition_delete` has not been called on the definition.
    Using the generator pointer after the definition has been deleted will
    result in undefined behaviour.
    """
    raise NotImplementedError

matcher_definition_iter(definition: MatchingRuleDefinitionResult) -> MatchingRuleIterator

Returns an iterator over the matching rules from the parsed definition.

The iterator needs to be deleted with the pactffi_matching_rule_iter_delete function once done with it.

Rust pactffi_matcher_definition_iter

If there was an error parsing the expression, this function will return a NULL pointer.

Source code in src/pact/v3/ffi.py
def matcher_definition_iter(
    definition: MatchingRuleDefinitionResult,
) -> MatchingRuleIterator:
    """
    Returns an iterator over the matching rules from the parsed definition.

    The iterator needs to be deleted with the
    `pactffi_matching_rule_iter_delete` function once done with it.

    [Rust
    `pactffi_matcher_definition_iter`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_matcher_definition_iter)

    If there was an error parsing the expression, this function will return a
    NULL pointer.
    """
    raise NotImplementedError

matcher_definition_value(definition: MatchingRuleDefinitionResult) -> str

Returns the value from parsing a matching definition expression.

If there was an error, it will return a NULL pointer, otherwise returns the value as a NULL-terminated string. The returned string must be freed using the pactffi_string_delete function once done with it.

Rust pactffi_matcher_definition_value

Note that different expressions values can have types other than a string. Use pactffi_matcher_definition_value_type to get the actual type of the value. This function will always return the string representation of the value.

Source code in src/pact/v3/ffi.py
def matcher_definition_value(definition: MatchingRuleDefinitionResult) -> str:
    """
    Returns the value from parsing a matching definition expression.

    If there was an error, it will return a NULL pointer, otherwise returns the
    value as a NULL-terminated string. The returned string must be freed using
    the `pactffi_string_delete` function once done with it.

    [Rust
    `pactffi_matcher_definition_value`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_matcher_definition_value)

    Note that different expressions values can have types other than a string.
    Use `pactffi_matcher_definition_value_type` to get the actual type of the
    value. This function will always return the string representation of the
    value.
    """
    raise NotImplementedError

matcher_definition_value_type(definition: MatchingRuleDefinitionResult) -> ExpressionValueType

Returns the type of the value from parsing a matching definition expression.

If there was an error parsing the expression, it will return Unknown.

Rust pactffi_matcher_definition_value_type

Source code in src/pact/v3/ffi.py
def matcher_definition_value_type(
    definition: MatchingRuleDefinitionResult,
) -> ExpressionValueType:
    """
    Returns the type of the value from parsing a matching definition expression.

    If there was an error parsing the expression, it will return Unknown.

    [Rust
    `pactffi_matcher_definition_value_type`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_matcher_definition_value_type)
    """
    raise NotImplementedError

matches_binary_value(matching_rule: MatchingRule, expected_value: str, expected_value_len: int, actual_value: str, actual_value_len: int, cascaded: int) -> OwnedString

Determines if the binary value matches the given matching rule.

If the value matches OK, will return a NULL pointer. If the value does not match, will return a error message as a NULL terminated string. The error message pointer will need to be deleted with the pactffi_string_delete function once it is no longer required.

Rust pactffi_matches_binary_value

  • matching_rule - pointer to a matching rule
  • expected_value - value we expect to get
  • expected_value_len - length of the expected value bytes
  • actual_value - value to match
  • actual_value_len - length of the actual value bytes
  • cascaded - if the matching rule has been cascaded from a parent. 0 == false, 1 == true

Safety

The matching rule, expected value and actual value pointers must be a valid pointers. expected_value_len and actual_value_len must contain the number of bytes that the value pointers point to. Passing invalid lengths can lead to undefined behaviour.

Source code in src/pact/v3/ffi.py
def matches_binary_value(  # noqa: PLR0913
    matching_rule: MatchingRule,
    expected_value: str,
    expected_value_len: int,
    actual_value: str,
    actual_value_len: int,
    cascaded: int,
) -> OwnedString:
    """
    Determines if the binary value matches the given matching rule.

    If the value matches OK, will return a NULL pointer. If the value does not
    match, will return a error message as a NULL terminated string. The error
    message pointer will need to be deleted with the `pactffi_string_delete`
    function once it is no longer required.

    [Rust
    `pactffi_matches_binary_value`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_matches_binary_value)

    * matching_rule - pointer to a matching rule
    * expected_value - value we expect to get
    * expected_value_len - length of the expected value bytes
    * actual_value - value to match
    * actual_value_len - length of the actual value bytes
    * cascaded - if the matching rule has been cascaded from a parent. 0 ==
      false, 1 == true

    # Safety

    The matching rule, expected value and actual value pointers must be a valid
    pointers. expected_value_len and actual_value_len must contain the number of
    bytes that the value pointers point to. Passing invalid lengths can lead to
    undefined behaviour.
    """
    raise NotImplementedError

matches_bool_value(matching_rule: MatchingRule, expected_value: int, actual_value: int, cascaded: int) -> OwnedString

Determines if the boolean value matches the given matching rule.

If the value matches OK, will return a NULL pointer. If the value does not match, will return a error message as a NULL terminated string. The error message pointer will need to be deleted with the pactffi_string_delete function once it is no longer required.

Rust pactffi_matches_bool_value

  • matching_rule - pointer to a matching rule
  • expected_value - value we expect to get, 0 == false and 1 == true
  • actual_value - value to match, 0 == false and 1 == true
  • cascaded - if the matching rule has been cascaded from a parent. 0 == false, 1 == true

Safety

The matching rule pointer must be a valid pointer.

Source code in src/pact/v3/ffi.py
def matches_bool_value(
    matching_rule: MatchingRule,
    expected_value: int,
    actual_value: int,
    cascaded: int,
) -> OwnedString:
    """
    Determines if the boolean value matches the given matching rule.

    If the value matches OK, will return a NULL pointer. If the value does not
    match, will return a error message as a NULL terminated string. The error
    message pointer will need to be deleted with the `pactffi_string_delete`
    function once it is no longer required.

    [Rust
    `pactffi_matches_bool_value`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_matches_bool_value)

    * matching_rule - pointer to a matching rule
    * expected_value - value we expect to get, 0 == false and 1 == true
    * actual_value - value to match, 0 == false and 1 == true
    * cascaded - if the matching rule has been cascaded from a parent. 0 ==
      false, 1 == true

    # Safety

    The matching rule pointer must be a valid pointer.
    """
    raise NotImplementedError

matches_f64_value(matching_rule: MatchingRule, expected_value: float, actual_value: float, cascaded: int) -> OwnedString

Determines if the floating point value matches the given matching rule.

If the value matches OK, will return a NULL pointer. If the value does not match, will return a error message as a NULL terminated string. The error message pointer will need to be deleted with the pactffi_string_delete function once it is no longer required.

Rust pactffi_matches_f64_value

  • matching_rule - pointer to a matching rule
  • expected_value - value we expect to get
  • actual_value - value to match
  • cascaded - if the matching rule has been cascaded from a parent. 0 == false, 1 == true

Safety

The matching rule pointer must be a valid pointer.

Source code in src/pact/v3/ffi.py
def matches_f64_value(
    matching_rule: MatchingRule,
    expected_value: float,
    actual_value: float,
    cascaded: int,
) -> OwnedString:
    """
    Determines if the floating point value matches the given matching rule.

    If the value matches OK, will return a NULL pointer. If the value does not
    match, will return a error message as a NULL terminated string. The error
    message pointer will need to be deleted with the `pactffi_string_delete`
    function once it is no longer required.

    [Rust
    `pactffi_matches_f64_value`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_matches_f64_value)

    * matching_rule - pointer to a matching rule
    * expected_value - value we expect to get
    * actual_value - value to match
    * cascaded - if the matching rule has been cascaded from a parent. 0 ==
      false, 1 == true

    # Safety

    The matching rule pointer must be a valid pointer.
    """
    raise NotImplementedError

matches_i64_value(matching_rule: MatchingRule, expected_value: int, actual_value: int, cascaded: int) -> OwnedString

Determines if the signed integer value matches the given matching rule.

If the value matches OK, will return a NULL pointer. If the value does not match, will return a error message as a NULL terminated string. The error message pointer will need to be deleted with the pactffi_string_delete function once it is no longer required.

Rust pactffi_matches_i64_value

  • matching_rule - pointer to a matching rule
  • expected_value - value we expect to get
  • actual_value - value to match
  • cascaded - if the matching rule has been cascaded from a parent. 0 == false, 1 == true

Safety

The matching rule pointer must be a valid pointer.

Source code in src/pact/v3/ffi.py
def matches_i64_value(
    matching_rule: MatchingRule,
    expected_value: int,
    actual_value: int,
    cascaded: int,
) -> OwnedString:
    """
    Determines if the signed integer value matches the given matching rule.

    If the value matches OK, will return a NULL pointer. If the value does not
    match, will return a error message as a NULL terminated string. The error
    message pointer will need to be deleted with the `pactffi_string_delete`
    function once it is no longer required.

    [Rust
    `pactffi_matches_i64_value`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_matches_i64_value)

    * matching_rule - pointer to a matching rule
    * expected_value - value we expect to get
    * actual_value - value to match
    * cascaded - if the matching rule has been cascaded from a parent. 0 ==
      false, 1 == true

    # Safety

    The matching rule pointer must be a valid pointer.
    """
    raise NotImplementedError

matches_json_value(matching_rule: MatchingRule, expected_value: str, actual_value: str, cascaded: int) -> OwnedString

Determines if the JSON value matches the given matching rule.

If the value matches OK, will return a NULL pointer. If the value does not match, will return a error message as a NULL terminated string. The error message pointer will need to be deleted with the pactffi_string_delete function once it is no longer required.

Rust pactffi_matches_json_value

  • matching_rule - pointer to a matching rule
  • expected_value - value we expect to get as a NULL terminated string
  • actual_value - value to match as a NULL terminated string
  • cascaded - if the matching rule has been cascaded from a parent. 0 == false, 1 == true

Safety

The matching rule pointer must be a valid pointer, and the value parameters must be valid pointers to a NULL terminated strings.

Source code in src/pact/v3/ffi.py
def matches_json_value(
    matching_rule: MatchingRule,
    expected_value: str,
    actual_value: str,
    cascaded: int,
) -> OwnedString:
    """
    Determines if the JSON value matches the given matching rule.

    If the value matches OK, will return a NULL pointer. If the value does not
    match, will return a error message as a NULL terminated string. The error
    message pointer will need to be deleted with the `pactffi_string_delete`
    function once it is no longer required.

    [Rust
    `pactffi_matches_json_value`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_matches_json_value)

    * matching_rule - pointer to a matching rule
    * expected_value - value we expect to get as a NULL terminated string
    * actual_value - value to match as a NULL terminated string
    * cascaded - if the matching rule has been cascaded from a parent. 0 ==
      false, 1 == true

    # Safety

    The matching rule pointer must be a valid pointer, and the value parameters
    must be valid pointers to a NULL terminated strings.
    """
    raise NotImplementedError

matches_string_value(matching_rule: MatchingRule, expected_value: str, actual_value: str, cascaded: int) -> OwnedString

Determines if the string value matches the given matching rule.

If the value matches OK, will return a NULL pointer. If the value does not match, will return a error message as a NULL terminated string. The error message pointer will need to be deleted with the pactffi_string_delete function once it is no longer required.

Rust pactffi_matches_string_value

  • matching_rule - pointer to a matching rule
  • expected_value - value we expect to get as a NULL terminated string
  • actual_value - value to match as a NULL terminated string
  • cascaded - if the matching rule has been cascaded from a parent. 0 == false, 1 == true

Safety

The matching rule pointer must be a valid pointer, and the value parameters must be valid pointers to a NULL terminated strings.

Source code in src/pact/v3/ffi.py
def matches_string_value(
    matching_rule: MatchingRule,
    expected_value: str,
    actual_value: str,
    cascaded: int,
) -> OwnedString:
    """
    Determines if the string value matches the given matching rule.

    If the value matches OK, will return a NULL pointer. If the value does not
    match, will return a error message as a NULL terminated string. The error
    message pointer will need to be deleted with the `pactffi_string_delete`
    function once it is no longer required.

    [Rust
    `pactffi_matches_string_value`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_matches_string_value)

    * matching_rule - pointer to a matching rule
    * expected_value - value we expect to get as a NULL terminated string
    * actual_value - value to match as a NULL terminated string
    * cascaded - if the matching rule has been cascaded from a parent. 0 ==
      false, 1 == true

    # Safety

    The matching rule pointer must be a valid pointer, and the value parameters
    must be valid pointers to a NULL terminated strings.
    """
    raise NotImplementedError

matches_u64_value(matching_rule: MatchingRule, expected_value: int, actual_value: int, cascaded: int) -> OwnedString

Determines if the unsigned integer value matches the given matching rule.

If the value matches OK, will return a NULL pointer. If the value does not match, will return a error message as a NULL terminated string. The error message pointer will need to be deleted with the pactffi_string_delete function once it is no longer required.

Rust pactffi_matches_u64_value

  • matching_rule - pointer to a matching rule
  • expected_value - value we expect to get
  • actual_value - value to match
  • cascaded - if the matching rule has been cascaded from a parent. 0 == false, 1 == true

Safety

The matching rule pointer must be a valid pointer.

Source code in src/pact/v3/ffi.py
def matches_u64_value(
    matching_rule: MatchingRule,
    expected_value: int,
    actual_value: int,
    cascaded: int,
) -> OwnedString:
    """
    Determines if the unsigned integer value matches the given matching rule.

    If the value matches OK, will return a NULL pointer. If the value does not
    match, will return a error message as a NULL terminated string. The error
    message pointer will need to be deleted with the `pactffi_string_delete`
    function once it is no longer required.

    [Rust
    `pactffi_matches_u64_value`](https://docs.rs/pact_ffi/0.4.22/pact_ffi/?search=pactffi_matches_u64_value)

    * matching_rule - pointer to a matching rule
    * expected_value - value we expect to get
    * actual_value - value to match
    * cascaded - if the matching rule has been cascaded from a parent. 0 ==
      false, 1 == true

    # Safety

    The matching rule pointer must be a valid pointer.
    """
    raise NotImplementedError

matching_rule_id(rule_result: MatchingRuleResult) -> int

Return the ID of the matching rule.

Rust pactffi_matching_rule_id

The ID corresponds to the following rules:

Rule ID
Equality 1
Regex 2
Type 3
MinType 4
MaxType 5
MinMaxType 6
Timestamp 7
Time 8
Date 9
Include 10
Number 11
Integer 12
Decimal 13
Null 14
ContentType 15
ArrayContains 16
Values 17
Boolean 18
StatusCode 19
NotEmpty 20
Semver 21
EachKey 22
EachValue 23

Safety

This function is safe as long as the MatchingRuleResult pointer is a valid pointer and the iterator has not been deleted.

Source code in src/pact/v3/ffi.py