我正在嘗試調試一個類似于以下內容的片狀單元測試:package mainimport ( "net" "net/http" "testing" "time" "github.com/stretchr/testify/require")func TestFlaky(t *testing.T) { // Mock an API http.HandleFunc("/foo/bar", func(w http.ResponseWriter, r *http.Request) { _, err := w.Write([]byte("foobar")) require.NoError(t, err) }) go func() { require.NoError(t, http.ListenAndServe("localhost:7777", nil)) }() // Wait (up to 1 second) for the mocked API to be available conn, err := net.DialTimeout("tcp", "localhost:7777", time.Second) require.NoError(t, err) require.NoError(t, conn.Close())}但是,從錯誤之后的行中,我收到以下錯誤(僅在CI環境中):require.NoError()DialTimeout --- FAIL: TestFlaky (0.00s) main_test.go:24: Error Trace: main_test.go:24 Error: Received unexpected error: dial tcp [::1]:7777: connect: connection refused Test: TestFlaky由于測試立即失敗,我猜這不是調整超時的問題。我應該如何使這個測試不片狀?我正在考慮將最后三行替換為類似于以下內容的行:require.Eventually var conn net.Conn require.Eventually(t, func() bool { var err error conn, err = net.DialTimeout("tcp", "localhost:7777", time.Second) if err != nil { t.Logf("DialTimeout error: %v. Retrying...", err) return false } return true }, time.Second, 100*time.Millisecond) require.NoError(t, conn.Close())這是否足以消除測試剝落?
1 回答

蠱毒傳說
TA貢獻1895條經驗 獲得超3個贊
goroutine內部的代碼不能保證在撥號之前執行(如果你在大流子之后睡覺,它應該可以工作,但這是一個丑陋的解決方案)。
另請注意,當連接穩定時,“超時撥號”正在等待 tcp 數據包,但拒絕的連接實際上是 RST 數據包。
提示:看看 httptest 包是如何工作的。
編輯:這是 httptest 的工作原理:https://cs.opensource.google/go/go/+/refs/tags/go1.16.6:src/net/http/httptest/server.go;l=304
func (s *Server) goServe() {
s.wg.Add(1)
go func() {
defer s.wg.Done()
s.Config.Serve(s.Listener)
}()
}
- 1 回答
- 0 關注
- 89 瀏覽
添加回答
舉報
0/150
提交
取消