...

Source file src/k8s.io/klog/v2/ktesting/contextual_test.go

Documentation: k8s.io/klog/v2/ktesting

     1  /*
     2  Copyright 2019 The Kubernetes Authors.
     3  Copyright 2020 Intel Corporation.
     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  	var buffer ktesting.BufferTL
    20  	logger, ctx := ktesting.NewTestContext(&buffer)
    21  
    22  	doSomething(ctx)
    23  
    24  	// When contextual logging is disabled, the output goes to klog
    25  	// instead of the testing logger.
    26  	state := klog.CaptureState()
    27  	defer state.Restore()
    28  	klog.EnableContextualLogging(false)
    29  	doSomething(ctx)
    30  
    31  	testingLogger, ok := logger.GetSink().(ktesting.Underlier)
    32  	if !ok {
    33  		t.Fatal("Should have had a ktesting LogSink!?")
    34  	}
    35  
    36  	actual := testingLogger.GetBuffer().String()
    37  	if actual != "" {
    38  		t.Errorf("testinglogger should not have buffered, got:\n%s", actual)
    39  	}
    40  
    41  	actual = buffer.String()
    42  	actual = headerRe.ReplaceAllString(actual, "${1}xxx] ")
    43  	expected := `Ixxx] hello world
    44  Ixxx] foo: hello also from me
    45  `
    46  	if actual != expected {
    47  		t.Errorf("mismatch in captured output, expected:\n%s\ngot:\n%s\n", expected, actual)
    48  	}
    49  }
    50  
    51  func doSomething(ctx context.Context) {
    52  	logger := klog.FromContext(ctx)
    53  	logger.Info("hello world")
    54  
    55  	logger = logger.WithName("foo")
    56  	ctx = klog.NewContext(ctx, logger)
    57  	doSomeMore(ctx)
    58  }
    59  
    60  func doSomeMore(ctx context.Context) {
    61  	logger := klog.FromContext(ctx)
    62  	logger.Info("hello also from me")
    63  }
    64  

View as plain text