亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在測試期間同步測試服務器

在測試期間同步測試服務器

Go
慕無忌1623718 2023-06-26 18:06:05
摘要:我在測試過程中遇到了競爭狀況,我的服務器在向其發出客戶端請求之前尚未可靠地準備好服務請求。如何僅在偵聽器準備好之前進行阻止,并且仍然維護可組合的公共 API,而不要求用戶 BYO net.Listener?client.Do(req)我們看到以下錯誤,因為在我們調用測試函數之前,在后臺啟動(阻塞)服務器的 goroutine 沒有監聽TestRun。--- FAIL: TestRun/Server_accepts_HTTP_requests (0.00s)         /home/matt/repos/admission-control/server_test.go:64: failed to make a request: Get https://127.0.0.1:37877: dial tcp 127.0.0.1:37877: connect: connection refused我沒有httptest.Server直接使用,因為我正在嘗試測試我自己的服務器組件的阻止和取消特性。我創建一個,在使用 啟動它后將httptest.NewUnstartedServer其克隆*tls.Config到一個新的中,然后在調用 之前將其關閉。這還有一個好處是為我提供了配置了匹配的 RootCA。http.ServerStartTLS()*AdmissionServer.Run()*http.Client測試 TLS 在這里很重要,因為它公開的守護進程存在于僅 TLS 的環境中。func newTestServer(ctx context.Context, t *testing.T) *httptest.Server {    testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {        fmt.Fprintln(w, "OK")    })    testSrv := httptest.NewUnstartedServer(testHandler)    admissionServer, err := NewServer(nil, &noopLogger{})    if err != nil {        t.Fatalf("admission server creation failed: %s", err)        return nil    }    // We start the test server, copy its config out, and close it down so we can    // start our own server. This is because httptest.Server only generates a    // self-signed TLS config after starting it.    testSrv.StartTLS()    admissionServer.srv = &http.Server{        Addr:      testSrv.Listener.Addr().String(),        Handler:   testHandler,        TLSConfig: testSrv.TLS.Clone(),    }    testSrv.Close()    // We need a better synchronization primitive here that doesn't block    // but allows the underlying listener to be ready before     // serving client requests.    go func() {        if err := admissionServer.Run(ctx); err != nil {            t.Fatalf("server returned unexpectedly: %s", err)        }    }()    return testSrv}
查看完整描述

1 回答

?
青春有我

TA貢獻1784條經驗 獲得超8個贊

作為初始化過程的一部分,您可以在啟動測試套件之前嘗試連接到服務器。


例如,我在測試中通常有這樣的函數:


// waitForServer attempts to establish a TCP connection to localhost:<port>

// in a given amount of time. It returns upon a successful connection;?

// ptherwise exits with an error.

func waitForServer(port string) {

? ? backoff := 50 * time.Millisecond


? ? for i := 0; i < 10; i++ {

? ? ? ? conn, err := net.DialTimeout("tcp", ":"+port, 1*time.Second)

? ? ? ? if err != nil {

? ? ? ? ? ? time.Sleep(backoff)

? ? ? ? ? ? continue

? ? ? ? }

? ? ? ? err = conn.Close()

? ? ? ? if err != nil {

? ? ? ? ? ? log.Fatal(err)

? ? ? ? }

? ? ? ? return

? ? }

? ? log.Fatalf("Server on port %s not up after 10 attempts", port)

}

然后在我的TestMain()我做:


func TestMain(m *testing.M) {

? ? go startServer()

? ? waitForServer(serverPort)


? ? // run the suite

? ? os.Exit(m.Run())

}


查看完整回答
反對 回復 2023-06-26
  • 1 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號