dtm37893 2019-06-23 12:26
浏览 221

测试http.Response.Body已关闭

I'm searching for an easy way to test that http.Response.Body.Close() was called.

I already tried this by counting the number of open connections to the server (https://golang.org/src/net/http/serve_test.go - countCloseListener), but it seems that it only is testable on the client side, via rewriting the Roundtripper.

So the following example works, but I'm wondering whether there is an easier way for such a common task...

package closing

import "net/http"

type MyClient struct {
    Client http.Client
}

func (c *MyClient) Closing() (err error) {
    res, err := c.Client.Get("http://localhost")
    defer res.Body.Close()
    return
}

func (c *MyClient) NotClosing() (err error) {
    _, err = c.Client.Get("http://localhost")
    return
}

https://github.com/elgohr/golang-test-body-close/blob/master/performsHttpRequest.go

package closing_test

import (
    "github.com/elgohr/closing"
    "io"
    "io/ioutil"
    "net/http"
    "strings"
    "testing"
)

func TestShouldBeClosedWhenClosed(t *testing.T) {
    tripper := NewFakeRoundTripper()
    cl := closing.MyClient{
        Client: http.Client{
            Transport: tripper,
        },
    }

    if err := cl.Closing(); err != nil {
        t.Error(err)
    }

    if !tripper.Body.Closed {
        t.Error("Should be closed, but wasn't")
    }
}

func TestShouldBeOpenWhenNotClosed(t *testing.T) {
    tripper := NewFakeRoundTripper()
    cl := closing.MyClient{
        Client: http.Client{
            Transport: tripper,
        },
    }

    if err := cl.NotClosing(); err != nil {
        t.Error(err)
    }

    if tripper.Body.Closed {
        t.Error("Should be open, but wasn't")
    }
}

func NewFakeRoundTripper() *FakeRoundTripper {
    return &FakeRoundTripper{
        Body: &FakeReadCloser{
            ReadCloser: ioutil.NopCloser(strings.NewReader("content")),
        },
    }
}

type FakeRoundTripper struct {
    Body *FakeReadCloser
}

func (r *FakeRoundTripper) RoundTrip(*http.Request) (*http.Response, error) {
    return &http.Response{
        Body: r.Body,
    }, nil
}

type FakeReadCloser struct {
    io.ReadCloser
    Closed bool
}

func (r *FakeReadCloser) Close() error {
    r.Closed = true
    return r.ReadCloser.Close()
}

https://github.com/elgohr/golang-test-body-close/blob/master/performsHttpRequest_test.go

  • 写回答

0条回答

    报告相同问题?

    悬赏问题

    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
    • ¥15 保护模式-系统加载-段寄存器
    • ¥15 电脑桌面设定一个区域禁止鼠标操作