client timeout not working
jan4984 opened this issue · comments
context.WithTimeout()
http.DefaultClient.Do(taskReq.WithContext(cxt))
not working when mocking with gock.
Any idea to test the timeout?
You can try this:
https://pkg.go.dev/github.com/h2non/gock?tab=doc#Response.Delay
Note: delayed response is still experimental.
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.
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.
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)
OK. Since httptest
is a official http testing package, please consider adding some support to it for network lantency testing.