如何在Go测试中测试连接是否泄漏?

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

How to test for leaking connections in a Go test?

问题

在我找到程序中的漏洞后,我解决了这个问题。然而,现在我正在尝试找出如何在Go测试中"<i>测试</i>"泄漏的连接。这是我的问题。

我尝试改变测试中的请求数量,但没有用。无论我做什么,测试中当前的TCP连接数量都保持不变。

func TestLeakingConnections(t *testing.T) {
    getter := myhttp.New()

    s := newServer(ok)
    defer s.Close()

    cur := tcps(t)
    for i := 0; i < 1000; i++ {
        r, _ := getter.GetWithTimeout(s.URL, time.Millisecond*10)
        r.Body.Close()
    }

    for tries := 10; tries >= 0; tries-- {
        growth := tcps(t) - cur
        if growth > 5 {
            t.Error("leaked")
            return
        }
    }
}

// find tcp connections
func tcps(t *testing.T) (conns int) {
    lsof, err := exec.Command("lsof", "-n", "-p", strconv.Itoa(os.Getpid())).Output()
    if err != nil {
        t.Skip("skipping test; error finding or running lsof")
    }

    for _, ls := range strings.Split(string(lsof), "\n") {
        if strings.Contains(ls, "TCP") {
            conns++
        }
    }
    return
}

func newServer(f http.HandlerFunc) *httptest.Server {
    return httptest.NewServer(http.HandlerFunc(f))
}

func ok(w http.ResponseWriter, r *http.Request) {
    w.Header().Add("Content-Type", "application/xml")
    io.WriteString(w, "<xml></xml>")
}

// myhttp package

// ...other code omitted for clarification

func (g *Getter) GetWithTimeout(
    url string,
    timeout time.Duration,
) (
    *http.Response, error,
) {
    // this is the leaking part
    // moving this out of here will stop leaks
    transport := http.Transport{
        DialContext: (&net.Dialer{
            Timeout: timeout,
        }).DialContext,
        TLSHandshakeTimeout:   timeout,
        ResponseHeaderTimeout: timeout,
        ExpectContinueTimeout: timeout,
    }

    client := http.Client{
        Timeout:   timeout,
        Transport: &transport,
    }

    return client.Get(url)
}

// fixture worker package

// some outside code injects getter into fixture_worker like this:
getter := myhttp.New()

// NewWithTimeout creates a new fetcher with timeout threshold
func NewWithTimeout(
    getter myhttp.HTTPGetter,
    fetchURL string,
    timeout time.Duration,
) *Fetcher {
    return &Fetcher{getter, fetchURL, timeout}
}

// Fetch fetches fixture xml
func (f *Fetcher) Fetch() (*parser.FixtureXML, error) {
    res, err := f.getter.GetWithTimeout(f.fetchURL, f.timeout)
    if err != nil {
        if res != nil && res.Body != nil {
            res.Body.Close()
        }
        return nil, errors.Wrap(err, ErrFetch.Error())
    }
    defer res.Body.Close()

    ioutil.ReadAll(res.Body)

    return &parser.FixtureXML{}, nil
}

fixture worker的lsof输出:https://pastebin.com/fDUkpYsE

测试的输出:https://pastebin.com/uGpK0czn

测试从不泄漏,而fixture worker泄漏。

fixture worker使用与测试相同的代码,使用myhttp包请求http获取。

英文:

After I've found leaks in my program, I've solved the problem. However, now I'm trying to find out how to "<i> test </i>" leaking connections in a Go test? This is my question.

I've tried to change the number of requests in my test, didn't matter. No matter what I do, the current number of TCP connections in my test stay the same.

