How to verify an image contains in the response via pact test

864 views Asked by At

I want to use pact test to verify if a provider could provide a image in a response. now the actual response looks like this server response body which contains the picture

My Pact Json File looks like this

  "interactions": [
    {
      "providerState": "there's a user has a portrait tiger.png",
      "description": "Get the user's portrait",
      "request": {
        "method": "GET",
        "path": "/api/Employees/v1/Employee/106656048406528/Attachments",
        "headers": {
          "Content-Type": "application/json",
          "X-Employee-ID": "106656048406528",
          "X-Tenant-ID": "26663977872256",
          "X-User-ID": "1333"
        }
      },
      "response": {
        "status": 200,
        "headers": {
          "Content-Type": "image/jpeg;charset=UTF-8"
        },
        "body": "iVBORw0KGgoAAAANSU",
        "matchingRules": {
            "$.body": {
            "match": "type"
          }
        }
      }
    }
  ],

the pact test always fails and say the body mismatch. I can understand the actual response is not a base64 format and not a string. it should some binaries file. In this case, how can I write the matching rules to valid it's a binary file?

2

There are 2 answers

0
Gopinath Langote On

In my opinion, only the header check is enough. (Unless you want to verify entire binary content, which I think is not the best).

0
J_A_X On

The way to do this would be to ignore the body unless you really want to match the exact binary every time, which would be counter productive in my opinion.

When a binary file is sent, it does send the appropriate headers with it, like you already have in your contract with 'Content-Type'. You can always add a matching rule that the body has to be there, but you just don't care about the content, but I'm not positive if this is even needed since you could just look at the 'Content-Length' header and make sure it's bigger than 0.

What needs to be remembered is that Pact is not meant to be used to match everything. It's meant to match the critical parts of your system and certain expectations from your consumer, ie. as a consumer, I want to call this service which should give me an image, but I don't care what that image is since I just show it in the DOM. If you need an actual image to be given on the consumer side while testing, you can use the matcher query to resolve to anything by using regex, then as the generator, use the actual image output. I'd use something small though if I were you since Pact isn't exactly meant to be spewing out megabytes of binaries.