|
| 1 | +/* |
| 2 | +Copyright 2019 The Kubernetes Authors. |
| 3 | +Copyright 2020 Intel Coporation. |
| 4 | +
|
| 5 | +SPDX-License-Identifier: Apache-2.0 |
| 6 | +*/ |
| 7 | + |
| 8 | +package ktesting_test |
| 9 | + |
| 10 | +import ( |
| 11 | + "context" |
| 12 | + "testing" |
| 13 | + |
| 14 | + "k8s.io/klog/v2" |
| 15 | + "k8s.io/klog/v2/ktesting" |
| 16 | +) |
| 17 | + |
| 18 | +func TestContextual(t *testing.T) { |
| 19 | + logger, ctx := ktesting.NewTestContext(t) |
| 20 | + |
| 21 | + doSomething(ctx) |
| 22 | + |
| 23 | + // When contextual logging is disabled, the output goes to klog |
| 24 | + // instead of the testing logger. |
| 25 | + state := klog.CaptureState() |
| 26 | + defer state.Restore() |
| 27 | + klog.EnableContextualLogging(false) |
| 28 | + doSomething(ctx) |
| 29 | + |
| 30 | + testingLogger, ok := logger.GetSink().(ktesting.Underlier) |
| 31 | + if !ok { |
| 32 | + t.Fatal("Should have had a ktesting LogSink!?") |
| 33 | + } |
| 34 | + |
| 35 | + actual := testingLogger.GetBuffer().String() |
| 36 | + expected := `INFO hello world |
| 37 | +INFO foo: hello also from me |
| 38 | +` |
| 39 | + if actual != expected { |
| 40 | + t.Errorf("mismatch in captured output, expected:\n%s\ngot:\n%s\n", expected, actual) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +func doSomething(ctx context.Context) { |
| 45 | + logger := klog.FromContext(ctx) |
| 46 | + logger.Info("hello world") |
| 47 | + |
| 48 | + logger = logger.WithName("foo") |
| 49 | + ctx = klog.NewContext(ctx, logger) |
| 50 | + doSomeMore(ctx) |
| 51 | +} |
| 52 | + |
| 53 | +func doSomeMore(ctx context.Context) { |
| 54 | + logger := klog.FromContext(ctx) |
| 55 | + logger.Info("hello also from me") |
| 56 | +} |
0 commit comments