Renske
Renske

Reputation: 98

How to define pact-specification matching rule for single string body?

I am setting up a test for a put request uploading a file. The request body in my pact-file consists of a single string, containing a mime boundary that changes for every test run. I am trying to define a regex matching rule for the request body string, but it won't match. A similar matching rule for the header content-type does match.

How should I define the matching rule for the body if the body is only a string?

I'm using a reference implementation of Pact in Rust. The Pact-Specification version is 3.

"request": {
    "headers": {
        "Content-Length": "206",
        "Host": "127.0.0.1:1234",
        "Connection": "Close",
        "Content-Type": "multipart/form-data; boundary=\"MIME_boundary_4FBA8D0826C707B6\""
    },
    "body": "--MIME_boundary_4FBA8D0826C707B6\r\nContent-Disposition: form-data; name=\"file\"; filename=\"test_file.txt\"\r\nContent-Type: application/octet-stream\r\n\r\nContent of test file.\r\n--MIME_boundary_4FBA8D0826C707B6--\r\n",
    "matchingRules": {
        "header": {
            "$.Content-Type": {
                "matchers": [
                    {
                        "match": "regex",
                        "regex": "multipart/form-data; boundary=\"MIME_boundary_[A-Z0-9]{16}\""
                    }
                ]
            }
        },
        "body": {
            "$": {
                "matchers": [
                    {
                        "match": "regex",
                        "regex": "--MIME_boundary_[A-Z0-9]{16}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"test_file.txt\"\r\nContent-Type: application/octet-stream\r\n\r\nContent of test file.\r\n--MIME_boundary_[A-Z0-9]{16}--\r\n"
                    }
                ]
            }
        }
    }
}

The code above is part of the pact file used in the test. The test results in a BodyMismatch error. Comparing the expected and received bodies shows that they only differ in mime boundary, so the regex matching is not working.

Upvotes: 6

Views: 2077

Answers (2)

Renske
Renske

Reputation: 98

Through Pact's Slack channel we got the answer that the current Pact code does not support this type of matching. We created a feature request issue on GitHub: https://github.com/pact-foundation/pact-reference/issues/43

Upvotes: 2

Ronald Holshausen
Ronald Holshausen

Reputation: 931

The mime boundary value will always change. Writing a regular expression to match that will be quite challenging. It would be better to have a matching implementation that understands multi-part bodies. Pact-JVM supports this (see https://github.com/DiUS/pact-jvm/blob/master/consumer/pact-jvm-consumer-junit/src/test/groovy/au/com/dius/pact/consumer/junit/ExampleFileUploadSpec.groovy), so it would not be too hard to implement in Pact-Rust.

Upvotes: 0

Related Questions