k8s.io/apiserver@v0.31.1/pkg/server/filters/wrap_test.go (about) 1 /* 2 Copyright 2024 The Kubernetes 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 filters 18 19 import ( 20 "bytes" 21 "net/http" 22 "net/http/httptest" 23 "strings" 24 "testing" 25 26 "k8s.io/apimachinery/pkg/util/sets" 27 "k8s.io/apiserver/pkg/endpoints/request" 28 "k8s.io/apiserver/pkg/server/routine" 29 "k8s.io/klog/v2" 30 ) 31 32 func TestPropogatingPanic(t *testing.T) { 33 var buf bytes.Buffer 34 klog.SetOutput(&buf) 35 klog.LogToStderr(false) 36 defer klog.LogToStderr(true) 37 38 panicMsg := "panic as designed" 39 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 40 panic(panicMsg) 41 }) 42 resolver := &request.RequestInfoFactory{ 43 APIPrefixes: sets.NewString("api", "apis"), 44 GrouplessAPIPrefixes: sets.NewString("api"), 45 } 46 ts := httptest.NewServer(routine.WithRoutine(WithPanicRecovery(handler, resolver), func(_ *http.Request, _ *request.RequestInfo) bool { return true })) 47 defer ts.Close() 48 _, err := http.Get(ts.URL) 49 if err == nil { 50 t.Error("expected to receive an error") 51 } 52 53 klog.Flush() 54 klog.SetOutput(&bytes.Buffer{}) // prevent further writes into buf 55 capturedOutput := buf.String() 56 57 if !strings.Contains(capturedOutput, panicMsg) || !strings.Contains(capturedOutput, "apiserver panic'd") { 58 t.Errorf("unexpected out captured actual = %v", capturedOutput) 59 } 60 }