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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 delta降尺度方法,未来数据怎么降尺度
    • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
    • ¥15 高德地图点聚合中Marker的位置无法实时更新
    • ¥15 DIFY API Endpoint 问题。
    • ¥20 sub地址DHCP问题
    • ¥15 delta降尺度计算的一些细节,有偿
    • ¥15 Arduino红外遥控代码有问题
    • ¥15 数值计算离散正交多项式
    • ¥30 数值计算均差系数编程
    • ¥15 redis-full-check比较 两个集群的数据出错