Skip to content

Commit f7dda3b

Browse files
committed
refactor(examples): make examples more consistent for readability
1 parent 0346784 commit f7dda3b

File tree

16 files changed

+100
-114
lines changed

16 files changed

+100
-114
lines changed

README.md

Lines changed: 31 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ Read [Getting started with Pact] for more information for beginners.
8989
## Versions
9090

9191
<details><summary>Specification Compatibility</summary>
92+
9293
| Version | Stable | [Spec] Compatibility | Install |
9394
| ------- | ---------- | -------------------- | ------------------ |
9495
| 1.0.x | Yes | 2, 3\* | See [installation] |
@@ -149,70 +150,60 @@ We'll run through a simple example to get an understanding the concepts:
149150
The simple example looks like this:
150151

151152
```go
152-
package main
153-
154-
import (
155-
"fmt"
156-
"log"
157-
"net/http"
158-
"strings"
159-
"testing"
160-
161-
"github.com/pact-foundation/pact-go/dsl"
162-
)
163-
164-
// Example Pact: How to run me!
165-
// 1. cd <pact-go>/examples
166-
// 2. go test -v -run TestConsumer
167153
func TestConsumer(t *testing.T) {
154+
type struct {
155+
Name string `json:"name" pact:"example=billy"`
156+
LastName string `json:"lastName" pact:"example=sampson"`
157+
}
168158

169-
// Create Pact client
159+
// Create Pact connecting to local Daemon
170160
pact := &dsl.Pact{
171161
Consumer: "MyConsumer",
172162
Provider: "MyProvider",
163+
Host: "localhost",
173164
}
174165
defer pact.Teardown()
175166

176-
// Pass in test case
177-
var test = func() error {
167+
// Pass in test case. This is the component that makes the external HTTP call
168+
var test = func() (err error) {
178169
u := fmt.Sprintf("http://localhost:%d/foobar", pact.Server.Port)
179-
req, err := http.NewRequest("GET", u, strings.NewReader(`{"s":"foo"}`))
170+
req, _ := http.NewRequest("GET", u, strings.NewReader(`{"name":"billy"}`))
180171

181172
// NOTE: by default, request bodies are expected to be sent with a Content-Type
182173
// of application/json. If you don't explicitly set the content-type, you
183174
// will get a mismatch during Verification.
184175
req.Header.Set("Content-Type", "application/json")
185-
if err != nil {
186-
return err
187-
}
188-
if _, err = http.DefaultClient.Do(req); err != nil {
189-
return err
190-
}
191-
192-
return err
176+
req.Header.Set("Authorization", "Bearer 1234")
177+
178+
_, err = http.DefaultClient.Do(req); err != nil {
179+
return
193180
}
194181

195182
// Set up our expected interactions.
196183
pact.
197184
AddInteraction().
198-
Given("User 1 exists").
199-
UponReceiving("A request to get user 1").
185+
Given("User foo exists").
186+
UponReceiving("A request to get foo").
200187
WithRequest(dsl.Request{
201188
Method: "GET",
202-
Path: dsl.String("/users/1"),
203-
Headers: dsl.MapMatcher{"Content-Type": "application/json"},
189+
Path: dsl.String("/foobar"),
190+
Headers: dsl.MapMatcher{"Content-Type": dsl.String("application/json"), "Authorization": dsl.String("Bearer 1234")},
191+
Body: map[string]string{
192+
"name": "billy",
193+
},
204194
}).
205195
WillRespondWith(dsl.Response{
206196
Status: 200,
207-
Headers: dsl.MapMatcher{"Content-Type": "application/json"},
208-
Body: dsl.Match(&Foo{})
197+
Headers: dsl.MapMatcher{"Content-Type": dsl.String("application/json")},
198+
Body: dsl.Match(&User{}),
209199
})
210200

211-
// Verify
201+
// Run the test, verify it did what we expected and capture the contract
212202
if err := pact.Verify(test); err != nil {
213203
log.Fatalf("Error on Verify: %v", err)
214204
}
215205
}
206+
216207
```
217208
218209
### Provider API Testing
@@ -259,7 +250,7 @@ Here is the Provider test process broker down:
259250
// Start provider API in the background
260251
go startServer()
261252

