diff --git a/docs/consumer.md b/docs/consumer.md index 7a4f8da2f..696ea0c0c 100644 --- a/docs/consumer.md +++ b/docs/consumer.md @@ -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. diff --git a/pact-python-ffi/hatch_build.py b/pact-python-ffi/hatch_build.py index fdd3c4284..8c4513e22 100644 --- a/pact-python-ffi/hatch_build.py +++ b/pact-python-ffi/hatch_build.py @@ -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: @@ -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) diff --git a/pact-python-ffi/tests/test_init.py b/pact-python-ffi/tests/test_init.py index 05a9d7140..856ff72c9 100644 --- a/pact-python-ffi/tests/test_init.py +++ b/pact-python-ffi/tests/test_init.py @@ -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: diff --git a/src/pact/match/__init__.py b/src/pact/match/__init__.py index 073ea7a57..b5b79cf84 100644 --- a/src/pact/match/__init__.py +++ b/src/pact/match/__init__.py @@ -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 @@ -255,6 +301,7 @@ EachKeyMatcher, EachValueMatcher, GenericMatcher, + OrMatcher, ) from pact.types import UNSET, Matchable, Unset @@ -280,6 +327,7 @@ # __all__ = [ "AbstractMatcher", + "any_of", "array_containing", "bool", "boolean", @@ -296,6 +344,7 @@ "like", "none", "null", + "nullable", "number", "regex", "str", @@ -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) diff --git a/src/pact/match/matcher.py b/src/pact/match/matcher.py index 74c747eff..f89c3326a 100644 --- a/src/pact/match/matcher.py +++ b/src/pact/match/matcher.py @@ -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]): """ @@ -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 @@ -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. @@ -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 diff --git a/tests/test_match_or.py b/tests/test_match_or.py new file mode 100644 index 000000000..aa7388b6c --- /dev/null +++ b/tests/test_match_or.py @@ -0,0 +1,303 @@ +""" +Tests for matchers combined with a logical OR. + +These require a Pact FFI with support for the `pact:matcher:combine` +integration JSON attribute (pact-reference#601). +""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any + +import pytest +import requests + +from pact import Pact, match +from pact.error import RequestMismatch +from pact.match.matcher import ( + IntegrationJSONEncoder, + MatchingRuleJSONEncoder, + OrMatcher, +) + +if TYPE_CHECKING: + from pathlib import Path + +UUID = "e1d6e6a8-3f0a-4d5e-9c8b-6f3a2d1c0b9a" + + +def integration_json(value: object) -> Any: # noqa: ANN401 + return json.loads(json.dumps(value, cls=IntegrationJSONEncoder)) + + +def matching_rule(value: object) -> Any: # noqa: ANN401 + return json.loads(json.dumps(value, cls=MatchingRuleJSONEncoder)) + + +class TestIntegrationJson: + """Integration JSON and matching rules emitted for OR matchers.""" + + def test_any_of(self) -> None: + assert integration_json(match.any_of(match.str("Fred"), match.null())) == { + "pact:matcher:type": [ + {"pact:matcher:type": "type", "value": "Fred"}, + {"pact:matcher:type": "null"}, + ], + "pact:matcher:combine": "OR", + "value": "Fred", + } + + def test_or_operator(self) -> None: + assert integration_json(match.str("Fred") | match.null()) == integration_json( + match.any_of(match.str("Fred"), match.null()) + ) + + def test_alternative_attributes_are_kept(self) -> None: + result = integration_json( + match.any_of(match.regex("123", regex=r"^\d+$"), match.uuid()) + ) + assert result["pact:matcher:type"][0] == { + "pact:matcher:type": "regex", + "regex": r"^\d+$", + "value": "123", + } + assert result["pact:matcher:type"][1]["pact:matcher:type"] == "regex" + assert result["value"] == "123" + + def test_flattened(self) -> None: + nested = match.any_of( + match.int(1) | match.null(), + match.any_of(match.str("a"), match.bool(True)), + ) + chained = match.int(1) | match.null() | match.str("a") | match.bool(True) + for matcher in (nested, chained): + result = integration_json(matcher) + assert [m["pact:matcher:type"] for m in result["pact:matcher:type"]] == [ + "integer", + "null", + "type", + "boolean", + ] + assert result["value"] == 1 + + def test_value_inferred_from_first_matcher_with_value(self) -> None: + result = integration_json(match.null() | match.int(42)) + assert result["value"] == 42 + + def test_explicit_value(self) -> None: + result = integration_json(match.any_of(match.int(1), match.null(), value=None)) + assert result["value"] is None + + def test_no_value(self) -> None: + result = integration_json(match.null() | match.uuid()) + assert "value" not in result + + def test_nullable_matcher(self) -> None: + assert integration_json(match.nullable(match.int(42))) == { + "pact:matcher:type": [ + {"pact:matcher:type": "integer", "value": 42}, + {"pact:matcher:type": "null"}, + ], + "pact:matcher:combine": "OR", + "value": 42, + } + + def test_nullable_object(self) -> None: + result = integration_json( + match.nullable({"street": "Main St", "number": match.int(42)}) + ) + assert result == { + "pact:matcher:type": [ + {"pact:matcher:type": "type"}, + {"pact:matcher:type": "null"}, + ], + "pact:matcher:combine": "OR", + "value": { + "street": "Main St", + "number": {"pact:matcher:type": "integer", "value": 42}, + }, + } + + def test_nullable_or_matcher_is_flattened(self) -> None: + result = integration_json(match.nullable(match.int(1) | match.str("a"))) + assert [m["pact:matcher:type"] for m in result["pact:matcher:type"]] == [ + "integer", + "type", + "null", + ] + + def test_nested_in_body(self) -> None: + result = integration_json({"a": {"b": match.nullable(match.int(1))}}) + assert result["a"]["b"]["pact:matcher:combine"] == "OR" + + def test_matching_rule(self) -> None: + assert matching_rule(match.any_of(match.int(1), match.null())) == { + "combine": "OR", + "matchers": [{"match": "integer", "value": 1}, {"match": "null"}], + } + + def test_requires_two_alternatives(self) -> None: + with pytest.raises(ValueError, match="at least two"): + match.any_of(match.int(1)) + + def test_rejects_non_matcher(self) -> None: + with pytest.raises(TypeError, match="Expected a matcher"): + OrMatcher(match.int(1), 2) # type: ignore[arg-type] + + def test_rejects_matcher_value(self) -> None: + with pytest.raises(TypeError, match="cannot be a matcher"): + match.any_of(match.int(1), match.null(), value=match.int(2)) + + def test_rejects_and_inside_or(self) -> None: + with pytest.raises(TypeError, match="AndMatcher"): + match.any_of(match.int(1) & match.number(1), match.null()) + + def test_rejects_or_inside_and(self) -> None: + with pytest.raises(TypeError, match="OrMatcher"): + match.int(1) & (match.int(1) | match.null()) + + def test_or_with_non_matcher(self) -> None: + with pytest.raises(TypeError): + match.int(1) | 2 # type: ignore[operator] + + +@pytest.fixture +def pact() -> Pact: + return Pact("or-consumer", "or-provider").with_specification("V4") + + +def _body_interaction(pact: Pact) -> None: + ( + pact + .upon_receiving("a request with nullable fields") + .with_request("POST", "/users") + .with_body( + { + "name": match.nullable(match.str("Fred")), + "id": match.regex("123", regex=r"^\d+$") | match.uuid(), + "address": match.nullable({ + "street": match.str("Main St"), + "number": match.int(42), + }), + }, + "application/json", + ) + .will_respond_with(200) + ) + + +@pytest.mark.parametrize( + "body", + [ + pytest.param( + {"name": "Fred", "id": "123", "address": {"street": "x", "number": 1}}, + id="first-alternatives", + ), + pytest.param( + {"name": None, "id": UUID, "address": None}, + id="second-alternatives", + ), + ], +) +def test_body_alternatives_match(pact: Pact, body: dict[str, Any]) -> None: + _body_interaction(pact) + with pact.serve() as srv: + response = requests.post(f"{srv.url}/users", json=body, timeout=5) + assert response.status_code == 200 + + +@pytest.mark.parametrize( + "body", + [ + pytest.param( + {"name": 1, "id": "123", "address": None}, + id="name-not-string-or-null", + ), + pytest.param( + {"name": "Fred", "id": "abc", "address": None}, + id="id-not-digits-or-uuid", + ), + pytest.param( + {"name": "Fred", "id": "123", "address": {"street": "x", "number": "1"}}, + id="nested-rule-still-applies", + ), + ], +) +def test_body_no_alternative_matches(pact: Pact, body: dict[str, Any]) -> None: + _body_interaction(pact) + with pact.serve(raises=False) as srv: + response = requests.post(f"{srv.url}/users", json=body, timeout=5) + assert response.status_code == 500 + assert len(srv.mismatches) == 1 + assert isinstance(srv.mismatches[0], RequestMismatch) + + +def test_pact_file_has_or_rules(pact: Pact, tmp_path: Path) -> None: + _body_interaction(pact) + with pact.serve() as srv: + response = requests.post( + f"{srv.url}/users", + json={"name": "Fred", "id": "123", "address": None}, + timeout=5, + ) + assert response.status_code == 200 + pact.write_file(tmp_path) + + contents = json.loads((tmp_path / "or-consumer-or-provider.json").read_text()) + rules = contents["interactions"][0]["request"]["matchingRules"]["body"] + assert rules["$.name"] == { + "combine": "OR", + "matchers": [{"match": "type"}, {"match": "null"}], + } + assert rules["$.id"]["combine"] == "OR" + assert [m["match"] for m in rules["$.id"]["matchers"]] == ["regex", "regex"] + assert rules["$.address"] == { + "combine": "OR", + "matchers": [{"match": "type"}, {"match": "null"}], + } + assert rules["$.address.number"]["matchers"] == [{"match": "integer"}] + + +@pytest.mark.parametrize( + ("value", "status"), + [ + pytest.param("123", 200, id="digits"), + pytest.param(UUID, 200, id="uuid"), + pytest.param("abc", 500, id="neither"), + ], +) +def test_header_alternatives(pact: Pact, value: str, status: int) -> None: + ( + pact + .upon_receiving("a request with an OR header") + .with_request("GET", "/") + .with_header("X-Id", match.regex("123", regex=r"^\d+$") | match.uuid()) + .will_respond_with(200) + ) + with pact.serve(raises=False) as srv: + response = requests.get(srv.url, headers={"X-Id": value}, timeout=5) + assert response.status_code == status + assert len(srv.mismatches) == (status != 200) + + +@pytest.mark.parametrize( + ("value", "status"), + [ + pytest.param("123", 200, id="digits"), + pytest.param(UUID, 200, id="uuid"), + pytest.param("abc", 500, id="neither"), + ], +) +def test_query_alternatives(pact: Pact, value: str, status: int) -> None: + ( + pact + .upon_receiving("a request with an OR query parameter") + .with_request("GET", "/") + .with_query_parameter("id", match.regex("123", regex=r"^\d+$") | match.uuid()) + .will_respond_with(200) + ) + with pact.serve(raises=False) as srv: + response = requests.get(srv.url, params={"id": value}, timeout=5) + assert response.status_code == status + assert len(srv.mismatches) == (status != 200)