1

I have the below pact file with following interactions

"interactions": [
{
"description": "I call fixture service using a valid fixture Id",
"providerState": "a request to check the api response",
"request": {
"method": "get",
"path": "/api/v1.0/abc/5d550d86-fe18-44e5-93d2-817318acca3d",
"headers": {
"Accept": "application/json",
"X-Clarksons-Security-Cloud": "xxxxyyyyy"
}
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"body": {
"fixtureId": "5d550d86-fe18-44e5-93d2-817318acca3d",
"fixtureNumber": "145393-02-DR-03-18"
},
"matchingRules": {
"$.body.fixtureId": {
"match": "type"
},
"$.body.fixtureNumber": {
"match": "regex",
"regex": "[0-9]{6}-[0-9]{2}-[a-zA-Z]{2}-[0-9]{2}-[0-9]{2}"
}
}
}
}
],

There is a chance fixtureNumber can be null. Please could you let me know a matcher that would do both check for [0-9]{6}-[0-9]{2}-[a-zA-Z]{2}-[0-9]{2}-[0-9]{2} and also check for null.

Biffen
  • 6,249
  • 6
  • 28
  • 36
makil
  • 489
  • 2
  • 7
  • 19

2 Answers2

1

You can check for a null character: \x00.

The pattern would look something like:

([0-9]{6}-[0-9]{2}-[a-zA-Z]{2}-[0-9]{2}-[0-9]{2})|\x00
Jim Wright
  • 5,905
  • 1
  • 15
  • 34
0

You can't test for both the presence (with a regex) or absence of a field. You should write two separate tests, that test for each use case, to ensure that your code properly handles it.

Please read this article which explains why: https://docs.pact.io/faq#why-is-there-no-support-for-specifying-optional-attributes

...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.

The same goes for specifying "SOME_VALUE or null". If all your provider verification test data returned nulls for this key, you might think that you had validated the "SOME_VALUE", but in fact, you never had. You could get a completely different "SOME_VALUE" for this key in production, which may then cause issues.

Matthew Fellows
  • 3,669
  • 1
  • 15
  • 18
  • Thanks for this. But I am not testing the presence or absence of a field but instead its value and if that can sometime return a string or some times null. The example you have given is the assert sometime the field is returned and sometimes its not. Here the field is always returned just its value can be a string or null. – makil Jan 11 '19 at 19:12
  • The exact same logic applies - you need a separate test for each different type of response. A regex cannot do this because the type is not a string. – Matthew Fellows Jan 11 '19 at 21:23