Can some one help me how to verify the pact.json file from the provider end.I am not able to find an example in github.

3,359 views
Skip to first unread message

bujji

unread,
Jun 20, 2016, 1:02:39 AM6/20/16
to Pact
It will be really helpful if some one can provide me the code for validating the pact file.

This is how i am generating the pact file.I am able to do the consumer part but not able to do the provider validating the json.

ExampleConsumerTest.java

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;

import au.com.dius.pact.consumer.Pact;
import au.com.dius.pact.consumer.PactProviderRule;
import au.com.dius.pact.consumer.PactVerification;
import au.com.dius.pact.consumer.dsl.PactDslJsonBody;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.model.PactFragment;

public class ExampleConsumerTest {
    String DATA_A_ID = "AAAAAAAA_ID";
    String DATA_B_ID = "BBBBBBBB_ID";

    Map<String, String> headers = MapUtils.putAll(new HashMap<String, String>(),
            new String[] { "Content-Type", "application/json;charset=UTF-8" });

    @Rule
    public PactProviderRule provider = new PactProviderRule("CarBookingProvider", "localhost", 8080, this);

    @Pact(provider = "CarBookingProvider", consumer = "CarBookingConsumer")
    public PactFragment configurationFragment(PactDslWithProvider builder) {
        return builder.given("john smith books a civic").uponReceiving("retrieve data from Service-A")
                .path("/persons/" + DATA_A_ID).method("GET").willRespondWith().headers(headers).status(200)
                .body(new PactDslJsonBody().stringValue("id", DATA_A_ID).stringValue("firstName", "John")
                        .stringValue("lastName", "Smith"))

                .uponReceiving("retrieving data from Service-B").path("/cars/" + DATA_B_ID).method("GET")
                .willRespondWith().headers(headers).status(200).body(new PactDslJsonBody().stringValue("id", DATA_B_ID)
                        .stringValue("brand", "Honda").stringValue("model", "Civic").numberValue("year", 2012))

                .uponReceiving("book a car").path("/orders/").method("POST")
                .body(new PactDslJsonBody().object("person").stringValue("id", DATA_A_ID)
                        .stringValue("firstName", "John").stringValue("lastName", "Smith").closeObject().object("cars")
                        .stringValue("id", DATA_B_ID).stringValue("brand", "Honda").stringValue("model", "Civic")
                        .numberValue("year", 2012).closeObject())
                .willRespondWith().headers(headers).status(201)
                .body(new PactDslJsonBody().stringMatcher("id", "ORDER_ID_\\d+", "ORDER_ID_123456")).toFragment();
    }

    @PactVerification("CarBookingProvider")
    @Test
    public void testBookCar() throws IOException {
        ExampleProviderTest providerRestClient = new ExampleProviderTest();
        HttpResponse response = providerRestClient.placeOrder("http://localhost:8080", DATA_A_ID, DATA_B_ID,
                "2015-03-15");

        Assert.assertEquals(201, response.getStatusLine().getStatusCode());
        String orderDetails = EntityUtils.toString(response.getEntity());
        Assert.assertEquals("{\"id\":\"ORDER_ID_123456\"}", orderDetails);
    }

}


ExampleProviderTest.java

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;

import com.google.gson.Gson;

public class ExampleProviderTest {

    public class Person {
        private String id;
        private String firstName;
        private String lastName;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    }

    public class Car {
        private String id;
        private String brand;
        private String model;
        private Integer year;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getBrand() {
            return brand;
        }

        public void setBrand(String brand) {
            this.brand = brand;
        }

        public String getModel() {
            return model;
        }

        public void setModel(String model) {
            this.model = model;
        }

        public Integer getYear() {
            return year;
        }

        public void setYear(Integer year) {
            this.year = year;
        }
    }

    public HttpResponse placeOrder(String baseUrl, String personId, String carId, String date) throws IOException {
        Gson gson = new Gson();
        String personStr = Request.Get(baseUrl + "/persons/" + personId).execute().returnContent().asString();
        Person person = gson.fromJson(personStr, Person.class);

        String carDetails = Request.Get(baseUrl + "/cars/" + carId).execute().returnContent().asString();
        Car car = gson.fromJson(carDetails, Car.class);

        String body = "{\n" + "\"person\": " + gson.toJson(person) + ",\n" + "\"cars\": " + gson.toJson(car) + "\n"
                + "}\n";
        return Request.Post(baseUrl + "/orders/").bodyString(body, ContentType.APPLICATION_JSON).execute()
                .returnResponse();
    }

}

CarBookingConsumer-CarBookingProvider.JSON


