MCPcopy
hub / github.com/keploy/keploy / startRefuseThenServe

Function startRefuseThenServe

pkg/util_simulate_refuse_integration_test.go:19–44  ·  view source on GitHub ↗

startRefuseThenServe reserves a free port, releases it so connects are REFUSED for `refuse`, then re-binds it and serves GET /ping -> 200 {"msg":"pong"}. This reproduces an app container that briefly refuses connections while it is still coming up (the CI contention scenario the retry exists for).

(t *testing.T, refuse time.Duration)

Source from the content-addressed store, hash-verified

17// This reproduces an app container that briefly refuses connections while it is
18// still coming up (the CI contention scenario the retry exists for).
19func startRefuseThenServe(t *testing.T, refuse time.Duration) (baseURL string, stop func()) {
20 t.Helper()
21 l, err := net.Listen("tcp", "127.0.0.1:0")
22 if err != nil {
23 t.Fatalf("reserve port: %v", err)
24 }
25 addr := l.Addr().String()
26 _ = l.Close() // the port now actively refuses until we re-bind below
27
28 mux := http.NewServeMux()
29 mux.HandleFunc("/ping", func(w http.ResponseWriter, _ *http.Request) {
30 w.Header().Set("Content-Type", "application/json")
31 w.WriteHeader(http.StatusOK)
32 _, _ = w.Write([]byte(`{"msg":"pong"}`))
33 })
34 srv := &http.Server{Handler: mux}
35 go func() {
36 time.Sleep(refuse) // connects to addr are refused during this window
37 ln, lerr := net.Listen("tcp", addr)
38 if lerr != nil {
39 return
40 }
41 _ = srv.Serve(ln)
42 }()
43 return "http://" + addr, func() { _ = srv.Close() }
44}
45
46func pingTestCase(baseURL string) *models.TestCase {
47 return &models.TestCase{

Calls 4

CloseMethod · 0.65
WriteMethod · 0.65
StringMethod · 0.45
SetMethod · 0.45

Tested by

no test coverage detected