在我的程序中发现泄漏之后,我已经解决了这个问题。但是,现在我试图找出如何“测试”在Go测试中泄漏连接?这是我的问题。如何在Go测试中测试泄漏连接?
我试图改变在我的测试中的请求数量,没关系。无论我做什么,测试中的当前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
}
夹具工人lsof
的输出:https://pastebin.com/fDUkpYsE
测试的输出:https://pastebin.com/uGpK0czn
测试从来没有泄漏,而它泄漏灯具的工人。
Fixture Worker正在使用与测试相同的代码来请求http获取使用myhttp包。
你根本没有在读身体,http客户端通过完全抛弃连接来保存你的连接(这不是保证行为,也不能被依赖)。 'GetWithTimeout'也打破了关闭身体的记录模式,在有合法的响应时添加一个错误值。这意味着调用者无法知道机构是否需要关闭或不出错,而不会以某种方式检查“ErrStatus”,可能导致更多的泄漏。我不明白'dialFunc'的原因,你现在应该使用'DialContext'。 – JimB
谢谢你的提示,我会研究这些。但是,这并不能回答我的问题:我如何在测试中测试泄漏? –