h2non / gock

HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽

Home Page:https://pkg.go.dev/github.com/h2non/gock

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Simulate a http client get timeout

lneves12 opened this issue · comments

Is there a way to simulate a http client timeout?

I am struggling to find a way how to implement that.

It would be nice to have an example of that on the docs.

I am planning to open a PR with that, if I find a solution in the the meanwhile.

Thanks

Finally found a solution:

type timeoutError struct {
	err     string
	timeout bool
}

func (e *timeoutError) Error() string {
	return e.err
}
func (e *timeoutError) Timeout() bool {
	return e.timeout
}

func (e *timeoutError) Temporary() bool {
	return true
}

var _ = Describe("Testing", func() {
		It("client timeout", func() {
			defer gock.Off()

			gock.New("https://baseurl.com").
				Get("/url").
				ReplyError(&timeoutError{err: "net/http: timeout awaiting response headers", timeout: true})
		})
	})

})

I will open a PR later adding this to the examples list

commented

You can use the Delay(duration) method:
https://godoc.org/github.com/h2non/gock#Response.Delay

Alternatively, you can simulate the native timeout error via:
https://godoc.org/github.com/h2non/gock#Response.SetError

I tried the Dealy(duration) method, but I couldn't simulate the http.client timeout:

var httpClient = &http.Client{Timeout: 1 * time.Second}

I had to use the solution on my second comment. Not sure if it's the best solution though

commented

It depends on what type of error you want to simulate.
If you simply want to test the error handling for a timeout-like situation, that's fine.

yeah, I want to simulate an offline situation, where http.get will timeout. Do you think it's worth to add this as an example to docs? or should we just close the issue?

commented

Adding an example file here should be fine. Feel free to send a PR!