Nathan Farmer
10/21/2023, 1:30 AMLike
, how can I "clean" these dictionaries or otherwise use them for unit tests?Matt (pactflow.io / pact-js / pact-go)
Nathan Farmer
10/21/2023, 2:42 AMMatt (pactflow.io / pact-js / pact-go)
Matt (pactflow.io / pact-js / pact-go)
fixtures
directory with all of the payloads in there, e.g.
fixtures
- api1.py # contains all of the interactions for the API, or scenario or however you cut it up
- api2.py
...
Then for each Pact test, you just pull them in as is with the matchers etc. already specified
For other tests, you could use them also, and create a reify
function that strips away the matchers and pact specific stuff.
This way, you know the mocks used in one part of the code base can’t drift from the otherMatt (pactflow.io / pact-js / pact-go)
reify
in Typescript: https://github.com/pact-foundation/pact-js/blob/master/src/v3/matchers.ts#L538Nathan Farmer
10/22/2023, 1:02 AMreify
function:
JsonType: TypeAlias = Union[None, int, str, bool, List[Any], Dict[str, Any]]
PactBody: TypeAlias = Union[Dict[str, Union[JsonType, Matcher]], Matcher]
def _convert_matcher_to_value(matcher: Matcher) -> JsonType:
return matcher.generate()["contents"]
def _reify_pact_body(
body: PactBody,
) -> JsonType:
if isinstance(body, list):
for index, item in enumerate(body):
if isinstance(item, Matcher):
body[index] = _convert_matcher_to_value(matcher=item)
body[index] = _reify_pact_body(body=body[index])
return body
elif isinstance(body, Matcher):
return _reify_pact_body(body=_convert_matcher_to_value(matcher=body))
elif isinstance(body, dict):
for key, value in body.items():
if isinstance(value, Matcher):
body[key] = _convert_matcher_to_value(matcher=value)
body[key] = _reify_pact_body(body=body[key])
return body
else:
return body