{
    "provider": {
        "name": "CarBookingProvider"
    },
    "consumer": {
        "name": "CarBookingConsumer"
    },
    "interactions": [
        {
            "providerState": "john smith books a civic",
            "description": "book a car",
            "request": {
                "method": "POST",
                "path": "/orders/",
                "headers": {
                    "Content-Type": "application/json; charset=UTF-8"
                },
                "body": {
                    "cars": {
                        "brand": "Honda",
                        "id": "BBBBBBBB_ID",
                        "model": "Civic",
                        "year": 2012
                    },
                    "person": {
                        "firstName": "John",
                        "id": "AAAAAAAA_ID",
                        "lastName": "Smith"
                    }
                }
            },
            "response": {
                "status": 201,
                "headers": {
                    "Content-Type": "application/json;charset=UTF-8"
                },
                "body": {
                    "id": "ORDER_ID_123456"
                },
                "matchingRules": {
                    "$.body.id": {
                        "regex": "ORDER_ID_\\d+"
                    }
                }
            }
        },
        {
            "providerState": "john smith books a civic",
            "description": "retrieve data from Service-A",
            "request": {
                "method": "GET",
                "path": "/persons/AAAAAAAA_ID",
                "body": null
            },
            "response": {
                "status": 200,
                "headers": {
                    "Content-Type": "application/json;charset=UTF-8"
                },
                "body": {
                    "firstName": "John",
                    "id": "AAAAAAAA_ID",
                    "lastName": "Smith"
                }
            }
        },
        {
            "providerState": "john smith books a civic",
            "description": "retrieving data from Service-B",
            "request": {
                "method": "GET",
                "path": "/cars/BBBBBBBB_ID",
                "body": null
            },
            "response": {
                "status": 200,
                "headers": {
                    "Content-Type": "application/json;charset=UTF-8"
                },
                "body": {
                    "brand": "Honda",
                    "id": "BBBBBBBB_ID",
                    "model": "Civic",
                    "year": 2012
                }
            }
        }
    ],
    "metadata": {
        "pact-specification": {
            "version": "2.0.0"
        },
        "pact-jvm": {
            "version": "3.2.7"
        }
    }
}

Ronald Holshausen

unread,
Jun 20, 2016, 1:10:35 AM6/20/16
to bujji, Pact
There are a number of ways of validating the provider with the generated pact file. It depends on what build tool or test framework you want to use.



--
You received this message because you are subscribed to the Google Groups "Pact" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pact-support...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
Ronald Holshausen

DiUS Computing Pty Ltd

Level 10, 99 Queens Street
Melbourne, VIC 3000

Phone: +61 3 9008 5400
Mobile: +61 413 162 439

http://www.diuscomputing.com.au

bujji

unread,
Jun 20, 2016, 1:16:46 AM6/20/16
to Pact, vutukuri...@gmail.com
I tried the below patc jvm provider maven example.

For that I created a new maven project and updated the pom.xml like this.

Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>


  <groupId>CDCProvider</groupId>

  <artifactId>CDCProvider</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <packaging>jar</packaging>


  <name>CDCProvider</name>

  <url>http://maven.apache.org</url>


  <properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  </properties>


  <dependencies>

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>3.8.1</version>

      <scope>test</scope>

    </dependency>

  </dependencies>

  

  <build>

   

    <plugins>

     

      

      <plugin>

    <groupId>au.com.dius</groupId>

    <artifactId>pact-jvm-provider-maven_2.11</artifactId>

    <version>2.1.9</version>

    <configuration>

      <serviceProviders>

        <!-- You can define as many as you need, but each must have a unique name -->

        <serviceProvider>

          <name>CarBookingProvider</name>

           <stateChangeUrl>http://localhost:8080/persons/AAAAAAAA_ID</stateChangeUrl>

          <!-- All the provider properties are optional, and have sensible defaults (shown below) -->

          <protocol>http</protocol>

          <host>localhost</host>

          <port>8080</port>

          <path>/persons/AAAAAAAA_ID</path>

          <consumers>

            <!-- Again, you can define as many consumers for each provider as you need, but each must have a unique name -->

            <consumer>

              <name>CarBookingConsumer</name>

              <!--  currently supports a file path using pactFile or a URL using pactUrl -->

              <pactFile>src/test/resources/CarBookingConsumer-CarBookingProvider.json</pactFile>

            </consumer>

          </consumers>

        </serviceProvider>

      </serviceProviders>

    </configuration>

</plugin>

     

    </plugins>

   

  </build>

</project>


I place my pact file in src/test/resources/CarBookingConsumer-CarBookingProvider.json

