How to convey to provider a contractual agreement of data format

57 Views Asked by At

Is there a way to generate a PACT file to convey data format validation?

An exaple of what I'm trying to accomplish: As a consumer, I expect a "phoneNumber" field with some data. I also expect that the phone number must contain 7 to 10 digit numbers. It may include dashes and/or brackets.

In the consumer test (code below), I construct the response object, so I can specify the format as I would expect. But this doesn't mean that the provider is bound by the same limitation. (ie, they might provide it in this way, but they may also provide it in a format that I don't expect).

I'm guessing that the most logical way to validate the data is to provide some RegEx inside the PACT file as a meta data. Is this something that can be done? If so, how do you provide this in the code.

The code snippit below to help visualize how I'm doing this: (Credit for the code snippit goes to "https://github.com/Mikuu/Pact-JVM-Example")

    Object homerUser = new Object() {
        public String name = "Homer Simpson";
        public String phoneNumber = "1-234-5678";
    };
    JSONObject responseBody = new JSONObject(new ObjectMapper().writeValueAsString(homerUser));

    RequestResponsePact pact = ConsumerPactBuilder
            .consumer(consumer)
            .hasPactWith(provider)
            .given("User Homer Exist")
            .uponReceiving("getUserById where homer exists")
                .path("/users/1")
                .method("GET")
                .headers(requestHeader)
            .willRespondWith()
                .status(HttpStatus.OK.value())
                .headers(responseHeader)
                .body(responseBody)
            .toPact();

    PactVerificationResult result = runConsumerTest(pact, getProviderConfig(), mockServer -> {
        ResponseEntity<User> response = userProvider.getUserById(1);
        assertThat(response.getStatusCode().value(), is(200));
        assertThat(response.getHeaders().get(HttpHeaders.CONTENT_TYPE), contains(MediaType.APPLICATION_JSON_UTF8_VALUE));
        assertThat(response.getBody(), notNullValue());
        assertThat(response.getBody().phoneNumber, matchesPhoneNumberPattern());
    });
1

There are 1 best solutions below

0
On

Yes, you can use regular expressions. Look at the matchers documentation for pact-jvm.