h2non / gock

HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽
https://pkg.go.dev/github.com/h2non/gock
MIT License
2.04k stars 106 forks source link

client timeout not working #69

Closed jan4984 closed 4 years ago

jan4984 commented 4 years ago
context.WithTimeout()
http.DefaultClient.Do(taskReq.WithContext(cxt))

not working when mocking with gock.

Any idea to test the timeout?

h2non commented 4 years ago

You can try this: https://pkg.go.dev/github.com/h2non/gock?tab=doc#Response.Delay

Note: delayed response is still experimental.

jan4984 commented 4 years ago

@h2non Yes I do delay with Response.Delay, but client timeout error not return

h2non commented 4 years ago

To make the delay error effective, you should run the request in a goroutine. Also, make sure the http.Transport of the http.Client has a reduced timeout tolerance.

jan4984 commented 4 years ago

Yes maybe http.Transport problem with httptest.NewRecorder(). Must I run the testing in real tcp network?

the Testing function:

res := httptest.NewRecorder()
defer gock.Off()
//gock.New(aiEp).Post("/asr/v1/tasks").ReplyError(errors.New("simulate timeout error"))
gock.New(aiEp).Post("/asr/v1/tasks").Reply(200).Delay(time.Second * 3)
handleXXXXX(res, req)

the /asr/v1/tasks post handler

cxt, canF := context.WithTimeout(context.Background(), time.Second * 2)
defer canF()
...
l.Debug().Time("xlStart", time.Now()).Msg("start xxxx")
resp, err := http.DefaultClient.Do(taskReq.WithContext(cxt))
l.Debug().Time("xlEnd", time.Now()).Msg("end xxxx)

running the testing, I can not get timeout err return after 2 seconds, but get the norman reply after 3 seconds.

h2non commented 4 years ago

Since you are not touching any network layer with this mocking/testing strategy, I would suggest you to simply return an artificially generated error in the mock simulating a native net/tcp timeout error.

timeoutErr := errors.New("dial tcp i/o timeout")
gock.New(aiEp).Post("/asr/v1/tasks").Reply(200).SetError(timeoutErr)
jan4984 commented 4 years ago

OK. Since httptest is a official http testing package, please consider adding some support to it for network lantency testing.