k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/test/utils/ktesting/helper_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 ktesting 18 19 import ( 20 "fmt" 21 "regexp" 22 "strings" 23 "testing" 24 "time" 25 26 "github.com/stretchr/testify/assert" 27 ) 28 29 // testcase wraps a callback which is called with a TContext that intercepts 30 // errors and log output. Those get compared. 31 type testcase struct { 32 cb func(TContext) 33 expectNoFail bool 34 expectError string 35 expectDuration time.Duration 36 expectLog string 37 } 38 39 func (tc testcase) run(t *testing.T) { 40 bufferT := &logBufferT{T: t} 41 tCtx := Init(bufferT) 42 var err error 43 tCtx, finalize := WithError(tCtx, &err) 44 start := time.Now() 45 func() { 46 defer finalize() 47 tc.cb(tCtx) 48 }() 49 50 log := bufferT.log.String() 51 t.Logf("Log output:\n%s\n", log) 52 if tc.expectLog != "" { 53 assert.Equal(t, tc.expectLog, normalize(log)) 54 } else if log != "" { 55 t.Error("Expected no log output.") 56 } 57 58 duration := time.Since(start) 59 assert.InDelta(t, tc.expectDuration.Seconds(), duration.Seconds(), 0.1, fmt.Sprintf("callback invocation duration %s", duration)) 60 assert.Equal(t, !tc.expectNoFail, tCtx.Failed(), "Failed()") 61 if tc.expectError == "" { 62 assert.NoError(t, err) 63 } else if assert.NotNil(t, err) { 64 t.Logf("Result:\n%s", err.Error()) 65 assert.Equal(t, tc.expectError, normalize(err.Error())) 66 } 67 } 68 69 // normalize replaces parts of message texts which may vary with constant strings. 70 func normalize(msg string) string { 71 // duration 72 msg = regexp.MustCompile(`[[:digit:]]+\.[[:digit:]]+s`).ReplaceAllString(msg, "x.y s") 73 // hex pointer value 74 msg = regexp.MustCompile(`0x[[:xdigit:]]+`).ReplaceAllString(msg, "0xXXXX") 75 // per-test klog header 76 msg = regexp.MustCompile(`[EI][[:digit:]]{4} [[:digit:]]{2}:[[:digit:]]{2}:[[:digit:]]{2}\.[[:digit:]]{6}\]`).ReplaceAllString(msg, "<klog header>:") 77 return msg 78 } 79 80 type logBufferT struct { 81 *testing.T 82 log strings.Builder 83 } 84 85 func (l *logBufferT) Log(args ...any) { 86 l.log.WriteString(fmt.Sprintln(args...)) 87 } 88 89 func (l *logBufferT) Logf(format string, args ...any) { 90 l.log.WriteString(fmt.Sprintf(format, args...)) 91 l.log.WriteRune('\n') 92 }