k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/test/utils/ktesting/stepcontext_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 "bytes" 21 "os" 22 "testing" 23 "time" 24 25 "github.com/stretchr/testify/assert" 26 ) 27 28 func TestStepContext(t *testing.T) { 29 for name, tc := range map[string]testcase{ 30 "output": { 31 cb: func(tCtx TContext) { 32 tCtx = WithStep(tCtx, "step") 33 tCtx.Log("Log", "a", "b", 42) 34 tCtx.Logf("Logf %s %s %d", "a", "b", 42) 35 tCtx.Error("Error", "a", "b", 42) 36 tCtx.Errorf("Errorf %s %s %d", "a", "b", 42) 37 }, 38 expectLog: `<klog header>: step: Log a b 42 39 <klog header>: step: Logf a b 42 40 `, 41 expectError: `step: Error a b 42 42 step: Errorf a b 42`, 43 }, 44 "fatal": { 45 cb: func(tCtx TContext) { 46 tCtx = WithStep(tCtx, "step") 47 tCtx.Fatal("Error", "a", "b", 42) 48 // not reached 49 tCtx.Log("Log") 50 }, 51 expectError: `step: Error a b 42`, 52 }, 53 "fatalf": { 54 cb: func(tCtx TContext) { 55 tCtx = WithStep(tCtx, "step") 56 tCtx.Fatalf("Error %s %s %d", "a", "b", 42) 57 // not reached 58 tCtx.Log("Log") 59 }, 60 expectError: `step: Error a b 42`, 61 }, 62 "progress": { 63 cb: func(tCtx TContext) { 64 tCtx = WithStep(tCtx, "step") 65 var buffer bytes.Buffer 66 oldOut := defaultProgressReporter.setOutput(&buffer) 67 defer defaultProgressReporter.setOutput(oldOut) 68 remove := tCtx.Value("GINKGO_SPEC_CONTEXT").(ginkgoReporter).AttachProgressReporter(func() string { return "hello world" }) 69 defer remove() 70 defaultSignalChannel <- os.Interrupt 71 // No good way to sync here, so let's just wait. 72 time.Sleep(5 * time.Second) 73 defaultProgressReporter.setOutput(oldOut) 74 tCtx.Log(buffer.String()) 75 76 noSuchValue := tCtx.Value("some other key") 77 assert.Equal(tCtx, nil, noSuchValue, "value for unknown context value key") 78 }, 79 expectLog: `<klog header>: step: You requested a progress report. 80 81 step: hello world 82 `, 83 expectDuration: 5 * time.Second, 84 expectNoFail: true, 85 }, 86 } { 87 tc := tc 88 t.Run(name, func(t *testing.T) { 89 tc.run(t) 90 }) 91 } 92 }