How to Pact test a dictionary object

127 Views Asked by At

The below test will pass correctly, but if I post a body of {"a different key" : 4.56} it will fail as "key" is expected. In other words, the dictionary key is not flexible, only the float value.

How can I define a pact where only the dictionary types matter i.e. keys must be strings, value must be floats? The docs don't make this clear: https://github.com/pact-foundation/pact-python

def test_case_1(pact, client):
   (
      pact.given("object does not exist")
      .upon_receiving("a new post request")
      .with_request(
         "post", 
         "/url/post/endpoint",
         body=Like({"key": 1.23})
      .will_respond_with(200, body={})
   )
   with pact:
      client.post(body={"key": 4.56})
1

There are 1 best solutions below

0
On

I think you want to say "I don't care if that key exists or not". If that's the case, then you don't include the keys you aren't interested in.

If you need it in some cases, but not in others, you're best to write a test case for each of the scenarios you actually need, rather than defining what the provider API can do (test your code, not the provider)

Community member Tim Jones has a really great way to think about matchers:

Think of the matchers as saying “this test covers all cases that pass this matcher”, not “this is the response schema”

I'd also have a read of this article to understand the dangers in what you might be asking for: https://docs.pact.io/faq#why-is-there-no-support-for-specifying-optional-attributes