262-
// Verify the Provider with local Pact Files
253+
// Verify the Provider using the locally saved Pact Files
263254
pact.VerifyProvider(t, types.VerifyRequest{
264255
ProviderBaseURL: "http://localhost:8000",
265256
PactURLs: []string{filepath.ToSlash(fmt.Sprintf("%s/myconsumer-myprovider.json", pactDir))},
@@ -282,9 +273,6 @@ Note that `PactURLs` may be a list of local pact files or remote based
282273
urls (e.g. from a
283274
[Pact Broker](http://docs.pact.io/documentation/sharings_pacts.html)).
284275
285-
See the `Skip()'ed` [integration tests](https://github.com/pact-foundation/pact-go/blob/master/dsl/pact_test.go)
286-
for a more complete E2E example.
287-
288276
#### Provider Verification
289277
290278
When validating a Provider, you have 3 options to provide the Pact files:
@@ -311,7 +299,7 @@ When validating a Provider, you have 3 options to provide the Pact files:
311299
})
312300
```
313301
314-
1. Use `BrokerURL` and `Tags` to automatically find all of the latest consumers:
302+
1. Use `BrokerURL` and `Tags` to automatically find all of the latest consumers given one or more tags:
315303
316304
```go
317305
pact.VerifyProvider(t, types.VerifyRequest{
@@ -366,18 +354,18 @@ Read more about [Provider States](https://docs.pact.io/getting_started/provider_
366354
367355
#### Before and After Hooks
368356
369-
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 `BeforeHook` runs before any other part of the Pact test lifecycle, and a `AfterHook` runs as the last step before returning the verification result back to the test.
357+
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.
370358
371359
You can add them to your Verification as follows:
372360
373361
```go
374362
pact.VerifyProvider(t, types.VerifyRequest{
375363
...
376-
BeforeHook: func() error {
364+
BeforeEach: func() error {
377365
fmt.Println("before hook, do something")
378366
return nil
379367
},
380-
AfterHook: func() error {
368+
AfterEach: func() error {
381369
fmt.Println("after hook, do something")
382370
return nil
383371
},
@@ -437,7 +425,7 @@ _Important Note_: You should only use this feature for things that can not be pe
437425
438426
For each _interaction_ in a pact file, the order of execution is as follows:
439427
440-
`BeforeHook` -> `StateHandler` -> `RequestFilter (pre)`, `Execute Provider Test` -> `RequestFilter (post)` -> `AfterHook`
428+
`BeforeEach` -> `StateHandler` -> `RequestFilter (pre)`, `Execute Provider Test` -> `RequestFilter (post)` -> `AfterEach`
441429
442430
If any of the middleware or hooks fail, the tests will also fail.
443431
@@ -756,7 +744,6 @@ for more matching examples.
756744

757745
- [API Consumer](https://github.com/pact-foundation/pact-go/tree/master/examples/)
758746
- [Golang ServeMux](https://github.com/pact-foundation/pact-go/tree/master/examples/mux)
759-
- [Go Kit](https://github.com/pact-foundation/pact-go/tree/master/examples/go-kit)
760747
- [Gin](https://github.com/pact-foundation/pact-go/tree/master/examples/gin)
761748

762749
### Asynchronous APIs

client/service.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/*
2-
Package client implements the raw interface to the Pact CLI tools: The Pact Mock Service and Provider Verification
3-
"binaries."
2+
Package client is an internal package, implementing the raw interface to the
3+
Pact CLI tools: The Pact Mock Service and Provider Verification "binaries."
44
55
See https://github.com/pact-foundation/pact-provider-verifier and
66
https://github.com/bethesque/pact-mock_service for more on the Ruby "binaries".

command/version.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ var versionCmd = &cobra.Command{
1212
Short: "Print the version number of Pact Go",
1313
Long: `All software has versions. This is Pact Go's`,
1414
Run: func(cmd *cobra.Command, args []string) {
15-
fmt.Println("Pact Go CLI v1.0.0-beta.3, using CLI tools version", cliToolsVersion)
15+
fmt.Println("Pact Go CLI v1.0.0-beta.4, using CLI tools version", cliToolsVersion)
1616
},
1717
}
1818

dsl/pact.go

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,7 @@ func (p *Pact) WritePact() error {
297297
// VerifyProviderRaw reads the provided pact files and runs verification against
298298
// a running Provider API, providing raw response from the Verification process.
299299
//
300-
// Order of events: beforeHook, stateHandlers, requestFilter(pre <execute provider> post), afterHook
300+
// Order of events: BeforeEach, stateHandlers, requestFilter(pre <execute provider> post), AfterEach
301301
func (p *Pact) VerifyProviderRaw(request types.VerifyRequest) (types.ProviderVerifierResponse, error) {
302302
p.Setup(false)
303303
var res types.ProviderVerifierResponse
@@ -310,12 +310,12 @@ func (p *Pact) VerifyProviderRaw(request types.VerifyRequest) (types.ProviderVer
310310

311311
m := []proxy.Middleware{}
312312

313-
if request.BeforeHook != nil {
314-
m = append(m, beforeHookMiddleware(request.BeforeHook))
313+
if request.BeforeEach != nil {
314+
m = append(m, BeforeEachMiddleware(request.BeforeEach))
315315
}
316316

317-
if request.AfterHook != nil {
318-
m = append(m, afterHookMiddleware(request.AfterHook))
317+
if request.AfterEach != nil {
318+
m = append(m, AfterEachMiddleware(request.AfterEach))
319319
}
320320

321321
if len(request.StateHandlers) > 0 {
@@ -406,15 +406,15 @@ var checkCliCompatibility = func() {
406406
}
407407
}
408408

409-
// beforeHookMiddleware is invoked before any other, only on the __setup
409+
// BeforeEachMiddleware is invoked before any other, only on the __setup
410410
// request (to avoid duplication)
411-
func beforeHookMiddleware(beforeHook types.Hook) proxy.Middleware {
411+
func BeforeEachMiddleware(BeforeEach types.Hook) proxy.Middleware {
412412
return func(next http.Handler) http.Handler {
413413
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
414414
if r.URL.Path == "/__setup" {
415415

416416
log.Println("[DEBUG] executing before hook")
417-
err := beforeHook()
417+
err := BeforeEach()
418418

419419
if err != nil {
420420
log.Println("[ERROR] error executing before hook:", err)
@@ -426,17 +426,17 @@ func beforeHookMiddleware(beforeHook types.Hook) proxy.Middleware {
426426
}
427427
}
428428

429-
// afterHookMiddleware is invoked after any other, and is the last
429+
// AfterEachMiddleware is invoked after any other, and is the last
430430
// function to be called prior to returning to the test suite. It is
431431
// therefore not invoked on __setup
432-
func afterHookMiddleware(afterHook types.Hook) proxy.Middleware {
432+
func AfterEachMiddleware(AfterEach types.Hook) proxy.Middleware {
433433
return func(next http.Handler) http.Handler {
434434
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
435435
next.ServeHTTP(w, r)
436436

437437
if r.URL.Path != "/__setup" {
438438
log.Println("[DEBUG] executing after hook")
439-
err := afterHook()
439+
err := AfterEach()
440440

441441
if err != nil {
442442
log.Println("[ERROR] error executing after hook:", err)

dsl/pact_test.go

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -264,11 +264,11 @@ func TestPact_VerifyProviderRaw(t *testing.T) {
264264
ProviderBaseURL: "http://www.foo.com",
265265
PactURLs: []string{"foo.json", "bar.json"},
266266
RequestFilter: dummyMiddleware,
267-
BeforeHook: func() error {
267+
BeforeEach: func() error {
268268
fmt.Println("aeuaoseu")
269269
return nil
270270
},
271-
AfterHook: func() error {
271+
AfterEach: func() error {
272272
fmt.Println("aeuaoseu")
273273
return nil
274274
},
@@ -383,7 +383,7 @@ func TestPact_AddInteraction(t *testing.T) {
383383
}
384384
}
385385

386-
func TestPact_BeforeHook(t *testing.T) {
386+
func TestPact_BeforeEach(t *testing.T) {
387387
var called bool
388388

389389
req, err := http.NewRequest("GET", "/__setup", nil)
@@ -394,7 +394,7 @@ func TestPact_BeforeHook(t *testing.T) {
394394

395395
rr := httptest.NewRecorder()
396396

397-
mw := beforeHookMiddleware(func() error {
397+
mw := BeforeEachMiddleware(func() error {
398398
called = true
399399
return nil
400400
})
@@ -410,7 +410,7 @@ func TestPact_BeforeHook(t *testing.T) {
410410
t.Error("expected http handler to be invoked")
411411
}
412412
}
413-
func TestPact_BeforeHookNotSetupPath(t *testing.T) {
413+
func TestPact_BeforeEachNotSetupPath(t *testing.T) {
414414
var called bool
415415

416416
req, err := http.NewRequest("GET", "/blah", nil)
@@ -421,7 +421,7 @@ func TestPact_BeforeHookNotSetupPath(t *testing.T) {
421421

422422
rr := httptest.NewRecorder()
423423

424-
mw := beforeHookMiddleware(func() error {
424+
mw := BeforeEachMiddleware(func() error {
425425
called = true
426426
return nil
427427
})
@@ -437,7 +437,7 @@ func TestPact_BeforeHookNotSetupPath(t *testing.T) {
437437
t.Error("expected http handler to be invoked")
438438
}
439439
}
440-
func TestPact_AfterHook(t *testing.T) {
440+
func TestPact_AfterEach(t *testing.T) {
441441
var called bool
442442

443443
req, err := http.NewRequest("GET", "/blah", nil)
@@ -448,7 +448,7 @@ func TestPact_AfterHook(t *testing.T) {
448448

449449
rr := httptest.NewRecorder()
450450

451-
mw := afterHookMiddleware(func() error {
451+
mw := AfterEachMiddleware(func() error {
452452
called = true
453453
return nil
454454
})
@@ -464,7 +464,7 @@ func TestPact_AfterHook(t *testing.T) {
464464
t.Error("expected http handler to be invoked")
465465
}
466466
}
467-
func TestPact_AfterHookSetupPath(t *testing.T) {
467+
func TestPact_AfterEachSetupPath(t *testing.T) {
468468
var called bool
469469

470470
req, err := http.NewRequest("GET", "/__setup", nil)
@@ -475,7 +475,7 @@ func TestPact_AfterHookSetupPath(t *testing.T) {
475475

476476
rr := httptest.NewRecorder()
477477

478-
mw := afterHookMiddleware(func() error {
478+
mw := AfterEachMiddleware(func() error {
479479
called = true
480480
return nil
481481
})

examples/README.md

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,13 @@ how Pact could be used in each.
66
Each Provider API currently exposes a single `Login` endpoint at `POST /login/1`,
77
which the [Consumer](consumer/goconsumer) uses to authenticate a User.
88

9-
We test 3 scenarios, highlighting the use of [Provider States](/pact-foundation/pact-go#provider#provider-states):
9+
We test 5 scenarios, highlighting the use of [Provider States](/pact-foundation/pact-go#provider#provider-states), [Hooks](/pact-foundation/pact-go#before-and-after-hooks) and [RequestFilters](/pact-foundation/pact-go#request-filters):
1010

1111
1. When the user "jmarie" exists, and we perform a login, we expect an HTTP `200`
1212
1. When the user "jmarie" does not exists, and we perform a login, we expect an HTTP `404`
1313
1. When the user "jmarie" is unauthorized, and we perform a login, we expect an HTTP `403`
14+
1. When the user is authenticated, and we request to get the user 'jmarie', we expect an HTTP `200`
15+
1. When the user is unauthenticated, and we request to get the user 'jmarie', we expect an HTTP `401`
1416

1517
# Getting started
1618

@@ -23,7 +25,7 @@ go get ./...
2325

2426
## Providers
2527

26-
1. [Go-Kit](go-kit)
28+
1. [Mux](mux)
2729
2. [Gin](gin)
2830

2931
## Consumer
@@ -46,12 +48,12 @@ This will generate a Pact file in `./pacts/jmarie-loginprovider.json`.
4648

4749
### Running the Consumer
4850

49-
Before you can run the consumer make sure the provider is
50-
[running](#running-the-provider).
51+
Before you can run the consumer make sure one of the providers is
52+
running first. You can then run:
5153

5254
```
5355
go run cmd/web/main.go
5456
```
5557

5658
Hit http://localhost:8081/ in your browser. You can use the username/password
57-
combination of "billy" / "issilly" to authenticate.
59+
combination of "jmarie" / "issilly" to authenticate.

examples/consumer/goconsumer/user_service_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ func TestPactConsumerGetUser_Unauthenticated(t *testing.T) {
298298
pact.
299299
AddInteraction().
300300
Given("User jmarie is unauthenticated").
301-
UponReceiving("A request to login with user 'jmarie'").
301+
UponReceiving("A request to get with user 'jmarie'").
302302
WithRequest(request{
303303
Method: "GET",
304304
Path: s("/users/10"),

0 commit comments

Comments
 (0)