如何在读取响应正文时强加错误 [英] How to force error on reading response body

查看:84
本文介绍了如何在读取响应正文时强加错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在go中编写了http客户端包装程序,我需要对其进行彻底的测试. 我正在使用包装器中的ioutil.ReadAll阅读响应正文.我在弄清楚如何在httptest的帮助下如何强制从响应正文读取失败时遇到了麻烦.

I've written http client wrapper in go and I need to test it thoroughly. I'm reading the response body with ioutil.ReadAll within the wrapper. I'm having a bit of trouble figuring out how I can force a read from the response body to fail with the help of httptest.

package req

func GetContent(url string) ([]byte, error) {
    response, err := httpClient.Get(url)
    // some header validation goes here
    body, err := ioutil.ReadAll(response.Body)
    defer response.Body.Close()

    if err != nil {
        errStr := fmt.Sprintf("Unable to read from body %s", err)
        return nil, errors.New(errStr)
    }

    return body, nil
}

我假设我可以像这样设置一个假服务器:

I'm assuming I can set up a fake server as such:

package req_test

func Test_GetContent_RequestBodyReadError(t *testing.T) {

    handler := func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
    }

    ts := httptest.NewServer(http.HandlerFunc(handler))
    defer ts.Close()

    _, err := GetContent(ts.URL)

    if err != nil {
        t.Log("Body read failed as expected.")
    } else {
        t.Fatalf("Method did not fail as expected")
    }

}

我假设我需要修改ResposeWriter.现在,有什么方法可以修改responseWriter,从而迫使包装器中的ioutil.ReadAll失败吗?

I'm assuming I need to modify the ResposeWriter. Now, is there any way for me to modify the responseWriter and thereby force the ioutil.ReadAll in the wrapper to fail?

我意识到您似乎认为这是

I realize that you seem to think it's a duplicate of this post and while you may believe so or it might be, just marking it as a duplicate doesn't really help me. The code provided in the answers in the "duplicate" post makes very little sense to me in this context.

推荐答案

检查 Response.Body 以查看何时从中读取可能会返回错误:

Check the documentation of Response.Body to see when reading from it might return an error:

// Body represents the response body.
//
// The response body is streamed on demand as the Body field
// is read. If the network connection fails or the server
// terminates the response, Body.Read calls return an error.
//
// The http Client and Transport guarantee that Body is always
// non-nil, even on responses without a body or responses with
// a zero-length body. It is the caller's responsibility to
// close Body. The default HTTP client's Transport may not
// reuse HTTP/1.x "keep-alive" TCP connections if the Body is
// not read to completion and closed.
//
// The Body is automatically dechunked if the server replied
// with a "chunked" Transfer-Encoding.
Body io.ReadCloser

最简单的方法是从测试处理程序生成无效的HTTP响应.

The easiest way is to generate an invalid HTTP response from the test handler.

该怎么做?有很多方法,一种简单的方法是撒谎"内容的长度:

How to do that? There are many ways, a simple one is to "lie" about the content length:

handler := func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Length", "1")
}

此处理程序告诉它具有1个字节的正文,但实际上不发送任何字节.因此,在另一端(客户端)尝试从中读取1个字节时,显然不会成功,并且会导致以下错误:

This handler tells it has 1 byte body, but actually it sends none. So at the other end (the client) when attempting to read 1 byte from it, obviously that won't succeed, and will result in the following error:

Unable to read from body unexpected EOF

请参见相关问题,是否需要模拟从请求正文(而不是响应正文)读取错误:

See related question if you would need to simulate error reading from a request body (not from a response body): How do I test an error on reading from a request body?

这篇关于如何在读取响应正文时强加错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