I ran the project like 

mvn au.com.dius:pact-jvm-provider-maven_2.11:verify



I got the below error:

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option PermSize=1024m; support was removed in 8.0

[INFO] Scanning for projects...

[INFO]                                                                         

[INFO] ------------------------------------------------------------------------

[INFO] Building CDCProvider 0.0.1-SNAPSHOT

[INFO] ------------------------------------------------------------------------

[INFO] 

[INFO] --- pact-jvm-provider-maven_2.11:2.1.9:verify (default-cli) @ CDCProvider ---

[INFO] ------------------------------------------------------------------------

[INFO] BUILD FAILURE

[INFO] ------------------------------------------------------------------------

[INFO] Total time: 0.697 s

[INFO] Finished at: 2016-06-20T14:33:22+10:00

[INFO] Final Memory: 23M/981M

[INFO] ------------------------------------------------------------------------

[ERROR] Failed to execute goal au.com.dius:pact-jvm-provider-maven_2.11:2.1.9:verify (default-cli) on project CDCProvider: Unable to parse configuration of mojo au.com.dius:pact-jvm-provider-maven_2.11:2.1.9:verify for parameter stateChangeUrl: Cannot find 'stateChangeUrl' in class au.com.dius.pact.provider.maven.Provider -> [Help 1]

[ERROR] 

[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.

[ERROR] Re-run Maven using the -X switch to enable full debug logging.

[ERROR] 

[ERROR] For more information about the errors and possible solutions, please read the following articles:

[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginConfigurationException


Can you please help me what I am missing here.Do I need to write any other files. 

Ronald Holshausen

unread,
Jun 20, 2016, 1:35:55 AM6/20/16
to bujji, Pact
Firstly, try a more recent version (2.1.9 is quite old). Change:

 <plugin>

    <groupId>au.com.dius</groupId>

    <artifactId>pact-jvm-provider-maven_2.11</artifactId>

    <version>2.1.9</version>

to a later version (latest is 3.2.8).


Secondly, remove the state change URL, to make things simpler to get started:

       <serviceProvider>

          <name>CarBookingProvider</name>

           <stateChangeUrl>http://localhost:8080/persons/AAAAAAAA_ID</stateChangeUrl> <!-- Remove this line -->


Thirdly, you have specified the provider URL incorrectly. It should be the URL to access your running provider (i.e. if you have started it, what URL would you use to access it?).

                <protocol>http</protocol>

          <host>localhost</host>

          <port>8080</port>

          <path>/persons/AAAAAAAA_ID</path> <!-- remove this line -->

What you have specified there looks like the path used in the test. It should be the root path to the provider. Probably better to take it out unless your provider is running on some sub-path.



Message has been deleted

Ronald Holshausen

unread,
Jun 23, 2016, 8:04:22 PM6/23/16
to bujji, Pact
If your validating the pact against a standard tomcat with no application deployed, then this is working correctly. Pact is telling you that it has made the request that was in the pact file, but did not get the correct response. Tomcat will return a 404 for any request it does not know about.

You need to deploy your provider to tomcat that handles those requests.

On Wed, 22 Jun 2016 at 09:35 bujji <vutukuri...@gmail.com> wrote:
Thanks for the quick reply.

Now I modified my pom like this.

Pom.xml

    <version>3.2.8</version>

    <configuration>

      <serviceProviders>

        <!-- You can define as many as you need, but each must have a unique name -->

        <serviceProvider>

          <name>CarBookingProvider</name>

          

          <!-- All the provider properties are optional, and have sensible defaults (shown below) -->

          <protocol>http</protocol>

          <host>localhost</host>

          <port>8080</port>

          

          <consumers>

            <!-- Again, you can define as many consumers for each provider as you need, but each must have a unique name -->

            <consumer>

              <name>CarBookingConsumer</name>

              <!--  currently supports a file path using pactFile or a URL using pactUrl -->

              <pactFile>src/test/resources/CarBookingConsumer-CarBookingProvider.json</pactFile>

            </consumer>

          </consumers>

        </serviceProvider>

      </serviceProviders>

    </configuration>

</plugin>

     

    </plugins>

   

  </build>

</project>



I started local tomcat server on port 8080 for mocking the consumer requests.So thats the reason i provided localhost:8080 in my pom.xml as provider url.If it is the wrong url can you tell me what URL i need to provide here.I had taken this consumer example from github.


Now I got the below error message.


mvn au.com.dius:pact-jvm-provider-maven_2.11:verify 

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option PermSize=1024m; support was removed in 8.0

[INFO] Scanning for projects...

[INFO]                                                                         

[INFO] ------------------------------------------------------------------------

[INFO] Building CDCProvider 0.0.1-SNAPSHOT

[INFO] ------------------------------------------------------------------------

[INFO] 

[INFO] --- pact-jvm-provider-maven_2.11:3.2.8:verify (default-cli) @ CDCProvider ---


Verifying a pact between CarBookingConsumer and CarBookingProvider

  [Using file src/test/resources/CarBookingConsumer-CarBookingProvider.json]

  Given john smith books a civic

         WARNING: State Change ignored as there is no stateChange URL

  book a car

    returns a response which

      has status code 201 (FAILED)

      includes headers

        "Content-Type" with value "application/json;charset=UTF-8" (FAILED)

      has a matching body (FAILED)

  Given john smith books a civic

         WARNING: State Change ignored as there is no stateChange URL

  retrieve data from Service-A

    returns a response which

      has status code 200 (FAILED)

      includes headers

        "Content-Type" with value "application/json;charset=UTF-8" (FAILED)

      has a matching body (FAILED)

  Given john smith books a civic

         WARNING: State Change ignored as there is no stateChange URL

  retrieving data from Service-B

    returns a response which

      has status code 200 (FAILED)

      includes headers

        "Content-Type" with value "application/json;charset=UTF-8" (FAILED)

      has a matching body (FAILED)


Failures:


0) Verifying a pact between CarBookingConsumer and CarBookingProvider - book a car Given john smith books a civic returns a response which has status code 201

      assert expectedStatus == actualStatus

             |              |  |

             201            |  404

                            false


1) Verifying a pact between CarBookingConsumer and CarBookingProvider - book a car Given john smith books a civic returns a response which includes headers "Content-Type" with value "application/json;charset=UTF-8"

      Expected header 'Content-Type' to have value 'application/json;charset=UTF-8' but was 'text/html;charset=utf-8'