func TestLeakingConnections(t *testing.T) {
getter := myhttp.New()
s := newServer(ok)
defer s.Close()
cur := tcps(t)
for i := 0; i &lt; 1000; i++ {
r, _ := getter.GetWithTimeout(s.URL, time.Millisecond*10)
r.Body.Close()
}
for tries := 10; tries &gt;= 0; tries-- {
growth := tcps(t) - cur
if growth &gt; 5 {
t.Error(&quot;leaked&quot;)
return
}
}
}
// find tcp connections
func tcps(t *testing.T) (conns int) {
lsof, err := exec.Command(&quot;lsof&quot;, &quot;-n&quot;, &quot;-p&quot;, strconv.Itoa(os.Getpid())).Output()
if err != nil {
t.Skip(&quot;skipping test; error finding or running lsof&quot;)
}
for _, ls := range strings.Split(string(lsof), &quot;\n&quot;) {
if strings.Contains(ls, &quot;TCP&quot;) {
conns++
}
}
return
}
func newServer(f http.HandlerFunc) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(f))
}
func ok(w http.ResponseWriter, r *http.Request) {
w.Header().Add(&quot;Content-Type&quot;, &quot;application/xml&quot;)
io.WriteString(w, &quot;&lt;xml&gt;&lt;/xml&gt;&quot;)
}
// myhttp package
// ...other code omitted for clarification
func (g *Getter) GetWithTimeout(
url string,
timeout time.Duration,
) (
*http.Response, error,
) {
// this is the leaking part
// moving this out of here will stop leaks
transport := http.Transport{
DialContext: (&amp;net.Dialer{
Timeout: timeout,
}).DialContext,
TLSHandshakeTimeout:   timeout,
ResponseHeaderTimeout: timeout,
ExpectContinueTimeout: timeout,
}
client := http.Client{
Timeout:   timeout,
Transport: &amp;transport,
}
return client.Get(url)
}
// fixture worker package
// some outside code injects getter into fixture_worker like this:
getter := myhttp.New()
// NewWithTimeout creates a new fetcher with timeout threshold
func NewWithTimeout(
getter myhttp.HTTPGetter,
fetchURL string,
timeout time.Duration,
) *Fetcher {
return &amp;Fetcher{getter, fetchURL, timeout}
}
// Fetch fetches fixture xml
func (f *Fetcher) Fetch() (*parser.FixtureXML, error) {
res, err := f.getter.GetWithTimeout(f.fetchURL, f.timeout)
if err != nil {
if res != nil &amp;&amp; res.Body != nil {
res.Body.Close()
}
return nil, errors.Wrap(err, ErrFetch.Error())
}
defer res.Body.Close()
ioutil.ReadAll(res.Body)
return &amp;parser.FixtureXML{}, nil
}

如何在Go测试中测试连接是否泄漏?


Output of fixture worker lsof: https://pastebin.com/fDUkpYsE

Output of test: https://pastebin.com/uGpK0czn

Test never leaks whereas fixture worker it leaks.

Fixture worker is using the same code as the test, to request http gets using myhttp package.

答案1

得分: 0

如果你希望你的测试能够代表实际情况,你需要以与在测试之外相同的方式使用它。在这种情况下,你没有读取任何响应,并且传输过程会尽快丢弃无法重用的连接,以防止连接丢失。

读取响应将使用连接,并使其处于“泄漏”状态。你还需要正确处理所有情况下的错误,并始终需要Close()响应体。处理HTTP响应并确保其关闭的模式非常简单,不一定需要进行测试(参见https://stackoverflow.com/questions/33238518/what-could-happen-if-i-dont-close-response-body-in-golang/33238755#33238755):

resp, err := GetWithTimeout(s.URL)
if err != nil {
    t.Fatal(err)
}
ioutil.ReadAll(resp.Body)
resp.Body.Close()

这种方法可能有限的用处,因为最常见的错误和响应处理问题会导致错误,而你没有测试这一点,因为测试需要一开始就正确处理它们。

剩下的问题是,你的GetWithTimeout方法返回一个错误值和一个有效的HTTP响应,这与HTTP包的文档以及大多数用户的期望相矛盾。如果你要插入一个错误,最好在同一点处理响应,以确保关闭和丢弃响应体。

最后,GetWithTimeout的大部分内容都是多余的,因为不仅每次创建传输是不正确的,而且每个请求创建一个http.Client通常是不必要的,因为它们是可重用的并且对并发使用是安全的。

英文:

If you want your test to represent reality, you need to use it in the same manner that you do outside of tests. In this case you're not reading any of the responses, and the transport happens to be preventing lost connections because it's discarding them as quickly as possible since they can't be reused.

Reading the response will use the connection, and get it into a state where it's "leaked". You also need to properly handle errors in all cases, and you always need to Close() the response body. The pattern to handle an http response and make sure it's closed is very simple, and doesn't necessarily require testing (see https://stackoverflow.com/questions/33238518/what-could-happen-if-i-dont-close-response-body-in-golang/33238755#33238755)

	resp, err := GetWithTimeout(s.URL)
if err != nil {
t.Fatal(err)
}
ioutil.ReadAll(resp.Body)
resp.Body.Close()

This is arguably of limited usefulness, since the most common bugs would result from improper error and response handling, and you're not testing that because the test needs to do it correctly in the first place.

The remaining problem here is that your GetWithTimeout method returns an error value and a valid http response, which contradicts the http package documentation as well as most user's expectations. If you're going to insert an error, it would be better to also handle the response at the same point to ensure the body is closed and discarded.

Finally, most of GetWithTimeout is superfluous, since not only is creating Transports every time incorrect, but creating an http.Client every request is usually unnecessary as they are meant to be reused and are safe for concurrent use.

huangapple
  • 本文由 发表于 2017年8月18日 08:26:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/45746753.html
匿名

发表评论

匿名网友

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

确定