英文:
How to test if client side code correctly timeout API request to external server
问题
你好,以下是你要翻译的内容:
嗨,我有以下的GoLang代码片段。
func executeAuthorisationRequest(request http.Request) (*AuthorisationResponse, error) {
var response AuthResponse
client := &http.Client{
Timeout: time.Second * 10
}
requestResult, requestError := client.Do(&request)
if requestError != nil {
log.Error(fmt.Sprintf("Some error %s", request.Error()))
}
}
请求在这里创建
func creatRequest(url string, body url.Values) (*http.Request, error){
req, reqError := http.NewRequest(http.MethodPost, url, strings.NewReader(body.Encode()))
if reqError != nil {
// 错误处理
}
req.Header.Add("Content-Type", "some business logic")
return request, nil
}
我正在尝试创建一个测试用例,如果服务器端的API处理时间过长,我的客户端代码将在10秒后超时。我该如何模拟/创建这样的测试用例?
我无法访问服务器端的代码。
如果能给予指导,将不胜感激,请指点我正确的方向。
英文:
Hi I have this following GoLang code snippet.
func executeAuthorisationRequest(request http.Request) (*AuthorisationResponse, error) {
var response AuthResponse
client := &http.Client{
Timeout: time.Second * 10
}
requestResult, requestError := client.Do(&request)
if requestError != nil {
log.Error(fmt.Sprintf("Some error %s", request.Error()))
}
}
The request is created here
func creatRequest(url string, body url.Values) (*http.Request, error){
req,reqError := http.NewRequest(http.MethodPost,url,strings.NewReader(body.Encode()))
if reqError != nil {
//Error handle
}
req.Header.Add("Content-Type","some business logic")
return request,nil
}
I am trying to create a testcase that my client side code will timeout after 10 seconds if the server sided API is taking too long, how do I simulate/create a testcase like this
I do not have access to the server sided code
Any guidance will be highly appreciate please point me in right direction.
答案1
得分: 2
你需要使用httptest
库。
示例代码如下:
func TestTimeout(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Second * 15)
}))
defer ts.Close()
client := &http.Client{
Timeout: time.Second * 10,
}
res, err := client.Get(ts.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
}
英文:
You need lib httptest
example:
func TestTimeout(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Second * 15)
}))
defer ts.Close()
client := &http.Client{
Timeout: time.Second * 10,
}
res, err := client.Get(ts.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论