Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(mock): add Mock() support HTTP mocking #23

Merged
merged 1 commit into from
Feb 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,33 @@ baseRequest.Timeout(10 * time.Millisecond).
resp, body, errs := baseRequest.Clone().Get("http://exmaple.com/").End()
```

## Mock

You can mock the response of gorequest via [gock](https://github.com/h2non/gock)

```go
func TestMock(t *testing.T) {
defer gock.Off()

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

resp, body, errs := New().Mock().Get("http://foo.com/bar").SetDebug(true).End()
if len(errs) != 0 {
t.Fatalf("Expected no error, got error")
}
if resp.StatusCode != 200 {
t.Fatalf("Expected status code 200, got %d", resp.StatusCode)
}

if strings.Trim(body, " \n") != `{"foo":"bar"}` {
t.Fatalf("Expected body `{\"foo\":\"bar\"}`, got `%s`", body)
}
}
```

## Debug

For debugging, GoRequest leverages `httputil` to dump details of every request/response. (Thanks to @dafang)
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ require (
github.com/smartystreets/goconvey v1.7.2 // indirect
github.com/spf13/cast v1.4.1
golang.org/x/net v0.0.0-20211216030914-fe4d6282115f
gopkg.in/h2non/gock.v1 v1.1.2
moul.io/http2curl v1.0.0
)
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@ github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2 h1:dWB6v3RcOy0
github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2/go.mod h1:gNh8nYJoAm43RfaxurUnxr+N1PwuFV3ZMl/efxlIlY8=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw=
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4=
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-charset v0.0.0-20180617210344-2471d30d28b4/go.mod h1:qgYeAmZ5ZIpBWTGllZSQnw97Dj+woV0toclVaRGI8pc=
Expand All @@ -31,5 +35,7 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
gopkg.in/h2non/gock.v1 v1.1.2 h1:jBbHXgGBK/AoPVfJh5x4r/WxIrElvbLel8TCZkkZJoY=
gopkg.in/h2non/gock.v1 v1.1.2/go.mod h1:n7UGz/ckNChHiK05rDoiC4MYSunEC/lyaUm2WWaDva0=
moul.io/http2curl v1.0.0 h1:6XwpyZOYsgZJrU8exnG87ncVkU1FVCcTRpwzOkTDUi8=
moul.io/http2curl v1.0.0/go.mod h1:f6cULg+e4Md/oW1cYmwW4IWQOVl2lGbmCNGOHvzX2kE=
13 changes: 12 additions & 1 deletion gorequest.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (

"github.com/spf13/cast"
"golang.org/x/net/publicsuffix"
"gopkg.in/h2non/gock.v1"
"moul.io/http2curl"
)

Expand Down Expand Up @@ -65,6 +66,7 @@ type SuperAgent struct {
DoNotClearSuperAgent bool
isClone bool
ctx context.Context
isMock bool
}

var DisableTransportSwap = false
Expand Down Expand Up @@ -98,6 +100,7 @@ func New() *SuperAgent {
logger: log.New(os.Stderr, "[gorequest]", log.LstdFlags),
isClone: false,
ctx: nil,
isMock: false,
}
// disable keep alives by default, see this issue https://github.com/parnurzeal/gorequest/issues/75
s.Transport.DisableKeepAlives = true
Expand Down Expand Up @@ -149,6 +152,7 @@ func (s *SuperAgent) Clone() *SuperAgent {
DoNotClearSuperAgent: true,
isClone: true,
ctx: s.ctx,
isMock: s.isMock,
}
return clone
}
Expand All @@ -158,6 +162,13 @@ func (s *SuperAgent) Context(ctx context.Context) *SuperAgent {
return s
}

// Mock will enable gock, http mocking for net/http
func (s *SuperAgent) Mock() *SuperAgent {
gock.InterceptClient(s.Client)
s.isMock = true
return s
}

// SetDebug enable the debug mode which logs request/response detail.
func (s *SuperAgent) SetDebug(enable bool) *SuperAgent {
s.Debug = enable
Expand Down Expand Up @@ -1175,7 +1186,7 @@ func (s *SuperAgent) getResponseBytes() (Response, []byte, []error) {
}

// Set Transport
if !DisableTransportSwap {
if !DisableTransportSwap && !s.isMock {
s.Client.Transport = s.Transport
}

Expand Down
22 changes: 22 additions & 0 deletions gorequest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"time"

"github.com/elazarl/goproxy"
"gopkg.in/h2non/gock.v1"
)

type (
Expand Down Expand Up @@ -2688,3 +2689,24 @@ func TestContext(t *testing.T) {
t.Fatalf("Expected context deadline exceeded error, got %v", errs[0].Error())
}
}

func TestMock(t *testing.T) {
defer gock.Off()

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

resp, body, errs := New().Mock().Get("http://foo.com/bar").SetDebug(true).End()
if len(errs) != 0 {
t.Fatalf("Expected no error, got error")
}
if resp.StatusCode != 200 {
t.Fatalf("Expected status code 200, got %d", resp.StatusCode)
}

if strings.Trim(body, " \n") != `{"foo":"bar"}` {
t.Fatalf("Expected body `{\"foo\":\"bar\"}`, got `%s`", body)
}
}