Golang version of Pact. Pact is a contract testing framework for HTTP APIs and non-HTTP asynchronous messaging systems.
Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service Provider project.
Specification Compatibility
Version | Stable | Spec Compatibility | Install |
---|---|---|---|
2.0.x | Yes | 2, 3 | See installation |
1.0.x | Yes | 2, 3* | 1.x.x 1xx |
0.x.x | Yes | Up to v2 | 0.x.x stable |
* v3 support is limited to the subset of functionality required to enable language inter-operable Message support.
- Run
go get github.com/pact-foundation/pact-go/v2/@2.x.x
to install the source packages, and the installer code - Run
pact-go -l DEBUG install
to download and install the required libraries
If all is successful, you are ready to go!
Downlod the latest Pact Verifier FFI
and Pact Mock Server FFI
libraries for your OS, and install onto a standard library search path (for example, we suggest: /usr/local/lib
on OSX/Linux):
Ensure you have the correct extension for your OS:
- For Mac OSX:
.dylib
- For Linux:
.so
- For Windows:
.dll
wget https://github.com/pact-foundation/pact-reference/releases/download/pact_verifier_ffi-v0.0.2/libpact_verifier_ffi-osx-x86_64.dylib.gz
gunzip libpact_verifier_ffi-osx-x86_64.dylib.gz
mv libpact_verifier_ffi-osx-x86_64.dylib /usr/local/lib/libpact_verifier_ffi.dylib
wget https://github.com/pact-foundation/pact-reference/releases/download/libpact_mock_server_ffi-v0.0.15/libpact_mock_server_ffi-osx-x86_64.dylib.gz
gunzip libpact_mock_server_ffi-osx-x86_64.dylib.gz
mv libpact_mock_server_ffi-osx-x86_64.dylib /usr/local/lib/libpact_mock_server_ffi.dylib
Test the installation:
pact-go help
Pact supports synchronous request-response style HTTP interactions and has experimental support for asynchronous interactions with JSON-formatted payloads.
Pact Go runs as part of your regular Go tests.
We'll run through a simple example to get an understanding the concepts:
go get github.com/pact-foundation/pact-go
cd $GOPATH/src/github.com/pact-foundation/pact-go/examples/
go test -v -run TestConsumer
.
The simple example looks like this:
func TestConsumer(t *testing.T) {
type User struct {
Name string `json:"name" pact:"example=billy"`
LastName string `json:"lastName" pact:"example=sampson"`
}
// Create Pact connecting to local Daemon
pact := &dsl.Pact{
Consumer: "MyConsumer",
Provider: "MyProvider",
Host: "localhost",
}
defer pact.Teardown()
// Pass in test case. This is the component that makes the external HTTP call
var test = func() (err error) {
u := fmt.Sprintf("http://localhost:%d/foobar", pact.Server.Port)
req, err := http.NewRequest("GET", u, strings.NewReader(`{"name":"billy"}`))
if err != nil {
return err
}
// NOTE: by default, request bodies are expected to be sent with a Content-Type
// of application/json. If you don't explicitly set the content-type, you
// will get a mismatch during Verification.
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer 1234")
if _, err = http.DefaultClient.Do(req); err != nil {
return err
}
}
// Set up our expected interactions.
pact.
AddInteraction().
Given("User foo exists").
UponReceiving("A request to get foo").
WithRequest(dsl.Request{
Method: "GET",
Path: dsl.String("/foobar"),
Headers: dsl.MapMatcher{"Content-Type": dsl.String("application/json"), "Authorization": dsl.String("Bearer 1234")},
Body: map[string]string{
"name": "billy",
},
}).
WillRespondWith(dsl.Response{
Status: 200,
Headers: dsl.MapMatcher{"Content-Type": dsl.String("application/json")},
Body: dsl.Match(&User{}),
})
// Run the test, verify it did what we expected and capture the contract
if err := pact.Verify(test); err != nil {
log.Fatalf("Error on Verify: %v", err)
}
return nil
}
go get github.com/pact-foundation/pact-go
cd $GOPATH/src/github.com/pact-foundation/pact-go/examples/
go test -v -run TestProvider
.
Here is the Provider test process broker down:
-
Start your Provider API:
You need to be able to first start your API in the background as part of your tests before you can run the verification process. Here we create
startServer
which can be started in its own goroutine:var lastName = "" // User doesn't exist func startServer() { mux := http.NewServeMux() mux.HandleFunc("/users", func(w http.ResponseWriter, req *http.Request) { w.Header().Add("Content-Type", "application/json") fmt.Fprintf(w, fmt.Sprintf(`{"lastName":"%s"}`, lastName)) }) log.Fatal(http.ListenAndServe(":8000", mux)) }
-
Verify provider API
You can now tell Pact to read in your Pact files and verify that your API will satisfy the requirements of each of your known consumers:
func TestProvider(t *testing.T) { // Create Pact connecting to local Daemon pact := &dsl.Pact{ Provider: "MyProvider", } // Start provider API in the background go startServer() // Verify the Provider using the locally saved Pact Files err := verifier.VerifyProvider(t, v3.VerifyRequest{ ProviderBaseURL: "http://localhost:8000", PactFiles: []string{filepath.ToSlash(fmt.Sprintf("%s/MyConsumer-MyProvider.json", pactDir))}, StateHandlers: v3.StateHandlers{ // Setup any state required by the test // in this case, we ensure there is a User "foo" in the system "User foo exists": func(setup bool, s v3.ProviderStateV3) (v3.ProviderStateV3Response, error) { if setup { log.Println("[DEBUG] HOOK calling user foo exists state handler", s) } else { log.Println("[DEBUG] HOOK teardown the 'User foo exists' state") } // ... do something, such as create "foo" in the database // Optionally (if there are generators in the pact) return provider state values to be used in the verification // e.g. the user ID for use in a GET /users/:id path return v3.ProviderStateV3Response{"uuid": "1234"}, nil }, }, }) }
Note that PactURLs
may be a list of local pact files or remote based
urls (e.g. from a
Pact Broker).
If you have defined any states (as denoted by a Given()
) in your consumer tests, the Verifier
can put the provider into the correct state prior to sending the actual request for validation. For example, the provider can use the state to mock away certain database queries. To support this, set up a StateHandler
for each state using hooks on the StateHandlers
property. Here is an example:
pact.VerifyProvider(t, types.VerifyRequest{
...
StateHandlers: v3.StateHandlers{
"User 1234 exists": func(setup bool, s v3.ProviderStateV3) (v3.ProviderStateV3Response, error) {
// set the database to have users
userRepository = fullUsersRepository
// if you have dynamic IDs and you are using provider state value generators
// you can return a key/value response that will be used by the verifier to substitute
// the pact file values, with the replacements here
return v3.ProviderStateV3Response{"uuid": "1234"}, nil
},
"No users exist": func(setup bool, s v3.ProviderStateV3) (v3.ProviderStateV3Response, error) {
// set the database to an empty database
userRepository = emptyRepository
return nil, nil
},
},
})
As you can see, for each state ("User 1234 exists"
etc.) we configure the local datastore differently. If this option is not configured, the Verifier
will ignore the provider states defined in the pact and log a warning.
Each handler takes a setup
property indicating if the state is being setup (before the test) or torn dowmn (post request). This is useful if you want to cleanup after the test.
You may also optionally return a key/value map for provider state value generators to substitute values in the incoming test request.
Note that if the State Handler errors, the test will exit early with a failure.
Read more about Provider States.
Sometimes, it's useful to be able to do things before or after a test has run, such as reset a database, log a metric etc. A BeforeEach
runs before any other part of the Pact test lifecycle, and a AfterEach
runs as the last step before returning the verification result back to the test.
You can add them to your Verification as follows:
pact.VerifyProvider(t, types.VerifyRequest{
...
BeforeEach: func() error {
fmt.Println("before hook, do something")
return nil
},
AfterEach: func() error {
fmt.Println("after hook, do something")
return nil
},
})
If the Hook errors, the test will fail.
Sometimes you may need to add things to the requests that can't be persisted in a pact file. Examples of these are authentication tokens with a small life span. e.g. an OAuth bearer token: Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42
.
For these cases, we have two facilities that should be carefully used during verification:
- the ability to specify custom headers to be sent during provider verification. The flag to achieve this is
CustomProviderHeaders
. - the ability to modify a request/response and change the payload. The parameter to achieve this is
RequestFilter
.
Read on for more.
WARNING: This should only be attempted once you know what you're doing!
Request filters are custom middleware, that are executed for each request, allowing token
to change between invocations. Request filters can change the request coming in, and the response back to the verifier. It is common to pair this with StateHandlers
as per above, that can set/expire the token
for different test cases:
pact.VerifyProvider(t, types.VerifyRequest{
...
RequestFilter: func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
next.ServeHTTP(w, r)
})
}
})
Important Note: You should only use this feature for things that can not be persisted in the pact file. By modifying the request, you are potentially modifying the contract from the consumer tests!
Pending pacts is a feature that allows consumers to publish new contracts or changes to existing contracts without breaking Provider's builds. It does so by flagging the contract as "unverified" in the Pact Broker the first time a contract is published. A Provider can then enable a behaviour (via EnablePending: true
) that will still perform a verification (and thus share the results back to the broker) but not fail the verification step itself.
This enables safe introduction of new contracts into the system, without breaking Provider builds, whilst still providing feedback to Consumers as per before.
See the docs and this article for more background.
WIP Pacts builds upon pending pacts, enabling provider tests to pull in any contracts applicable to the provider regardless of the tag
it was given. This is useful, because often times consumers won't follow the exact same tagging convention and so their workflow would be interrupted. This feature enables any pacts determined to be "work in progress" to be verified by the Provider, without causing a build failure. You can enable this behaviour by specifying a valid time.Time
field for IncludeWIPPactsSince
. This sets the start window for which new WIP pacts will be pulled down for verification, regardless of the tag.
See the docs and this article for more background.
For each interaction in a pact file, the order of execution is as follows:
BeforeEach
-> StateHandler
-> RequestFilter (pre)
-> Execute Provider Test
-> RequestFilter (post)
-> AfterEach
If any of the middleware or hooks fail, the tests will also fail.
Using a Pact Broker is recommended for any serious workloads, you can run your own one or use a hosted broker.
By integrating with a Broker, you get much more advanced collaboration features and can take advantage of automation tools, such as the can-i-deploy tool, which can tell you at any point in time, which component is safe to release.
See the Pact Broker documentation for more details on the Broker.
p := Publisher{}
err := p.Publish(types.PublishRequest{
PactURLs: []string{"./pacts/my_consumer-my_provider.json"},
PactBroker: "http://pactbroker:8000",
ConsumerVersion: "1.0.0",
Tags: []string{"master", "dev"},
})
If you're using a Pact Broker (e.g. a hosted one at pact.dius.com.au), you can publish your verification results so that consumers can query if they are safe to release.
It looks like this:
You need to specify the following:
PublishVerificationResults: true,
ProviderVersion: "1.0.0",
NOTE: You need to be already pulling pacts from the broker for this feature to work.
Use a cURL request like the following to PUT the pact to the right location, specifying your consumer name, provider name and consumer version.
curl -v \
-X PUT \
-H "Content-Type: application/json" \
-d@spec/pacts/a_consumer-a_provider.json \
http://your-pact-broker/pacts/provider/A%20Provider/consumer/A%20Consumer/version/1.0.0
The following flags are required to use basic authentication when publishing or retrieving Pact files with a Pact Broker:
BrokerUsername
- the username for Pact Broker basic authentication.BrokerPassword
- the password for Pact Broker basic authentication.
The following flags are required to use bearer token authentication when publishing or retrieving Pact files with a Pact Broker:
BrokerToken
- the token to authenticate with (excluding the"Bearer"
prefix)
Modern distributed architectures are increasingly integrated in a decoupled, asynchronous fashion. Message queues such as ActiveMQ, RabbitMQ, SQS, Kafka and Kinesis are common, often integrated via small and frequent numbers of microservices (e.g. lambda).
Furthermore, the web has things like WebSockets which involve bidirectional messaging.
Pact now has experimental support for these use cases, by abstracting away the protocol and focussing on the messages passing between them.
For further reading and introduction into this topic, see this article and our example for a more detailed overview of these concepts.
A Consumer is the system that will be reading a message from a queue or some intermediary - like a Kinesis stream, websocket or S3 bucket - and be able to handle it.
From a Pact testing point of view, Pact takes the place of the intermediary and confirms whether or not the consumer is able to handle a request.
The following test creates a contract for a Dog API handler:
// 1 Given this handler that accepts a User and returns an error
userHandler := func(u User) error {
if u.ID == -1 {
return errors.New("invalid object supplied, missing fields (id)")
}
// ... actually consume the message
return nil
}
// 2 We write a small adapter that will take the incoming dsl.Message
// and call the function with the correct type
var userHandlerWrapper = func(m dsl.Message) error {
return userHandler(*m.Content.(*User))
}
// 3 Create the Pact Message Consumer
pact := dsl.Pact {
return dsl.Pact{
Consumer: "PactGoMessageConsumer",
Provider: "PactGoMessageProvider",
}
}
// 4 Write the consumer test, and call VerifyMessageConsumer
// passing through the function
func TestMessageConsumer_Success(t *testing.T) {
message := pact.AddMessage()
message.
Given("some state").
ExpectsToReceive("some test case").
WithMetadata(commonHeaders).
WithContent(map[string]interface{}{
"id": like(127),
"name": "Baz",
"access": eachLike(map[string]interface{}{
"role": term("admin", "admin|controller|user"),
}, 3),
})
AsType(&User{}) // Optional
pact.VerifyMessageConsumer(t, message, userHandlerWrapper)
}
Explanation:
- The API - a contrived API handler example. Expects a User object and throws an
Error
if it can't handle it.- In most applications, some form of transactionality exists and communication with a MQ/broker happens.
- It's important we separate out the protocol bits from the message handling bits, so that we can test that in isolation.
- Creates the MessageConsumer class
- Setup the expectations for the consumer - here we expect a
User
object with three fields - Pact will send the message to your message handler. If the handler does not error, the message is saved, otherwise the test fails. There are a few key things to consider:
- The actual request body that Pact will invoke on your handler will be contained within a
dsl.Message
object along with other context, so the body must be retrieved viaContent
attribute. If you setMessage.AsType(T)
this object will be mapped for you. If you don't want Pact to perform the conversion, you may do so on the object (dsl.Message.Content
) or on the raw JSON (dsl.Message.ContentRaw
). - All handlers to be tested must be of the shape
func(dsl.Message) error
- that is, they must accept aMessage
and return anerror
. This is how we get around all of the various protocols, and will often require a lightweight adapter function to convert it. - In this case, we wrap the actual
userHandler
withuserHandlerWrapper
provided by Pact.
- The actual request body that Pact will invoke on your handler will be contained within a
A Provider (Producer in messaging parlance) is the system that will be putting a message onto the queue.
As per the Consumer case, Pact takes the position of the intermediary (MQ/broker) and checks to see whether or not the Provider sends a message that matches the Consumer's expectations.
functionMappings := dsl.MessageProviders{
"some test case": func(m dsl.Message) (interface{}, error) {
fmt.Println("Calling provider function that is responsible for creating the message")
res := User{
ID: 44,
Name: "Baz",
Access: []AccessLevel{
{Role: "admin"},
{Role: "admin"},
{Role: "admin"}},
}
return res, nil
},
}
// Verify the Provider with local Pact Files
pact.VerifyMessageProvider(t, types.VerifyMessageRequest{
PactURLs: []string{filepath.ToSlash(fmt.Sprintf("%s/pactgomessageconsumer-pactgomessageprovider.json", pactDir))},
}, functionMappings)
Explanation:
- Our API client contains a single function
createDog
which is responsible for generating the message that will be sent to the consumer via some message queue - We configure Pact to stand-in for the queue. The most important bit here is the
handlers
block- Similar to the Consumer tests, we map the various interactions that are going to be verified as denoted by their
description
field. In this case,a request for a dog
, maps to thecreateDog
handler. Notice how this matches the original Consumer test.
- Similar to the Consumer tests, we map the various interactions that are going to be verified as denoted by their
- We can now run the verification process. Pact will read all of the interactions specified by its consumer, and invoke each function that is responsible for generating that message.
As per HTTP APIs, you can publish contracts and verification results to a Broker.
In addition to verbatim value matching, we have 3 useful matching functions
in the dsl
package that can increase expressiveness and reduce brittle test
cases.
Rather than use hard-coded values which must then be present on the Provider side, you can use regular expressions and type matches on objects and arrays to validate the structure of your APIs.
Matchers can be used on the Body
, Headers
, Path
and Query
fields of the dsl.Request
type, and the Body
and Headers
fields of the dsl.Response
type.
dsl.Like(content)
tells Pact that the value itself is not important, as long
as the element type (valid JSON number, string, object etc.) itself matches.
dsl.EachLike(content, min)
- tells Pact that the value should be an array type,
consisting of elements like those passed in. min
must be >= 1. content
may
be a valid JSON value: e.g. strings, numbers and objects.
dsl.Term(example, matcher)
- tells Pact that the value should match using
a given regular expression, using example
in mock responses. example
must be
a string. *
NOTE: One caveat to note, is that you will need to use valid Ruby regular expressions and double escape backslashes.
Example:
Here is a more complex example that shows how all 3 terms can be used together:
body :=
Like(map[string]interface{}{
"response": map[string]interface{}{
"name": Like("Billy"),
"type": Term("admin", "admin|user|guest"),
"items": EachLike("cat", 2)
},
})
This example will result in a response body from the mock server that looks like:
{
"response": {
"name": "Billy",
"type": "admin",
"items": ["cat", "cat"]
}
}
Often times, you find yourself having to re-write regular expressions for common formats. We've created a number of them for you to save you the time:
method | description |
---|---|
Identifier() |
Match an ID (e.g. 42) |
Integer() |
Match all numbers that are integers (both ints and longs) |
Decimal() |
Match all real numbers (floating point and decimal) |
HexValue() |
Match all hexadecimal encoded strings |
Date() |
Match string containing basic ISO8601 dates (e.g. 2016-01-01) |
Timestamp() |
Match a string containing an RFC3339 formatted timestapm (e.g. Mon, 31 Oct 2016 15:21:41 -0400) |
Time() |
Match string containing times in ISO date format (e.g. T22:44:30.652Z) |
IPv4Address() |
Match string containing IP4 formatted address |
IPv6Address() |
Match string containing IP6 formatted address |
UUID() |
Match strings containing UUIDs |
Furthermore, if you isolate your Data Transfer Objects (DTOs) to an adapters package so that they exactly reflect the interface between you and your provider, then you can leverage dsl.Match
to auto-generate the expected response body in your contract tests. Under the hood, Match
recursively traverses the DTO struct and uses Term, Like, and EachLike
to create the contract.
This saves the trouble of declaring the contract by hand. It also maintains one source of truth. To change the consumer-provider interface, you only have to update your DTO struct and the contract will automatically follow suit.
Example:
type DTO struct {
ID string `json:"id"`
Title string `json:"title"`
Tags []string `json:"tags" pact:"min=2"`
Date string `json:"date" pact:"example=2000-01-01,regex=^\\d{4}-\\d{2}-\\d{2}$"`
}
then specifying a response body is as simple as:
// Set up our expected interactions.
pact.
AddInteraction().
Given("User foo exists").
UponReceiving("A request to get foo").
WithRequest(dsl.Request{
Method: "GET",
Path: "/foobar",
Headers: map[string]string{"Content-Type": "application/json"},
}).
WillRespondWith(dsl.Response{
Status: 200,
Headers: map[string]string{"Content-Type": "application/json"},
Body: Match(DTO{}), // That's it!!!
})
The pact
struct tags shown above are optional. By default, dsl.Match just asserts that the JSON shape matches the struct and that the field types match.
See dsl.Match for more information.
See the matcher tests for more matching examples.
Learn everything in Pact Go in 60 minutes: https://github.com/pact-foundation/pact-workshop-go
There are number of examples we use as end-to-end integration test prior to releasing a new binary, including publishing to a Pact Broker. To enable them, set the following environment variables
make pact
Once these variables have been exported, cd into one of the directories containing a test and run go test -v .
:
Pact tests tend to be quite long, due to the need to be specific about request/response payloads. Often times it is nicer to be able to split your tests across multiple files for manageability.
You have two options to achieve this feat:
-
Set
PactFileWriteMode
to"merge"
when creating aPact
struct:This will allow you to have multiple independent tests for a given Consumer-Provider pair, without it clobbering previous interactions.
See this PR for background.
NOTE: If using this approach, you must be careful to clear out existing pact files (e.g.
rm ./pacts/*.json
) before you run tests to ensure you don't have left over requests that are no longer relevent. -
Create a Pact test helper to orchestrate the setup and teardown of the mock service for multiple tests.
In larger test bases, this can reduce test suite time and the amount of code you have to manage.
Pact Go uses a simple log utility (logutils) to filter log messages. The CLI already contains flags to manage this, should you want to control log level in your tests, you can set it like so:
pact := Pact{
...
LogLevel: "DEBUG", // One of TRACE, DEBUG, INFO, ERROR, NONE
}
TRACE
level logging will print the entire request/response cycle.
Pact ships with a CLI that you can also use to check if the tools are up to date. Simply run pact-go install
, exit status 0
is good, 1
or higher is bad.
Pact relies on a number of CLI tools for successful operation, and it performs some pre-emptive checks
during test runs to ensure that everything will run smoothly. This check, unfortunately, can add up
if spread across a large test suite. You can disable the check by setting the environment variable PACT_DISABLE_TOOL_VALIDITY_CHECK=1
or specifying it when creating a dsl.Pact
struct:
dsl.Pact{
...
DisableToolValidityCheck: true,
}
You can then check if the CLI tools are up to date as part of your CI process once up-front and speed up the rest of the process!
Sometimes you want to target a specific test for debugging an issue or some other reason.
This is easy for the consumer side, as each consumer test can be controlled
within a valid *testing.T
function, however this is not possible for Provider verification.
But there is a way! Given an interaction that looks as follows (taken from the message examples):
message := pact.AddMessage()
message.
Given("user with id 127 exists").
ExpectsToReceive("a user").
WithMetadata(commonHeaders).
WithContent(map[string]interface{}{
"id": like(127),
"name": "Baz",
"access": eachLike(map[string]interface{}{
"role": term("admin", "admin|controller|user"),
}, 3),
}).
AsType(&types.User{})
and the function used to run provider verification is go test -run TestMessageProvider
, you can test the verification of this specific interaction by setting two environment variables PACT_DESCRIPTION
and PACT_PROVIDER_STATE
and re-running the command. For example:
cd examples/message/provider
PACT_DESCRIPTION="a user" PACT_PROVIDER_STATE="user with id 127 exists" go test -v .
Supply your own TLS configuration to customise the behaviour of the runtime:
_, err := pact.VerifyProvider(t, types.VerifyRequest{
ProviderBaseURL: "https://localhost:8080",
PactURLs: []string{filepath.ToSlash(fmt.Sprintf("%s/consumer-selfsignedtls.json", pactDir))},
CustomTLSConfig: &tls.Config{
RootCAs: getCaCertPool(), // Specify a custom CA pool
// InsecureSkipVerify: true, // Disable SSL verification altogether
},
})
See self-signed certificate for an example.
AWS changed their certificate authority last year, and not all OSs have the latest CA chains. If you can't update to the latest certificate bunidles, see "Verifying APIs with a self-signed certificate" for how to work around this.
or
- Twitter: @pact_up
- Stack Overflow: https://stackoverflow.com/questions/tagged/pact
Additional documentation can be found at the main Pact website and in the Pact Wiki.
The roadmap for Pact and Pact Go is outlined on our main website. Detail on the native Go implementation can be found here.
See CONTRIBUTING.