Search code examples
pythonpact

pact: how to check a a field in the response that may or may not exist


I have a service that will respond to a request with a json blob, such as this:

{
  "field1": 1,
  "field2": "2",
  "array": [1,2,3]
}

I know that I can test array by using EachLike, like this:

expected = {
  "field1": Like(1),
  "field2": Like("2"),
  "array": EachLike(1)
}

The issue is that "array" is an optional field in the response. It may not exist at all, and if it doesn't, I still need the contract to validate. How do I define that a field in the response body must match a type if it exists, but that it may not exist at all?


Solution

  • From https://docs.pact.io/faq#why-is-there-no-support-for-specifying-optional-attributes

    Why is there no support for specifying optional attributes?

    Firstly, it is assumed that you have control over the provider's data (and consumer's data) when doing the verification tests. If you don't, then maybe Pact is not the best tool for your situation.

    Secondly, if you think about it, if Pact supports making an assertion that element $.body.name may be present in a response, then you write consumer code that can handle an optional $.body.name, but in fact, the provider gives $.body.firstname, no test will ever fail to tell you that you've made an incorrect assumption. Remember that a provider may return extra data without failing the contract, but it must provide at minimum the data you expect.


    I would recommend that you write one interaction where you require that the array is populated, so that you know how to deal with a populated array. Then leave it out of the other interactions altogether, and then it won't matter whether it's populated or not.