This workshop is aimed at demonstrating core features and benefits of contract testing with Pact.
Whilst contract testing can be applied retrospectively to systems, we will follow the consumer driven contracts approach in this workshop - where a new consumer and provider are created in parallel to evolve a service over time, especially where there is some uncertainty with what is to be built.
This workshop should take from 1 to 2 hours, depending on how deep you want to go into each topic.
NOTE: Each step is tied to, and must be run within, a git branch, allowing you to progress through each stage incrementally. For example, to move to step 2 run the following: git checkout step2
Meanwhile, our provider team has started building out their API in parallel. Let's run our website against our provider (you'll need two terminals to do this):
# Terminal 1
โฏ npm start --prefix provider
Provider API listening on port 8080...
# Terminal 2
> npm start --prefix consumer
Compiled successfully!
You can now view pact-workshop-js in the browser.
Local: http://localhost:3000/
On Your Network: http://192.168.20.17:3000/
Note that the development build is not optimized.
To create a production build, use npm run build.
You should now see a screen showing 3 different products. There is a See more! button which should display detailed product information.
Let's see what happens!
Doh! We are getting 404 everytime we try to view detailed product information. On closer inspection, the provider only knows about /product/{id} and /products.
We need to have a conversation about what the endpoint should be, but first...
Unit tests are written and executed in isolation of any other services. When we write tests for code that talk to other services, they are built on trust that the contracts are upheld. There is no way to validate that the consumer and provider can communicate correctly.
An integration contract test is a test at the boundary of an external service verifying that it meets the contract expected by a consuming service โ Martin Fowler
Adding contract tests via Pact would have highlighted the /product/{id} endpoint was incorrect.
Let us add Pact to the project and write a consumer pact test for the GET /products/{id} endpoint.
Provider states is an important concept of Pact that we need to introduce. These states help define the state that the provider should be in for specific interactions. For the moment, we will initially be testing the following states:
product with ID 10 exists
products exist
The consumer can define the state of an interaction using the given property.
This test starts a mock server a random port that acts as our provider service. To get this to work we update the URL in the Client that we create, after initialising Pact.
To simplify running the tests, add this to consumer/package.json:
// add it under scripts
"test:pact":"CI=true react-scripts test pact.spec.js",
Running this test still passes, but it creates a pact file which we can use to validate our assumptions on the provider side, and have conversation around.
โฏ npm run test:pact --prefix consumer
PASS src/api.spec.js
PASS src/api.pact.spec.js
Test Suites: 2 passed, 2 total
Tests: 4 passed, 4 total
Snapshots: 0 total
Time: 2.792s, estimated 3s
Ran all test suites.
A pact file should have been generated in consumer/pacts/frontendwebsite-productservice.json
NOTE: even if the API client had been graciously provided for us by our Provider Team, it doesn't mean that we shouldn't write contract tests - because the version of the client we have may not always be in sync with the deployed API - and also because we will write tests on the output appropriate to our specific needs.
We will need to copy the Pact contract file that was produced from the consumer test into the Provider module. This will help us verify that the provider can meet the requirements as set out in the contract.
Copy the contract located in consumer/pacts/frontendwebsite-productservice.json to provider/pacts/frontendwebsite-productservice.json.
Now let's make a start on writing Pact tests to validate the consumer contract:
In provider/product/product.pact.test.js:
const{Verifier}=require('@pact-foundation/pact');
const path =require('path');
// Setup provider server to verify
const app =require('express')();
app.use(require('./product.routes'));
const server = app.listen("8080");
describe("Pact Verification",()=>{
it("validates the expectations of ProductService",()=>{
โ validates the expectations of ProductService (716ms)
โ Pact Verification โบ validates the expectations of ProductService
WARN: Only the first item will be used to match the items in the array at $['body']
INFO: Reading pact at pact-workshop-js/provider/pacts/frontendwebsite-productservice.json
Verifying a pact between FrontendWebsite and ProductService
Given products exist
get all products
with GET /products
returns a response which
has status code 200
has a matching body
includes headers
"Content-Type" which equals "application/json; charset=utf-8"
Given product with ID 10 exists
get product with ID 10
with GET /products/10
returns a response which
has status code 200 (FAILED - 1)
has a matching body (FAILED - 2)
includes headers
"Content-Type" which equals "application/json; charset=utf-8" (FAILED - 3)
Failures:
1) Verifying a pact between FrontendWebsite and ProductService Given product with ID 10 exists get product with ID 10 with GET /products/10 returns a response which has status code 200
2) Verifying a pact between FrontendWebsite and ProductService Given product with ID 10 exists get product with ID 10 with GET /products/10 returns a response which has a matching body
Failure/Error: expect(response_body).to match_term expected_response_body, diff_options, example
Actual: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /products/10</pre>
</body>
</html>
Diff
--------------------------------------
Key: - is expected
+ is actual
Matching keys and values are not shown
-{
- "id": "10",
- "type": "CREDIT_CARD",
- "name": "28 Degrees"
-}
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Error</title>
+</head>
+<body>
+<pre>Cannot GET /products/10</pre>
+</body>
+</html>
Description of differences
--------------------------------------
* Expected a Hash but got a String ("<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot GET /products/10</pre>\n</body>\n</html>\n") at $
3) Verifying a pact between FrontendWebsite and ProductService Given product with ID 10 exists get product with ID 10 with GET /products/10 returns a response which includes headers "Content-Type" which equals "application/json; charset=utf-8"
Expected header "Content-Type" to equal "application/json; charset=utf-8", but was "text/html; charset=utf-8"
2 interactions, 1 failure
Failed interactions:
* Get product with id 10 given product with ID 10 exists
at ChildProcess.<anonymous> (node_modules/@pact-foundation/pact-node/src/verifier.ts:194:58)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 2.043s
Ran all test suites.
The test has failed, as the expected path /products/{id} is returning 404. We incorrectly believed our provider was following a RESTful design, but the authors were too lazy to implement a better routing solution ๐คท๐ปโโ๏ธ.
The correct endpoint which the consumer should call is /product/{id}.
Step 6 - Consumer updates contract for missing products#
We're now going to add 2 more scenarios for the contract
What happens when we make a call for a product that doesn't exist? We assume we'll get a 404.
What happens when we make a call for getting all products but none exist at the moment? We assume a 200 with an empty array.
Let's write a test for these scenarios, and then generate an updated pact file.
In consumer/src/api.pact.spec.js:
// within the 'getting all products' group
test("no products exists",async()=>{
// set up Pact interactions
await provider.addInteraction({
state:'no products exist',
uponReceiving:'get all products',
withRequest:{
method:'GET',
path:'/products'
},
willRespondWith:{
status:200,
headers:{
'Content-Type':'application/json; charset=utf-8'
},
body:[]
},
});
let api =newAPI(provider.mockService.baseUrl);
// make request to Pact mock server
let product =await api.getAllProducts();
expect(product).toStrictEqual([]);
});
// within the 'getting one product' group
test("product does not exist",async()=>{
// set up Pact interactions
await provider.addInteraction({
state:'product with ID 11 does not exist',
uponReceiving:'get product with ID 11',
withRequest:{
method:'GET',
path:'/product/11'
},
willRespondWith:{
status:404
},
});
let api =newAPI(provider.mockService.baseUrl);
// make request to Pact mock server
awaitexpect(api.getProduct("11")).rejects.toThrow("Request failed with status code 404");
});
Notice that our new tests look almost identical to our previous tests, and only differ on the expectations of the response - the HTTP request expectations are exactly the same.
โฏ npm run test:pact --prefix consumer
PASS src/api.pact.spec.js
API Pact test
getting all products
โ products exists (24ms)
โ no products exists (13ms)
getting one product
โ ID 10 exists (14ms)
โ product does not exist (14ms)
Test Suites: 1 passed, 1 total
Tests: 4 passed, 4 total
Snapshots: 0 total
Time: 2.437s, estimated 3s
Ran all test suites matching /pact.spec.js/i.
What does our provider have to say about this new test. Again, copy the updated pact file into the provider's pact directory and run the command:
[2020-01-14T11:11:51.941Z] WARN: pact@9.5.0/3894: No state handler found for "products exist", ignorning
[2020-01-14T11:11:51.972Z] WARN: pact@9.5.0/3894: No state handler found for "no products exist", ignorning
[2020-01-14T11:11:51.982Z] WARN: pact@9.5.0/3894: No state handler found for "product with ID 10 exists", ignorning
[2020-01-14T11:11:51.989Z] WARN: pact@9.5.0/3894: No state handler found for "product with ID 11 does not exist", ignorning
FAIL product/product.pact.test.js
Pact Verification
โ validates the expectations of ProductService (669ms)
โ Pact Verification โบ validates the expectations of ProductService
WARN: Only the first item will be used to match the items in the array at $['body']
INFO: Reading pact at pact-workshop-js/provider/pacts/frontendwebsite-productservice.json
Verifying a pact between FrontendWebsite and ProductService
Given products exist
get all products
with GET /products
returns a response which
has status code 200
has a matching body
includes headers
"Content-Type" which equals "application/json; charset=utf-8"
Given no products exist
get all products
with GET /products
returns a response which
has status code 200
has a matching body (FAILED - 1)
includes headers
"Content-Type" which equals "application/json; charset=utf-8"
Given product with ID 10 exists
get product with ID 10
with GET /product/10
returns a response which
has status code 200
has a matching body
includes headers
"Content-Type" which equals "application/json; charset=utf-8"
Given product with ID 11 does not exist
get product with ID 11
with GET /product/11
returns a response which
has status code 404 (FAILED - 2)
Failures:
1) Verifying a pact between FrontendWebsite and ProductService Given no products exist get all products with GET /products returns a response which has a matching body
Failure/Error: expect(response_body).to match_term expected_response_body, diff_options, example
* Actual array is too long and should not contain a Hash at $[0]
* Actual array is too long and should not contain a Hash at $[1]
* Actual array is too long and should not contain a Hash at $[2]
2) Verifying a pact between FrontendWebsite and ProductService Given product with ID 11 does not exist get product with ID 11 with GET /product/11 returns a response which has status code 404
* Get product with id 11 given product with ID 11 does not exist
at ChildProcess.<anonymous> (node_modules/@pact-foundation/pact-node/src/verifier.ts:194:58)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 2.044s
Ran all test suites.
[2020-01-14T11:11:52.052Z] WARN: pact-node@10.2.2/3894: Pact exited with code 1.
npm ERR! Test failed. See above for more details.
We expected this failure, because the product we are requesing does in fact exist! What we want to test for, is what happens if there is a different state on the Provider. This is what is referred to as "Provider states", and how Pact gets around test ordering and related issues.
We could resolve this by updating our consumer test to use a known non-existent product, but it's worth understanding how Provider states work more generally.
Our code already deals with missing users and sends a 404 response, however our test data fixture always has product ID 10 and 11 in our database.
In this step, we will add a state handler (stateHandlers) to our provider Pact verifications, which will update the state of our data store depending on which states the consumers require.
States are invoked prior to the actual test function is invoked. You can see the full lifecycle here.
We're going to add handlers for all our states:
products exist
no products exist
product with ID 10 exists
product with ID 11 does not exist
Let's open up our provider Pact verifications in provider/product/product.pact.test.js:
NOTE: The states are not necessarily a 1 to 1 mapping with the consumer contract tests. You can reuse states amongst different tests. In this scenario we could have used no products exist for both tests which would have equally been valid.
It turns out that not everyone should be able to use the API. After a discussion with the team, it was decided that a time-bound bearer token would suffice. The token must be in yyyy-MM-ddTHHmm format and within 1 hour of the current time.
In the case a valid bearer token is not provided, we expect a 401. Let's update the consumer to pass the bearer token, and capture this new 401 scenario.
โ validates the expectations of ProductService (667ms)
โ Pact Verification โบ validates the expectations of ProductService
WARN: Only the first item will be used to match the items in the array at $['body']
INFO: Reading pact at pact-workshop-js/provider/pacts/frontendwebsite-productservice.json
Verifying a pact between FrontendWebsite and ProductService
Given products exist
get all products
with GET /products
returns a response which
has status code 200
has a matching body
includes headers
"Content-Type" which equals "application/json; charset=utf-8"
Given no products exist
get all products
with GET /products
returns a response which
has status code 200
has a matching body
includes headers
"Content-Type" which equals "application/json; charset=utf-8"
Given products exist
get all products with no auth token
with GET /products
returns a response which
has status code 401 (FAILED - 1)
Given product with ID 10 exists
get product with ID 10
with GET /product/10
returns a response which
has status code 200
has a matching body
includes headers
"Content-Type" which equals "application/json; charset=utf-8"
Given product with ID 11 does not exist
get product with ID 11
with GET /product/11
returns a response which
has status code 404
Given product with ID 10 exists
get product by ID 10 with no auth token
with GET /product/10
returns a response which
has status code 401 (FAILED - 2)
Failures:
1) Verifying a pact between FrontendWebsite and ProductService Given products exist get all products with no auth token with GET /products returns a response which has status code 401
2) Verifying a pact between FrontendWebsite and ProductService Given product with ID 10 exists get product by ID 10 with no auth token with GET /product/10 returns a response which has status code 401
โ validates the expectations of ProductService (679ms)
โ Pact Verification โบ validates the expectations of ProductService
WARN: Only the first item will be used to match the items in the array at $['body']
INFO: Reading pact at pact-workshop-js/provider/pacts/frontendwebsite-productservice.json
Verifying a pact between FrontendWebsite and ProductService
Given products exist
get all products
with GET /products
returns a response which
has status code 200 (FAILED - 1)
has a matching body (FAILED - 2)
includes headers
"Content-Type" which equals "application/json; charset=utf-8"
Given no products exist
get all products
with GET /products
returns a response which
has status code 200 (FAILED - 3)
has a matching body (FAILED - 4)
includes headers
"Content-Type" which equals "application/json; charset=utf-8"
Given products exist
get all products with no auth token
with GET /products
returns a response which
has status code 401
Given product with ID 10 exists
get product with ID 10
with GET /product/10
returns a response which
has status code 200 (FAILED - 5)
has a matching body (FAILED - 6)
includes headers
"Content-Type" which equals "application/json; charset=utf-8"
Given product with ID 11 does not exist
get product with ID 11
with GET /product/11
returns a response which
has status code 404 (FAILED - 7)
Given product with ID 10 exists
get product by ID 10 with no auth token
with GET /product/10
returns a response which
has status code 401
Failures:
1) Verifying a pact between FrontendWebsite and ProductService Given products exist get all products with GET /products returns a response which has status code 200
2) Verifying a pact between FrontendWebsite and ProductService Given products exist get all products with GET /products returns a response which has a matching body
Failure/Error: expect(response_body).to match_term expected_response_body, diff_options, example
Actual: {"error":"Unauthorized"}
Diff
--------------------------------------
Key: - is expected
+ is actual
Matching keys and values are not shown
-[
- {
- "id": "09",
- "type": "CREDIT_CARD",
- "name": "Gem Visa"
- },
- {
- "id": "09",
- "type": "CREDIT_CARD",
- "name": "Gem Visa"
- },
-]
+{
+ "error": "Unauthorized"
+}
Description of differences
--------------------------------------
* Expected an Array (like [{"id"=>"09", "type"=>"CREDIT_CARD", "name"=>"Gem Visa"}, {"id"=>"09", "type"=>"CREDIT_CARD", "name"=>"Gem Visa"}]) but got a Hash at $
3) Verifying a pact between FrontendWebsite and ProductService Given no products exist get all products with GET /products returns a response which has status code 200
4) Verifying a pact between FrontendWebsite and ProductService Given no products exist get all products with GET /products returns a response which has a matching body
Failure/Error: expect(response_body).to match_term expected_response_body, diff_options, example
Actual: {"error":"Unauthorized"}
Diff
--------------------------------------
Key: - is expected
+ is actual
Matching keys and values are not shown
-[,
-
-]
+{
+ "error": "Unauthorized"
+}
Description of differences
--------------------------------------
* Expected an Array but got a Hash at $
5) Verifying a pact between FrontendWebsite and ProductService Given product with ID 10 exists get product with ID 10 with GET /product/10 returns a response which has status code 200
6) Verifying a pact between FrontendWebsite and ProductService Given product with ID 10 exists get product with ID 10 with GET /product/10 returns a response which has a matching body
Failure/Error: expect(response_body).to match_term expected_response_body, diff_options, example
Actual: {"error":"Unauthorized"}
Diff
--------------------------------------
Key: - is expected
+ is actual
Matching keys and values are not shown
{
- "id": String,
- "type": String,
- "name": String
}
Description of differences
--------------------------------------
* Could not find key "id" (keys present are: error) at $
* Could not find key "type" (keys present are: error) at $
* Could not find key "name" (keys present are: error) at $
7) Verifying a pact between FrontendWebsite and ProductService Given product with ID 11 does not exist get product with ID 11 with GET /product/11 returns a response which has status code 404
Because our pact file has static data in it, our bearer token is now out of date, so when Pact verification passes it to the Provider we get a 401. There are multiple ways to resolve this - mocking or stubbing out the authentication component is a common one. In our use case, we are going to use a process referred to as Request Filtering, using a RequestFilter.
The approach we are going to take to inject the header is as follows:
If we receive any Authorization header, we override the incoming request with a valid (in time) Authorization header, and continue with whatever call was being made
If we don't receive an Authorization header, we do nothing
NOTE: We are not considering the 403 scenario in this example.
We've been publishing our pacts from the consumer project by essentially sharing the file system with the provider. But this is not very manageable when you have multiple teams contributing to the code base, and pushing to CI. We can use a Pact Broker to do this instead.
Using a broker simplifies the management of pacts and adds a number of useful features, including some safety enhancements for continuous delivery which we'll see shortly.
In this workshop we will be using the open source Pact broker.
As part of this process, the results of the verification - the outcome (boolean) and the detailed information about the failures at the interaction level - are published to the Broker also.
This is one of the Broker's more powerful features. Referred to as Verifications, it allows providers to report back the status of a verification to the broker. You'll get a quick view of the status of each consumer and provider on a nice dashboard. But, it is much more important than this!
With just a simple use of the pact-brokercan-i-deploy tool - the Broker will determine if a consumer or provider is safe to release to the specified environment.
You can run the pact-broker can-i-deploy checks as follows: