knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/injection/health_check_test.go (about) 1 /* 2 Copyright 2023 The Knative Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package injection 18 19 import ( 20 "context" 21 "net/http" 22 "net/http/httptest" 23 "net/url" 24 "testing" 25 ) 26 27 func TestHealthCheckHandler(t *testing.T) { 28 tests := []struct { 29 name string 30 ctx context.Context 31 expectedReadiness int 32 expectedLiveness int 33 }{{ 34 name: "user provided no handlers, default health check handlers are used", 35 ctx: context.Background(), 36 expectedReadiness: http.StatusOK, 37 expectedLiveness: http.StatusOK, 38 }, { 39 name: "user provided custom readiness health check handler, liveness default handler is used", 40 ctx: AddReadiness(context.Background(), testHandler()), 41 expectedReadiness: http.StatusBadGateway, 42 expectedLiveness: http.StatusOK, 43 }, { 44 name: "user provided custom liveness health check handler, readiness default handler is used", 45 ctx: AddLiveness(context.Background(), testHandler()), 46 expectedReadiness: http.StatusOK, 47 expectedLiveness: http.StatusBadGateway, 48 }, { 49 name: "user provided custom health check handlers", 50 ctx: AddReadiness(AddLiveness(context.Background(), testHandler()), testHandler()), 51 expectedReadiness: http.StatusBadGateway, 52 expectedLiveness: http.StatusBadGateway, 53 }} 54 for _, tc := range tests { 55 t.Run(tc.name, func(t *testing.T) { 56 mux := muxWithHandles(tc.ctx) 57 reqReadiness := http.Request{ 58 URL: &url.URL{ 59 Path: "/readiness", 60 }, 61 } 62 resp := httptest.NewRecorder() 63 mux.ServeHTTP(resp, &reqReadiness) 64 if got, want := resp.Code, tc.expectedReadiness; got != want { 65 t.Errorf("Probe status = %d, wanted %d", got, want) 66 } 67 reqLiveness := http.Request{ 68 URL: &url.URL{ 69 Path: "/health", 70 }, 71 } 72 resp = httptest.NewRecorder() 73 mux.ServeHTTP(resp, &reqLiveness) 74 if got, want := resp.Code, tc.expectedLiveness; got != want { 75 t.Errorf("Probe status = %d, wanted %d", got, want) 76 } 77 }) 78 } 79 } 80 81 func testHandler() http.HandlerFunc { 82 return func(w http.ResponseWriter, req *http.Request) { 83 http.Error(w, "test", http.StatusBadGateway) 84 } 85 }