Skip to content

Commit

Permalink
feat(gock): add gock.Observe to support inspection of the outgoing in…
Browse files Browse the repository at this point in the history
…tercepted HTTP traffic
  • Loading branch information
steinfletcher committed Oct 14, 2018
1 parent db99161 commit 1cde9ef
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 0 deletions.
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,33 @@ func main() {
}
```

#### Debug intercepted http requests

```go
package main

import (
"bytes"
"gopkg.in/h2non/gock.v1"
"net/http"
)

func main() {
defer gock.Off()
gock.Observe(gock.DumpRequest)

gock.New("http://foo.com").
Post("/bar").
MatchType("json").
JSON(map[string]string{"foo": "bar"}).
Reply(200)

body := bytes.NewBuffer([]byte(`{"foo":"bar"}`))
http.Post("http://foo.com/bar", "application/json", body)
}

```

## Hacking it!

You can easily hack `gock` defining custom matcher functions with own matching rules.
Expand Down
21 changes: 21 additions & 0 deletions _examples/observe/observe.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package main

import (
"bytes"
"gopkg.in/h2non/gock.v1"
"net/http"
)

func main() {
defer gock.Off()
gock.Observe(gock.DumpRequest)

gock.New("http://foo.com").
Post("/bar").
MatchType("json").
JSON(map[string]string{"foo": "bar"}).
Reply(200)

body := bytes.NewBuffer([]byte(`{"foo":"bar"}`))
http.Post("http://foo.com/bar", "application/json", body)
}
21 changes: 21 additions & 0 deletions gock.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package gock

import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"regexp"
"sync"
Expand All @@ -14,8 +16,20 @@ var mutex = &sync.Mutex{}
var config = struct {
Networking bool
NetworkingFilters []FilterRequestFunc
Observer ObserverFunc
}{}

// ObserverFunc is implemented by users to inspect the outgoing intercepted HTTP traffic
type ObserverFunc func(*http.Request, Mock)

// DumpRequest is a default implementation of ObserverFunc that dumps
// the HTTP/1.x wire representation of the http request
var DumpRequest ObserverFunc = func(request *http.Request, mock Mock) {
bytes, _ := httputil.DumpRequestOut(request, true)
fmt.Println(string(bytes))
fmt.Printf("\nMatches: %v\n---\n", mock != nil)
}

// track unmatched requests so they can be tested for
var unmatchedRequests = []*http.Request{}

Expand Down Expand Up @@ -92,6 +106,13 @@ func OffAll() {
CleanUnmatchedRequest()
}

// Observe provides a hook to support inspection of the request and matched mock
func Observe(fn ObserverFunc) {
mutex.Lock()
defer mutex.Unlock()
config.Observer = fn
}

// EnableNetworking enables real HTTP networking
func EnableNetworking() {
mutex.Lock()
Expand Down
17 changes: 17 additions & 0 deletions gock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,23 @@ func TestMockRegExpMatching(t *testing.T) {
st.Expect(t, string(body)[:13], `{"foo":"bar"}`)
}

func TestObserve(t *testing.T) {
defer after()
var observedRequest *http.Request
var observedMock Mock
Observe(func(request *http.Request, mock Mock) {
observedRequest = request
observedMock = mock
})
New("http://observe-foo.com").Reply(200)
req, _ := http.NewRequest("POST", "http://observe-foo.com", nil)

http.DefaultClient.Do(req)

st.Expect(t, observedRequest.Host, "observe-foo.com")
st.Expect(t, observedMock.Request().URLStruct.Host, "observe-foo.com")
}

func after() {
Flush()
Disable()
Expand Down
5 changes: 5 additions & 0 deletions transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ func (m *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
return nil, err
}

// Invoke the observer with the intercepted http.Request and matched mock
if config.Observer != nil {
config.Observer(req, mock)
}

// Verify if should use real networking
networking := shouldUseNetwork(req, mock)
if !networking && mock == nil {
Expand Down

0 comments on commit 1cde9ef

Please sign in to comment.