我可以为我的测试案例编写自己的go的http client.Do()函数版本吗?

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

Can I write my own version of go's http client.Do() function for my test cases?

问题

我有一个名为user-service.go的文件,以及相应的测试文件user-service_test.go。当我尝试获得完整的代码覆盖率时,我很难让一些错误条件真正发生。

这是函数:GetOrCreateByAccessToken()

// GetOrCreateByAccessToken 从数据库中获取具有给定访问令牌的用户
func (s *service) GetOrCreateByAccessToken(aT string, client *Client) (*user.User, fcerr.FCErr) {

  1. var currentUser user.OauthUser
  2. req, err := http.NewRequest("GET", "https://openidconnect.googleapis.com/v1/userinfo?access_token="+aT, nil)
  3. if err != nil {
  4. return nil, fcerr.NewInternalServerError("设置网络请求时出错")
  5. }
  6. response, err := client.httpClient.Do(req)
  7. if err != nil {
  8. fmt.Println("使用访问令牌获取用户信息时出错")
  9. return nil, fcerr.NewInternalServerError("尝试验证用户身份时出错")
  10. }
  11. defer response.Body.Close()
  12. contents, err := io.ReadAll(response.Body)
  13. if err != nil {
  14. return nil, fcerr.NewInternalServerError("尝试读取来自Google的有关用户身份的响应时出错")
  15. }

我测试的主要控制是我可以传入一个*Client。

这是测试用例的一部分,我希望io.ReadAll引发错误:

h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 手动返回Google在实际请求中返回的消息
w.Write([]byte(googleAPIOKResponse))
})
// 调用测试文件中定义的testHTTPClient()函数来替换自己的HandlerFunc
httpClient, teardown := testHTTPClient(h)
defer teardown()

// 调用我user-service.go中的真实NewClient()
client := NewClient()

// 将默认的httpClient替换为我刚刚设置的httpClient。
client.httpClient = httpClient

resultingUser, err := userService.GetOrCreateByAccessToken(nU.AccessToken, client)

assert.Nil(t, resultingUser)
assert.NotNil(t, err)
assert.Equal(t, http.StatusInternalServerError, err.Status())

有没有地方可以编写自己的.Do()方法的版本,以便在响应中放入某些内容,从而导致io.ReadAll返回错误?或者有没有更好的方法来实现只使用我已经使用的预先准备好的响应文本的错误?

英文:

I have a file, called user-service.go and the corresponding test file, called user-service_test.go. As I try to get complete code coverage, I am struggling to get some of the error conditions to actually happen.

Here is the function: GetOrCreateByAccessToken()

  1. //GetOrCreateByAccessToken gets a user from the database with the given access token
  2. func (s *service) GetOrCreateByAccessToken(aT string, client *Client) (*user.User, fcerr.FCErr) {
  3. var currentUser user.OauthUser
  4. req, err := http.NewRequest("GET", "https://openidconnect.googleapis.com/v1/userinfo?access_token="+aT, nil)
  5. if err != nil {
  6. return nil, fcerr.NewInternalServerError("Error when setting up the network request")
  7. }
  8. response, err := client.httpClient.Do(req)
  9. if err != nil {
  10. fmt.Println("error when getting the userinfo with the access token")
  11. return nil, fcerr.NewInternalServerError("Error when trying to verify user identity")
  12. }
  13. defer response.Body.Close()
  14. contents, err := io.ReadAll(response.Body)
  15. if err != nil {
  16. return nil, fcerr.NewInternalServerError("Error when trying to read response from Google about user identity")
  17. }

The main control I have for my tests is that I can pass in a *Client.

Here is the part of the test case where I'd like to have io.ReadAll throw an error:

  1. h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2. //manually return the message google would return on an actual request
  3. w.Write([]byte(googleAPIOKResponse))
  4. })
  5. //Call the testHTTPClient() function defined in the test file to substitute my own HandlerFunc
  6. httpClient, teardown := testHTTPClient(h)
  7. defer teardown()
  8. //Call the real NewClient() from my user-service.go
  9. client := NewClient()
  10. //Substitute the default httpClient for the one I've just set up.
  11. client.httpClient = httpClient
  12. resultingUser, err := userService.GetOrCreateByAccessToken(nU.AccessToken, client)
  13. assert.Nil(t, resultingUser)
  14. assert.NotNil(t, err)
  15. assert.Equal(t, http.StatusInternalServerError, err.Status())

Is there somewhere I can write my own version of the .Do() method which will put something in the response which will cause io.ReadAll to return an error? Or is there a better way to achieve the error with just the pre-baked response text I'm already using?

答案1

得分: 0

没有一种方法可以替换Do方法,但有一种方法可以实现你的目标。

创建一个round tripper类型,返回任意的响应体:

  1. type respondWithReader struct{ body io.Reader }
  2. func (rr respondWithReader) RoundTrip(req *http.Request) (*http.Response, error) {
  3. return &http.Response{
  4. Proto: "HTTP/1.0",
  5. ProtoMajor: 1,
  6. Header: make(http.Header),
  7. Close: true,
  8. Body: ioutil.NopCloser(rr.body),
  9. }, nil
  10. }

创建一个会失败的io.Reader:

  1. var errReadFail = errors.New("blah!")
  2. type failReader int
  3. func (failReader) Read([]byte) (int, error) {
  4. return 0, errReadFail
  5. }

使用上述的传输和读取器来使用默认的客户端:

  1. c := http.Client{Transport: respondWithReader{body: failReader(0)}}
  2. resp, err := c.Get("http://whatever.com")
  3. if err != nil {
  4. t.Error(err)
  5. }
  6. defer resp.Body.Close()
  7. // ReadAll返回errReadFail
  8. _, err = ioutil.ReadAll(resp.Body)
  9. if err != errReadFail {
  10. t.Errorf("got err %v, expect %v", err, errReadFail)
  11. }

在Go playground上运行测试:Run the test on the Go playground

英文:

There is not a way to replace the Do method, but there is a way to accomplish your goal.

Create a round tripper type that returns an arbitrary response body:

  1. type respondWithReader struct{ body io.Reader }
  2. func (rr respondWithReader) RoundTrip(req *http.Request) (*http.Response, error) {
  3. return &http.Response{
  4. Proto: "HTTP/1.0",
  5. ProtoMajor: 1,
  6. Header: make(http.Header),
  7. Close: true,
  8. Body: ioutil.NopCloser(rr.body),
  9. }, nil
  10. }

Create an io.Reader that fails:

  1. var errReadFail = errors.New("blah!")
  2. type failReader int
  3. func (failReader) Read([]byte) (int, error) {
  4. return 0, errReadFail
  5. }

Use the stock client with the transport and reader above:

  1. c := http.Client{Transport: respondWithReader{body: failReader(0)}}
  2. resp, err := c.Get("http://whatever.com")
  3. if err != nil {
  4. t.Error(err)
  5. }
  6. defer resp.Body.Close()
  7. // ReadAll returns errReadFail
  8. _, err = ioutil.ReadAll(resp.Body)
  9. if err != errReadFail {
  10. t.Errorf("got err %v, expect %v", err, errReadFail)
  11. }

Run the test on the Go playground.

huangapple
  • 本文由 发表于 2022年3月27日 08:30:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/71632844.html
匿名

发表评论

匿名网友

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

确定