File: contextual_test.go

package info (click to toggle)
golang-k8s-klog 2.130.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 812 kB
  • sloc: sh: 86; makefile: 7
file content (63 lines) | stat: -rw-r--r-- 1,393 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
Copyright 2019 The Kubernetes Authors.
Copyright 2020 Intel Corporation.

SPDX-License-Identifier: Apache-2.0
*/

package ktesting_test

import (
	"context"
	"testing"

	"k8s.io/klog/v2"
	"k8s.io/klog/v2/ktesting"
)

func TestContextual(t *testing.T) {
	var buffer ktesting.BufferTL
	logger, ctx := ktesting.NewTestContext(&buffer)

	doSomething(ctx)

	// When contextual logging is disabled, the output goes to klog
	// instead of the testing logger.
	state := klog.CaptureState()
	defer state.Restore()
	klog.EnableContextualLogging(false)
	doSomething(ctx)

	testingLogger, ok := logger.GetSink().(ktesting.Underlier)
	if !ok {
		t.Fatal("Should have had a ktesting LogSink!?")
	}

	actual := testingLogger.GetBuffer().String()
	if actual != "" {
		t.Errorf("testinglogger should not have buffered, got:\n%s", actual)
	}

	actual = buffer.String()
	actual = headerRe.ReplaceAllString(actual, "${1}xxx] ")
	expected := `Ixxx] hello world
Ixxx] foo: hello also from me
`
	if actual != expected {
		t.Errorf("mismatch in captured output, expected:\n%s\ngot:\n%s\n", expected, actual)
	}
}

func doSomething(ctx context.Context) {
	logger := klog.FromContext(ctx)
	logger.Info("hello world")

	logger = logger.WithName("foo")
	ctx = klog.NewContext(ctx, logger)
	doSomeMore(ctx)
}

func doSomeMore(ctx context.Context) {
	logger := klog.FromContext(ctx)
	logger.Info("hello also from me")
}