github.com/argoproj/argo-cd/v3@v3.2.1/util/healthz/healthz_test.go (about) 1 package healthz 2 3 import ( 4 "errors" 5 "net" 6 "net/http" 7 "testing" 8 9 "github.com/stretchr/testify/require" 10 ) 11 12 func TestHealthCheck(t *testing.T) { 13 sentinel := false 14 15 serve := func(c chan<- string) { 16 // listen on first available dynamic (unprivileged) port 17 listener, err := net.Listen("tcp", ":0") 18 if err != nil { 19 panic(err) 20 } 21 22 // send back the address so that it can be used 23 c <- listener.Addr().String() 24 25 mux := http.NewServeMux() 26 ServeHealthCheck(mux, func(_ *http.Request) error { 27 if sentinel { 28 return errors.New("This is a dummy error") 29 } 30 return nil 31 }) 32 panic(http.Serve(listener, mux)) 33 } 34 35 c := make(chan string, 1) 36 37 // run a local webserver to test data retrieval 38 go serve(c) 39 40 address := <-c 41 t.Logf("Listening at address: %s", address) 42 43 server := "http://" + address 44 45 resp, err := http.Get(server + "/healthz") 46 require.NoError(t, err) 47 require.Equalf(t, http.StatusOK, resp.StatusCode, "Was expecting status code 200 from health check, but got %d instead", resp.StatusCode) 48 49 sentinel = true 50 51 resp, _ = http.Get(server + "/healthz") 52 require.Equalf(t, http.StatusServiceUnavailable, resp.StatusCode, "Was expecting status code 503 from health check, but got %d instead", resp.StatusCode) 53 }