登录
首页 >  Golang >  Go问答

处理强制读取响应主体错误

来源:stackoverflow

时间:2024-03-20 15:15:29 395浏览 收藏

如何测试 HTTP 客户端包装器中的读取响应主体失败情况?通过使用 httptest 模拟一个假服务器,并修改 responsewriter 以强制读取失败。一种简单的方法是在内容长度上“撒谎”,即声明有 1 个字节的主体,但实际上不发送任何内容。这样,当客户端尝试从中读取 1 个字节时,就会导致 unexpected eof 错误。

问题内容

我已经用 go 编写了 http 客户端包装器,我需要彻底测试它。 我正在使用包装器中的 ioutil.readall 读取响应正文。我在弄清楚如何在 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
}

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

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失败吗?

我意识到您似乎认为它是这篇文章的重复项,尽管您可能相信或可能如此,但仅将其标记为重复项并不能真正帮助我。在这种情况下,“重复”帖子的答案中提供的代码对我来说没有什么意义。


解决方案


检查 Response.Body 的文档,看看读取它时可能会返回错误:

// 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 响应。

如何做到这一点?方法有很多,一种简单的方法就是在内容长度上“撒谎”:

handler := func(w http.responsewriter, r *http.request) {
    w.header().set("content-length", "1")
}

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

unable to read from body unexpected eof

如果您需要模拟从请求正文(而不是从响应正文)读取错误,请参阅相关问题:How do I test an error on reading from a request body?

要扩展 icza 的出色答案,您还可以使用 httptest 来完成此操作。 server 对象:

bodyerrorserver := httptest.newserver(http.handlerfunc(func(w http.responsewriter, r *http.request) {
  w.header().set("content-length", "1")
}))

defer bodyerrorserver.close()

然后,您可以像平常一样在测试中传递 bodyerrorserver.url ,并且您将始终收到 eof 错误:

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/http/httptest"
    "testing"
    "time"
)

func getBodyFromURL(service string, clientTimeout int) (string, error) {

    var netClient = &http.Client{
        Timeout: time.Duration(clientTimeout) * time.Millisecond,
    }

    rsp, err := netClient.Get(service)
    if err != nil {
        return "", err
    }

    defer rsp.Body.Close()

    if rsp.StatusCode != 200 {
        return "", fmt.Errorf("HTTP request error. Response code: %d", rsp.StatusCode)
    }

    buf, err := ioutil.ReadAll(rsp.Body)
    if err != nil {
        return "", err
    }

    return string(bytes.TrimSpace(buf)), nil
}

func TestBodyError(t *testing.T) {

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

    _, err := getBodyFromURL(bodyErrorServer.URL, 1000)

    if err.Error() != "unexpected EOF" {
        t.Error("GOT AN ERROR")
    } else if err == nil {
            t.Error("GOT NO ERROR, THATS WRONG!")
    } else {
        t.Log("Got an unexpected EOF as expected, horray!")
    }
}

演示示例在这里:https://play.golang.org/p/JzPmatibgZn

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>