Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/consumer.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,19 @@ Common matcher types include:
- **Pattern matchers**: `match.regex()`, `match.uuid()` - validate specific formats
- **Collection matchers**: `match.each_like()`, `match.array_containing()` - handle arrays and objects
- **Date/time matchers**: `match.date()`, `match.time()`, `match.datetime()` - flexible timestamp handling
- **Alternative matchers**: `match.any_of()` (or the `|` operator), `match.nullable()` - accept a value matching any one of several matchers

```python
response = {
"nickname": match.nullable(match.str("Al")), # a string or null
"address": match.nullable({ # an object or null
"street": match.str("Main St"),
"number": match.int(42), # still applied when the address is present
}),
}
```

Only the example value is used in the consumer test, so the code under test only ever sees an address object; the `null` alternative is only checked during provider verification. Alternative matchers require a version of the Pact FFI with support for `pact:matcher:combine` ([pact-reference#601](https://github.com/pact-foundation/pact-reference/pull/601); TODO: minimum `pact_ffi` version).

Matchers ensure your contracts focus on data structure and semantics rather than brittle exact values, making tests more robust and maintainable.

Expand Down
7 changes: 6 additions & 1 deletion pact-python-ffi/hatch_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@
from collections.abc import Mapping, MutableMapping, Sequence

PKG_DIR = Path(__file__).parent.resolve() / "src" / "pact_ffi"
PACT_RELEASE_URL = "https://github.com/pact-foundation/pact-reference/releases/download/pact_ffi-v{version}"
# TEMP: fork prerelease, revert before merge.
PACT_RELEASE_URL = (
"https://github.com/YOU54F/pact-reference/releases/download/pact_ffi-v{version}"
)
PACT_FFI_VERSION_OVERRIDE = "0.5.13-or.1"


def _stable_abi() -> str:
Expand Down Expand Up @@ -133,6 +137,7 @@ def initialize(
incompatible platform).
"""
ffi_version = ".".join(self.metadata.version.split(".")[:3])
ffi_version = PACT_FFI_VERSION_OVERRIDE # TEMP: revert before merge
if not ffi_version:
msg = "Failed to determine Pact FFI version."
self.app.display_error(msg)
Expand Down
3 changes: 2 additions & 1 deletion pact-python-ffi/tests/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
def test_version() -> None:
assert isinstance(pact_ffi.version(), str)
assert len(pact_ffi.version()) > 0
assert pact_ffi.version().count(".") == 2
# TEMP: allow the 0.5.13-or.1 prerelease suffix, revert before merge.
assert pact_ffi.version().split("-")[0].count(".") == 2


def test_string_result_ok() -> None:
Expand Down
123 changes: 123 additions & 0 deletions src/pact/match/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,52 @@
)
```

## Alternative Matchers

When a value may take one of several forms, use `match.any_of()` (or the `|`
operator) to combine matchers with a logical OR. The value must satisfy at least
one of the alternatives:

```python
response = {
# Either a numeric string or a UUID
"id": match.any_of(
match.regex("12345", regex=r"^\d+$"),
match.uuid(),
),
# Equivalent, using the `|` operator
"ref": match.regex("12345", regex=r"^\d+$") | match.uuid(),
}
```

A common case is a value that may be `null`. The `match.nullable()` helper
combines a matcher (or an example value) with `match.null()`. Matchers nested
within an object still apply to its children whenever the object is not `null`:

```python
response = {
"nickname": match.nullable(match.str("Al")),
"address": match.nullable({
"street": match.str("Main St"),
"number": match.int(42),
}),
}
```

/// warning
Only the example value (the first value provided) is used during the consumer
test. The other alternatives are written to the Pact file and checked during
provider verification, but are never exercised against the consumer code. In the
example above, the consumer only ever sees an address object, never `null`.
///

/// note
OR matchers require a version of the Pact FFI with support for the
`pact:matcher:combine` integration JSON attribute
([pact-reference#601](https://github.com/pact-foundation/pact-reference/pull/601)).
TODO: Replace with the first released `pact_ffi` version that includes it.
///

"""

from __future__ import annotations
Expand All @@ -255,6 +301,7 @@
EachKeyMatcher,
EachValueMatcher,
GenericMatcher,
OrMatcher,
)
from pact.types import UNSET, Matchable, Unset

Expand All @@ -280,6 +327,7 @@
# <https://github.com/pact-foundation/pact-reference/blob/303073c/rust/pact_models/src/matchingrules/mod.rs#L62>
__all__ = [
"AbstractMatcher",
"any_of",
"array_containing",
"bool",
"boolean",
Expand All @@ -296,6 +344,7 @@
"like",
"none",
"null",
"nullable",
"number",
"regex",
"str",
Expand Down Expand Up @@ -1122,3 +1171,77 @@ def each_value_matches(
if isinstance(rules, AbstractMatcher):
rules = [rules]
return EachValueMatcher(value=value, rules=rules)


def any_of(
*matchers: AbstractMatcher[Any],
value: Any = UNSET, # noqa: ANN401
) -> AbstractMatcher[Any]:
r"""
Match a value against any one of several matchers.

The matchers are combined with a logical OR, so the value must satisfy at
least one of them. This is equivalent to combining the matchers with the
`|` operator:

```python
match.any_of(match.int(1), match.regex("one", regex=r"^\w+$"))
match.int(1) | match.regex("one", regex=r"^\w+$")
```

Nested OR matchers are flattened into a single list of alternatives. An
AND matcher (created with `&`) cannot be used as an alternative.

/// warning
Only the example value is used during the consumer test; the other
alternatives are only checked during provider verification.
///

Args:
matchers:
Matchers to combine. At least two are required.

value:
Example value. If not provided, the value of the first matcher
which has a value is used. The value must not itself be a matcher.

Returns:
Matcher for values that match at least one of the given matchers.
"""
return OrMatcher(*matchers, value=value)


@overload
def nullable(value: AbstractMatcher[_T], /) -> AbstractMatcher[_T | None]: ...
@overload
def nullable(value: _T, /) -> AbstractMatcher[_T | None]: ...
def nullable(value: Any, /) -> AbstractMatcher[Any]:
"""
Match a value that is either `null` or matches the given value.

If a matcher is given, the value must match it or be `null`. If a plain
value is given, the value must match its type or be `null`; matchers
nested within a plain value (for example, a dictionary) still apply to its
children:

```python
match.nullable(match.str("Al"))
match.nullable({"street": match.str("Main St"), "number": match.int(42)})
```

/// warning
Only the example value is used during the consumer test, so the consumer
never sees `null`. The `null` alternative is only checked during provider
verification.
///

Args:
value:
Matcher or example value for the non-null case.

Returns:
Matcher for values that are either `null` or match the given value.
"""
if isinstance(value, AbstractMatcher):
return OrMatcher(value, none())
return OrMatcher(GenericMatcher("type"), none(), value=value)
160 changes: 159 additions & 1 deletion src/pact/match/matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,29 @@ def __and__(self, other: object) -> AndMatcher[Any]:
return AndMatcher(self, other)
return NotImplemented

def __or__(self, other: object) -> OrMatcher[Any]:
"""
Combine two matchers using a logical OR.

This allows for combining multiple matchers into a single matcher that
requires at least one of the conditions to be met. Chaining the
operator (`a | b | c`) produces a single, flat list of alternatives.

Only a single example value is supported when combining matchers. The
first value found will be used. See [`OrMatcher`][pact.match.matcher.OrMatcher]
for caveats.

Args:
other:
The other matcher to combine with.

Returns:
An `OrMatcher` that combines both matchers.
"""
if isinstance(other, AbstractMatcher):
return OrMatcher(self, other)
return NotImplemented


class GenericMatcher(AbstractMatcher[_T_co]):
"""
Expand Down Expand Up @@ -372,6 +395,12 @@ def __init__(
Example value to match against. If not provided, the value
from the first matcher that has a value will be used.
"""
if any(isinstance(m, OrMatcher) for m in matchers):
msg = (
"An OrMatcher cannot be combined with other matchers using AND,"
" as Pact only supports a single combination per path."
)
raise TypeError(msg)
self._matchers = matchers
self._value: _T_co | Unset = value

Expand Down Expand Up @@ -406,6 +435,135 @@ def to_matching_rule(self) -> dict[str, Any]:
}


class OrMatcher(AbstractMatcher[_T_co]):
"""
Or matcher.

A matcher that combines multiple matchers using a logical OR: the value
must satisfy at least one of the constituent matchers.

Nested `OrMatcher` instances are flattened into a single list of
alternatives, as each path in a Pact file holds a single list of rules
combined with either AND or OR. For the same reason, an
[`AndMatcher`][pact.match.matcher.AndMatcher] cannot be used as one of the
alternatives.

/// warning
Only the example value is used during the consumer test. The other
alternatives are written to the Pact file and checked during provider
verification, but they are never exercised against the consumer code.
///

/// note
This requires a version of the Pact FFI with support for the
`pact:matcher:combine` integration JSON attribute
([pact-reference#601](https://github.com/pact-foundation/pact-reference/pull/601)).
TODO: Replace with the first released `pact_ffi` version that includes it.
///
"""

def __init__(
self,
*matchers: AbstractMatcher[Any],
value: _T_co | Unset = UNSET,
) -> None:
"""
Initialize the matcher.

It is best practice to provide a value. This may be set when creating
the `OrMatcher`, or it may be inferred from one of the constituent
matchers. In the latter case, the value from the first matcher that has
a value will be used.

Any matching rules nested within the example value (for example, when
the value is a dictionary containing matchers) still apply to the
children of the value.

Args:
matchers:
List of matchers to combine. At least two are required.

value:
Example value to match against. If not provided, the value
from the first matcher that has a value will be used.

Raises:
TypeError:
If an alternative is not a matcher or is an `AndMatcher`, or if
the value is itself a matcher.

ValueError:
If fewer than two alternatives are provided.
"""
alternatives: list[AbstractMatcher[Any]] = []
for matcher in matchers:
if isinstance(matcher, OrMatcher):
alternatives.extend(matcher._matchers) # noqa: SLF001
elif isinstance(matcher, AndMatcher):
msg = (
"An AndMatcher cannot be used as an alternative in an"
" OrMatcher, as Pact only supports a single combination"
" per path."
)
raise TypeError(msg)
elif isinstance(matcher, AbstractMatcher):
alternatives.append(matcher)
else:
msg = f"Expected a matcher, got {matcher!r}."
raise TypeError(msg)

if len(alternatives) < 2: # noqa: PLR2004
msg = "An OrMatcher requires at least two alternatives."
raise ValueError(msg)

if isinstance(value, AbstractMatcher):
msg = (
"The value of an OrMatcher cannot be a matcher. Pass it as one"
" of the alternatives instead."
)
raise TypeError(msg)

self._matchers: tuple[AbstractMatcher[Any], ...] = tuple(alternatives)
self.value: _T_co | Unset = value
"""
Default value used by Pact when executing tests.
"""

if isinstance(self.value, Unset):
for matcher in matchers:
if matcher.has_value():
# If `has_value` is true, `value` must be present
self.value = matcher.value # type: ignore[attr-defined]
break

def to_integration_json(self) -> dict[str, Any]:
"""
Convert the matcher to an integration JSON object.

See
[`AbstractMatcher.to_integration_json`][AbstractMatcher.to_integration_json]
for more information.
"""
return {
"pact:matcher:type": [m.to_integration_json() for m in self._matchers],
"pact:matcher:combine": "OR",
**({"value": self.value} if not isinstance(self.value, Unset) else {}),
}

def to_matching_rule(self) -> dict[str, Any]:
"""
Convert the matcher to a matching rule.

See
[`AbstractMatcher.to_matching_rule`][AbstractMatcher.to_matching_rule]
for more information.
"""
return {
"combine": "OR",
"matchers": [m.to_matching_rule() for m in self._matchers],
}


class MatchingRuleJSONEncoder(JSONEncoder):
"""
JSON encoder class for matching rules.
Expand All @@ -424,7 +582,7 @@ def default(self, o: Any) -> Any: # noqa: ANN401
Returns:
The encoded object.
"""
if isinstance(o, AndMatcher):
if isinstance(o, (AndMatcher, OrMatcher)):
return o.to_matching_rule()
if isinstance(o, AbstractMatcher):
# We need to convert all matchers in AndMatchers (even if there is
Expand Down
Loading
Loading