如何测试客户端代码是否正确超时处理对外部服务器的 API 请求?

huangapple go评论89阅读模式
英文:

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()}

huangapple
  • 本文由 发表于 2021年10月22日 11:02:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/69670930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定