RestAPI contract Testing with Golang

adkarigar
2 min readOct 5, 2020

--

Part-I : visit this blog before this Part-II :)

will keep the explaination Short , and more hands on….

  1. In the First part , we had the consumer application and pact file
    published to the broker running in docker-container.
  2. ProviderService was a basic Application exposing Rest-End points.
    this Provider was verified using pact-verifier CLI

lets take the part-I code which is in python , lets publish the pact to broker
after running

$ python -m unittest build_test.py

which will push to the pact file to the broker

now lets write the ProviderService and ProviderVerificationTest in Golang.

Prerequisite:

https://github.com/pact-foundation/pact-ruby-standalone/releases/tag/v1.88.11

downloaded the pact-1.88.11-win32.zip for windows
unzip the zip and add path to environment variables.
this comes with -:
pact-broker.bat
, pact-mock-service.bat, pact-provider-verifier.bat

which is required when running the ProviderVerification in Golang

lets dive into the code content of provider_test.go

var provider_app_url = "http://localhost:3001"
var broker_url = "http://192.168.99.114"

note:
1. provider_app_url = provider API will be started in the background by go routine.
2. broker_url = in my case , i am running pact-broker in docker , hence 192.168.99.114 is my docker-machine ip.

func TestProvider(t *testing.T) {
pact := &dsl.Pact{
Consumer: "Consumer",
Producer: "Producer",
}
go startServer() pact.VerifyProvider(t, types.VerifyRequest {
ProviderBaseUrl: provider_app_url,
BrokerURL: broker_url,
StateHandlers: types.StateHandlers{
"build 3455 exists": func() error {
return nil
},
},
BrokerUsername: "pactbroker",
BrokerPassword: "pactbroker",
PublishVerificationResults: true,
ProviderVersion: "latest",
})
}

here , we are verifying the provider with pact files in pact-broker.
BrokerUsername, BrokerPassword are given in docker-compose file for pact-broker environment variables.

func startServer() {
mux:= http.NewServerMux()
mux.HandleFunc("/builds/3455",func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type","application/json")
fmt.Fprintf(w,fmt.Sprintf(`{}`))
})
log.Fatal(http.ListenAndServe("localhost:3001",mux))
}

this function is the providerService handling the GET request for /builds/3455

lets run this providerPact and publish the results.

$ go test -v -run TestProvider

lets see the output

Test Provider-Verification
verification
after successful verification of the provider, we can see the results published in the Last Verified column

the entire code can be found in this gist file

that’s all folks, take it easy…..

Reference:

https://github.com/pact-foundation/pact-go/blob/master/examples/provider_test.go

--

--