在我的程序中發現泄漏之後,我已經解決了這個問題。但是,現在我試圖找出如何「測試」在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
謝謝你的提示,我會研究這些。但是,這並不能回答我的問題:我如何在測試中測試泄漏? –