forked from golang/glog
/
testinglogger_test.go
215 lines (197 loc) · 6 KB
/
testinglogger_test.go
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/*
Copyright 2019 The Kubernetes Authors.
Copyright 2020 Intel Coporation.
SPDX-License-Identifier: Apache-2.0
*/
package ktesting_test
import (
"bytes"
"errors"
"flag"
"fmt"
"regexp"
"runtime"
"sync"
"testing"
"k8s.io/klog/v2"
"k8s.io/klog/v2/ktesting"
)
func TestInfo(t *testing.T) {
tests := map[string]struct {
text string
withValues []interface{}
keysAndValues []interface{}
names []string
err error
expectedOutput string
}{
"should log with values passed to keysAndValues": {
text: "test",
keysAndValues: []interface{}{"akey", "avalue"},
expectedOutput: `INFO test akey="avalue"
`,
},
"should support single name": {
names: []string{"hello"},
text: "test",
keysAndValues: []interface{}{"akey", "avalue"},
expectedOutput: `INFO hello: test akey="avalue"
`,
},
"should support multiple names": {
names: []string{"hello", "world"},
text: "test",
keysAndValues: []interface{}{"akey", "avalue"},
expectedOutput: `INFO hello/world: test akey="avalue"
`,
},
"should not print duplicate keys with the same value": {
text: "test",
keysAndValues: []interface{}{"akey", "avalue", "akey", "avalue"},
expectedOutput: `INFO test akey="avalue" akey="avalue"
`,
},
"should only print the last duplicate key when the values are passed to Info": {
text: "test",
keysAndValues: []interface{}{"akey", "avalue", "akey", "avalue2"},
expectedOutput: `INFO test akey="avalue" akey="avalue2"
`,
},
"should only print the duplicate key that is passed to Info if one was passed to the logger": {
withValues: []interface{}{"akey", "avalue"},
text: "test",
keysAndValues: []interface{}{"akey", "avalue"},
expectedOutput: `INFO test akey="avalue"
`,
},
"should only print the key passed to Info when one is already set on the logger": {
withValues: []interface{}{"akey", "avalue"},
text: "test",
keysAndValues: []interface{}{"akey", "avalue2"},
expectedOutput: `INFO test akey="avalue2"
`,
},
"should correctly handle odd-numbers of KVs": {
text: "test",
keysAndValues: []interface{}{"akey", "avalue", "akey2"},
expectedOutput: `INFO test akey="avalue" akey2="(MISSING)"
`,
},
"should correctly html characters": {
text: "test",
keysAndValues: []interface{}{"akey", "<&>"},
expectedOutput: `INFO test akey="<&>"
`,
},
"should correctly handle odd-numbers of KVs in both log values and Info args": {
withValues: []interface{}{"basekey1", "basevar1", "basekey2"},
text: "test",
keysAndValues: []interface{}{"akey", "avalue", "akey2"},
expectedOutput: `INFO test basekey1="basevar1" basekey2="(MISSING)" akey="avalue" akey2="(MISSING)"
`,
},
"should correctly print regular error types": {
text: "test",
keysAndValues: []interface{}{"err", errors.New("whoops")},
expectedOutput: `INFO test err="whoops"
`,
},
"should correctly print regular error types when using logr.Error": {
text: "test",
err: errors.New("whoops"),
expectedOutput: `ERROR test err="whoops"
`,
},
}
for n, test := range tests {
t.Run(n, func(t *testing.T) {
var buffer logToBuf
klogr := ktesting.NewLogger(&buffer, ktesting.NewConfig())
for _, name := range test.names {
klogr = klogr.WithName(name)
}
klogr = klogr.WithValues(test.withValues...)
if test.err != nil {
klogr.Error(test.err, test.text, test.keysAndValues...)
} else {
klogr.Info(test.text, test.keysAndValues...)
}
actual := buffer.String()
if actual != test.expectedOutput {
t.Errorf("Expected:\n%sActual:\n%s\n", test.expectedOutput, actual)
}
})
}
}
func TestCallDepth(t *testing.T) {
logger := ktesting.NewLogger(t, ktesting.NewConfig())
logger.Info("hello world")
}
type logToBuf struct {
ktesting.NopTL
bytes.Buffer
}
func (l *logToBuf) Helper() {
}
func (l *logToBuf) Log(args ...interface{}) {
for i, arg := range args {
if i > 0 {
l.Write([]byte(" "))
}
l.Write([]byte(fmt.Sprintf("%s", arg)))
}
l.Write([]byte("\n"))
}
func TestStop(t *testing.T) {
// This test is set up so that a subtest spawns a goroutine and that
// goroutine logs through ktesting *after* the subtest has
// completed. This is not supported by testing.T.Log and normally
// leads to:
// panic: Log in goroutine after TestGoroutines/Sub has completed: INFO hello world
//
// It works with ktesting if (and only if) logging gets redirected to klog
// before returning from the test.
// Capture output for testing.
state := klog.CaptureState()
defer state.Restore()
var output bytes.Buffer
var fs flag.FlagSet
klog.InitFlags(&fs)
fs.Set("alsologtostderr", "false")
fs.Set("logtostderr", "false")
fs.Set("stderrthreshold", "FATAL")
fs.Set("one_output", "true")
klog.SetOutput(&output)
var line int
var wg1, wg2 sync.WaitGroup
wg1.Add(1)
wg2.Add(1)
t.Run("Sub", func(t *testing.T) {
logger, _ := ktesting.NewTestContext(t)
go func() {
defer wg2.Done()
// Wait for test to have returned.
wg1.Wait()
// This output must go to klog because the test has
// completed.
_, _, line, _ = runtime.Caller(0)
logger.Info("simple info message")
logger.Error(nil, "error message")
logger.WithName("me").WithValues("completed", true).Info("complex info message", "anotherValue", 1)
}()
})
// Allow goroutine above to proceed.
wg1.Done()
// Ensure that goroutine has completed.
wg2.Wait()
actual := output.String()
actual = regexp.MustCompile(`(?m)^.* testinglogger_test.go:`).ReplaceAllString(actual, `testinglogger_test.go:`)
expected := fmt.Sprintf(`testinglogger_test.go:%d] "TestStop/Sub leaked goroutine: simple info message"
testinglogger_test.go:%d] "TestStop/Sub leaked goroutine: error message"
testinglogger_test.go:%d] "TestStop/Sub leaked goroutine/me: complex info message" completed=true anotherValue=1
`,
line+1, line+2, line+3)
if actual != expected {
t.Errorf("Output does not match. Expected:\n%s\nActual:\n%s\n", expected, actual)
}
}