diff --git a/pkg/health/health_check_test.go b/pkg/health/health_check_test.go index ba36249578c..3997adac92b 100644 --- a/pkg/health/health_check_test.go +++ b/pkg/health/health_check_test.go @@ -96,3 +96,104 @@ func TestFindPort(t *testing.T) { t.Errorf("Expected %v, got %v", want, got) } } + +func TestHTTPHealthChecker(t *testing.T) { + httpHealthCheckerTests := []struct { + probe *api.HTTPGetProbe + status int + health Status + }{ + {&api.HTTPGetProbe{Host: "httptest"}, http.StatusOK, Healthy}, + {&api.HTTPGetProbe{}, http.StatusOK, Healthy}, + {nil, -1, Unknown}, + {&api.HTTPGetProbe{Port: "-1"}, -1, Unknown}, + } + hc := &HTTPHealthChecker{ + client: &http.Client{}, + } + for _, httpHealthCheckerTest := range httpHealthCheckerTests { + tt := httpHealthCheckerTest + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tt.status) + })) + u, err := url.Parse(ts.URL) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + host, port, err := net.SplitHostPort(u.Host) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + container := api.Container{ + LivenessProbe: &api.LivenessProbe{ + HTTPGet: tt.probe, + Type: "http", + }, + } + params := container.LivenessProbe.HTTPGet + if params != nil { + if params.Port == "" { + params.Port = port + } + if params.Host == "httptest" { + params.Host = host + } + } + health, err := hc.HealthCheck(container) + if tt.health == Unknown && err == nil { + t.Errorf("Expected error") + } + if tt.health != Unknown && err != nil { + t.Errorf("Unexpected error: %v", err) + } + if health != tt.health { + t.Errorf("Expected %v, got %v", tt.health, health) + } + } +} + +func TestMuxHealthChecker(t *testing.T) { + muxHealthCheckerTests := []struct { + health Status + probeType string + }{ + {Healthy, "http"}, + {Unknown, "ftp"}, + } + mc := &MuxHealthChecker{ + checkers: make(map[string]HealthChecker), + } + hc := &HTTPHealthChecker{ + client: &http.Client{}, + } + mc.checkers["http"] = hc + for _, muxHealthCheckerTest := range muxHealthCheckerTests { + tt := muxHealthCheckerTest + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + })) + u, err := url.Parse(ts.URL) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + host, port, err := net.SplitHostPort(u.Host) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + container := api.Container{ + LivenessProbe: &api.LivenessProbe{ + HTTPGet: &api.HTTPGetProbe{}, + }, + } + container.LivenessProbe.Type = tt.probeType + container.LivenessProbe.HTTPGet.Port = port + container.LivenessProbe.HTTPGet.Host = host + health, err := mc.HealthCheck(container) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + if health != tt.health { + t.Errorf("Expected %v, got %v", tt.health, health) + } + } +}