2) Verifying a pact between CarBookingConsumer and CarBookingProvider - book a car Given john smith books a civic returns a response which has a matching body

      comparison -> Expected a response type of 'application/json' but the actual type was 'text/html'


3) Verifying a pact between CarBookingConsumer and CarBookingProvider - retrieve data from Service-A Given john smith books a civic returns a response which has status code 200

      assert expectedStatus == actualStatus

             |              |  |

             200            |  404

                            false


4) Verifying a pact between CarBookingConsumer and CarBookingProvider - retrieve data from Service-A Given john smith books a civic returns a response which includes headers "Content-Type" with value "application/json;charset=UTF-8"

      Expected header 'Content-Type' to have value 'application/json;charset=UTF-8' but was 'text/html;charset=utf-8'


5) Verifying a pact between CarBookingConsumer and CarBookingProvider - retrieve data from Service-A Given john smith books a civic returns a response which has a matching body

      comparison -> Expected a response type of 'application/json' but the actual type was 'text/html'


6) Verifying a pact between CarBookingConsumer and CarBookingProvider - retrieving data from Service-B Given john smith books a civic returns a response which has status code 200

      assert expectedStatus == actualStatus

             |              |  |

             200            |  404

                            false


7) Verifying a pact between CarBookingConsumer and CarBookingProvider - retrieving data from Service-B Given john smith books a civic returns a response which includes headers "Content-Type" with value "application/json;charset=UTF-8"

      Expected header 'Content-Type' to have value 'application/json;charset=UTF-8' but was 'text/html;charset=utf-8'


8) Verifying a pact between CarBookingConsumer and CarBookingProvider - retrieving data from Service-B Given john smith books a civic returns a response which has a matching body

      comparison -> Expected a response type of 'application/json' but the actual type was 'text/html'


[INFO] ------------------------------------------------------------------------

[INFO] BUILD FAILURE

[INFO] ------------------------------------------------------------------------

[INFO] Total time: 2.073 s

[INFO] Finished at: 2016-06-20T15:43:54+10:00

[INFO] Final Memory: 29M/1033M

[INFO] ------------------------------------------------------------------------

[ERROR] Failed to execute goal au.com.dius:pact-jvm-provider-maven_2.11:3.2.8:verify (default-cli) on project CDCProvider: There were 9 pact failures -> [Help 1]

[ERROR] 

[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.

[ERROR] Re-run Maven using the -X switch to enable full debug logging.

[ERROR] 

[ERROR] For more information about the errors and possible solutions, please read the following articles:

[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException



Appreciate your help on this.

Surya

unread,
Sep 6, 2017, 5:19:09 AM9/6/17
to Pact Support
May I know how was this issue solved atlast?
Reply all
Reply to author
Forward
0 new messages