forked from uber-go/zap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sugar_test.go
467 lines (430 loc) · 16 KB
/
sugar_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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package zap
import (
"testing"
"go.uber.org/zap/internal/exit"
"go.uber.org/zap/internal/ztest"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSugarWith(t *testing.T) {
// Convenience functions to create expected error logs.
ignored := func(msg interface{}) observer.LoggedEntry {
return observer.LoggedEntry{
Entry: zapcore.Entry{Level: ErrorLevel, Message: _oddNumberErrMsg},
Context: []Field{Any("ignored", msg)},
}
}
nonString := func(pairs ...invalidPair) observer.LoggedEntry {
return observer.LoggedEntry{
Entry: zapcore.Entry{Level: ErrorLevel, Message: _nonStringKeyErrMsg},
Context: []Field{Array("invalid", invalidPairs(pairs))},
}
}
tests := []struct {
desc string
args []interface{}
expected []Field
errLogs []observer.LoggedEntry
}{
{
desc: "nil args",
args: nil,
expected: []Field{},
errLogs: nil,
},
{
desc: "empty slice of args",
args: []interface{}{},
expected: []Field{},
errLogs: nil,
},
{
desc: "just a dangling key",
args: []interface{}{"should ignore"},
expected: []Field{},
errLogs: []observer.LoggedEntry{ignored("should ignore")},
},
{
desc: "well-formed key-value pairs",
args: []interface{}{"foo", 42, "true", "bar"},
expected: []Field{Int("foo", 42), String("true", "bar")},
errLogs: nil,
},
{
desc: "just a structured field",
args: []interface{}{Int("foo", 42)},
expected: []Field{Int("foo", 42)},
errLogs: nil,
},
{
desc: "structured field and a dangling key",
args: []interface{}{Int("foo", 42), "dangling"},
expected: []Field{Int("foo", 42)},
errLogs: []observer.LoggedEntry{ignored("dangling")},
},
{
desc: "structured field and a dangling non-string key",
args: []interface{}{Int("foo", 42), 13},
expected: []Field{Int("foo", 42)},
errLogs: []observer.LoggedEntry{ignored(13)},
},
{
desc: "key-value pair and a dangling key",
args: []interface{}{"foo", 42, "dangling"},
expected: []Field{Int("foo", 42)},
errLogs: []observer.LoggedEntry{ignored("dangling")},
},
{
desc: "pairs, a structured field, and a dangling key",
args: []interface{}{"first", "field", Int("foo", 42), "baz", "quux", "dangling"},
expected: []Field{String("first", "field"), Int("foo", 42), String("baz", "quux")},
errLogs: []observer.LoggedEntry{ignored("dangling")},
},
{
desc: "one non-string key",
args: []interface{}{"foo", 42, true, "bar"},
expected: []Field{Int("foo", 42)},
errLogs: []observer.LoggedEntry{nonString(invalidPair{2, true, "bar"})},
},
{
desc: "pairs, structured fields, non-string keys, and a dangling key",
args: []interface{}{"foo", 42, true, "bar", Int("structure", 11), 42, "reversed", "baz", "quux", "dangling"},
expected: []Field{Int("foo", 42), Int("structure", 11), String("baz", "quux")},
errLogs: []observer.LoggedEntry{
ignored("dangling"),
nonString(invalidPair{2, true, "bar"}, invalidPair{5, 42, "reversed"}),
},
},
}
for _, tt := range tests {
withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
logger.With(tt.args...).Info("")
output := logs.AllUntimed()
if len(tt.errLogs) > 0 {
for i := range tt.errLogs {
assert.Equal(t, tt.errLogs[i], output[i], "Unexpected error log at position %d for scenario %s.", i, tt.desc)
}
}
assert.Equal(t, len(tt.errLogs)+1, len(output), "Expected only one non-error message to be logged in scenario %s.", tt.desc)
assert.Equal(t, tt.expected, output[len(tt.errLogs)].Context, "Unexpected message context in scenario %s.", tt.desc)
})
}
}
func TestSugarFieldsInvalidPairs(t *testing.T) {
withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
logger.With(42, "foo", []string{"bar"}, "baz").Info("")
output := logs.AllUntimed()
// Double-check that the actual message was logged.
require.Equal(t, 2, len(output), "Unexpected number of entries logged.")
require.Equal(t, observer.LoggedEntry{Context: []Field{}}, output[1], "Unexpected non-error log entry.")
// Assert that the error message's structured fields serialize properly.
require.Equal(t, 1, len(output[0].Context), "Expected one field in error entry context.")
enc := zapcore.NewMapObjectEncoder()
output[0].Context[0].AddTo(enc)
assert.Equal(t, []interface{}{
map[string]interface{}{"position": int64(0), "key": int64(42), "value": "foo"},
map[string]interface{}{"position": int64(2), "key": []interface{}{"bar"}, "value": "baz"},
}, enc.Fields["invalid"], "Unexpected output when logging invalid key-value pairs.")
})
}
func TestSugarStructuredLogging(t *testing.T) {
tests := []struct {
msg string
expectMsg string
}{
{"foo", "foo"},
{"", ""},
}
// Common to all test cases.
context := []interface{}{"foo", "bar"}
extra := []interface{}{"baz", false}
expectedFields := []Field{String("foo", "bar"), Bool("baz", false)}
for _, tt := range tests {
withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
logger.With(context...).Debugw(tt.msg, extra...)
logger.With(context...).Infow(tt.msg, extra...)
logger.With(context...).Warnw(tt.msg, extra...)
logger.With(context...).Errorw(tt.msg, extra...)
logger.With(context...).DPanicw(tt.msg, extra...)
expected := make([]observer.LoggedEntry, 5)
for i, lvl := range []zapcore.Level{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, DPanicLevel} {
expected[i] = observer.LoggedEntry{
Entry: zapcore.Entry{Message: tt.expectMsg, Level: lvl},
Context: expectedFields,
}
}
assert.Equal(t, expected, logs.AllUntimed(), "Unexpected log output.")
})
}
}
func TestSugarConcatenatingLogging(t *testing.T) {
tests := []struct {
args []interface{}
expect string
}{
{[]interface{}{nil}, "<nil>"},
}
// Common to all test cases.
context := []interface{}{"foo", "bar"}
expectedFields := []Field{String("foo", "bar")}
for _, tt := range tests {
withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
logger.With(context...).Debug(tt.args...)
logger.With(context...).Info(tt.args...)
logger.With(context...).Warn(tt.args...)
logger.With(context...).Error(tt.args...)
logger.With(context...).DPanic(tt.args...)
expected := make([]observer.LoggedEntry, 5)
for i, lvl := range []zapcore.Level{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, DPanicLevel} {
expected[i] = observer.LoggedEntry{
Entry: zapcore.Entry{Message: tt.expect, Level: lvl},
Context: expectedFields,
}
}
assert.Equal(t, expected, logs.AllUntimed(), "Unexpected log output.")
})
}
}
func TestSugarTemplatedLogging(t *testing.T) {
tests := []struct {
format string
args []interface{}
expect string
}{
{"", nil, ""},
{"foo", nil, "foo"},
// If the user fails to pass a template, degrade to fmt.Sprint.
{"", []interface{}{"foo"}, "foo"},
}
// Common to all test cases.
context := []interface{}{"foo", "bar"}
expectedFields := []Field{String("foo", "bar")}
for _, tt := range tests {
withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
logger.With(context...).Debugf(tt.format, tt.args...)
logger.With(context...).Infof(tt.format, tt.args...)
logger.With(context...).Warnf(tt.format, tt.args...)
logger.With(context...).Errorf(tt.format, tt.args...)
logger.With(context...).DPanicf(tt.format, tt.args...)
expected := make([]observer.LoggedEntry, 5)
for i, lvl := range []zapcore.Level{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, DPanicLevel} {
expected[i] = observer.LoggedEntry{
Entry: zapcore.Entry{Message: tt.expect, Level: lvl},
Context: expectedFields,
}
}
assert.Equal(t, expected, logs.AllUntimed(), "Unexpected log output.")
})
}
}
func TestSugarLnLogging(t *testing.T) {
tests := []struct {
args []interface{}
expect string
}{
{nil, ""},
{[]interface{}{}, ""},
{[]interface{}{""}, ""},
{[]interface{}{"foo"}, "foo"},
{[]interface{}{"foo", "bar"}, "foo bar"},
}
// Common to all test cases.
context := []interface{}{"foo", "bar"}
expectedFields := []Field{String("foo", "bar")}
for _, tt := range tests {
withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
logger.With(context...).Debugln(tt.args...)
logger.With(context...).Infoln(tt.args...)
logger.With(context...).Warnln(tt.args...)
logger.With(context...).Errorln(tt.args...)
logger.With(context...).DPanicln(tt.args...)
expected := make([]observer.LoggedEntry, 5)
for i, lvl := range []zapcore.Level{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, DPanicLevel} {
expected[i] = observer.LoggedEntry{
Entry: zapcore.Entry{Message: tt.expect, Level: lvl},
Context: expectedFields,
}
}
assert.Equal(t, expected, logs.AllUntimed(), "Unexpected log output.")
})
}
}
func TestSugarLnLoggingIgnored(t *testing.T) {
withSugar(t, WarnLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
logger.Infoln("hello")
assert.Zero(t, logs.Len(), "Expected zero log statements.")
})
}
func TestSugarPanicLogging(t *testing.T) {
tests := []struct {
loggerLevel zapcore.Level
f func(*SugaredLogger)
expectedMsg string
}{
{FatalLevel, func(s *SugaredLogger) { s.Panic("foo") }, ""},
{PanicLevel, func(s *SugaredLogger) { s.Panic("foo") }, "foo"},
{DebugLevel, func(s *SugaredLogger) { s.Panic("foo") }, "foo"},
{FatalLevel, func(s *SugaredLogger) { s.Panicf("%s", "foo") }, ""},
{PanicLevel, func(s *SugaredLogger) { s.Panicf("%s", "foo") }, "foo"},
{DebugLevel, func(s *SugaredLogger) { s.Panicf("%s", "foo") }, "foo"},
{FatalLevel, func(s *SugaredLogger) { s.Panicw("foo") }, ""},
{PanicLevel, func(s *SugaredLogger) { s.Panicw("foo") }, "foo"},
{DebugLevel, func(s *SugaredLogger) { s.Panicw("foo") }, "foo"},
{FatalLevel, func(s *SugaredLogger) { s.Panicln("foo") }, ""},
{PanicLevel, func(s *SugaredLogger) { s.Panicln("foo") }, "foo"},
{DebugLevel, func(s *SugaredLogger) { s.Panicln("foo") }, "foo"},
}
for _, tt := range tests {
withSugar(t, tt.loggerLevel, nil, func(sugar *SugaredLogger, logs *observer.ObservedLogs) {
assert.Panics(t, func() { tt.f(sugar) }, "Expected panic-level logger calls to panic.")
if tt.expectedMsg != "" {
assert.Equal(t, []observer.LoggedEntry{{
Context: []Field{},
Entry: zapcore.Entry{Message: tt.expectedMsg, Level: PanicLevel},
}}, logs.AllUntimed(), "Unexpected log output.")
} else {
assert.Equal(t, 0, logs.Len(), "Didn't expect any log output.")
}
})
}
}
func TestSugarFatalLogging(t *testing.T) {
tests := []struct {
loggerLevel zapcore.Level
f func(*SugaredLogger)
expectedMsg string
}{
{FatalLevel + 1, func(s *SugaredLogger) { s.Fatal("foo") }, ""},
{FatalLevel, func(s *SugaredLogger) { s.Fatal("foo") }, "foo"},
{DebugLevel, func(s *SugaredLogger) { s.Fatal("foo") }, "foo"},
{FatalLevel + 1, func(s *SugaredLogger) { s.Fatalf("%s", "foo") }, ""},
{FatalLevel, func(s *SugaredLogger) { s.Fatalf("%s", "foo") }, "foo"},
{DebugLevel, func(s *SugaredLogger) { s.Fatalf("%s", "foo") }, "foo"},
{FatalLevel + 1, func(s *SugaredLogger) { s.Fatalw("foo") }, ""},
{FatalLevel, func(s *SugaredLogger) { s.Fatalw("foo") }, "foo"},
{DebugLevel, func(s *SugaredLogger) { s.Fatalw("foo") }, "foo"},
{FatalLevel + 1, func(s *SugaredLogger) { s.Fatalln("foo") }, ""},
{FatalLevel, func(s *SugaredLogger) { s.Fatalln("foo") }, "foo"},
{DebugLevel, func(s *SugaredLogger) { s.Fatalln("foo") }, "foo"},
}
for _, tt := range tests {
withSugar(t, tt.loggerLevel, nil, func(sugar *SugaredLogger, logs *observer.ObservedLogs) {
stub := exit.WithStub(func() { tt.f(sugar) })
assert.True(t, stub.Exited, "Expected all calls to fatal logger methods to exit process.")
if tt.expectedMsg != "" {
assert.Equal(t, []observer.LoggedEntry{{
Context: []Field{},
Entry: zapcore.Entry{Message: tt.expectedMsg, Level: FatalLevel},
}}, logs.AllUntimed(), "Unexpected log output.")
} else {
assert.Equal(t, 0, logs.Len(), "Didn't expect any log output.")
}
})
}
}
func TestSugarAddCaller(t *testing.T) {
tests := []struct {
options []Option
pat string
}{
{opts(AddCaller()), `.+/sugar_test.go:[\d]+$`},
{opts(AddCaller(), AddCallerSkip(1), AddCallerSkip(-1)), `.+/sugar_test.go:[\d]+$`},
{opts(AddCaller(), AddCallerSkip(1)), `.+/common_test.go:[\d]+$`},
{opts(AddCaller(), AddCallerSkip(1), AddCallerSkip(5)), `.+/src/runtime/.*:[\d]+$`},
}
for _, tt := range tests {
withSugar(t, DebugLevel, tt.options, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
logger.Info("")
output := logs.AllUntimed()
assert.Equal(t, 1, len(output), "Unexpected number of logs written out.")
assert.Regexp(
t,
tt.pat,
output[0].Caller,
"Expected to find package name and file name in output.",
)
})
}
}
func TestSugarAddCallerFail(t *testing.T) {
errBuf := &ztest.Buffer{}
withSugar(t, DebugLevel, opts(AddCaller(), AddCallerSkip(1e3), ErrorOutput(errBuf)), func(log *SugaredLogger, logs *observer.ObservedLogs) {
log.Info("Failure.")
assert.Regexp(
t,
`Logger.check error: failed to get caller`,
errBuf.String(),
"Didn't find expected failure message.",
)
assert.Equal(
t,
logs.AllUntimed()[0].Message,
"Failure.",
"Expected original message to survive failures in runtime.Caller.")
})
}
func TestSugarWithOptionsIncreaseLevel(t *testing.T) {
withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
logger = logger.WithOptions(IncreaseLevel(WarnLevel))
logger.Info("logger.Info")
logger.Warn("logger.Warn")
logger.Error("logger.Error")
require.Equal(t, 2, logs.Len(), "expected only warn + error logs due to IncreaseLevel.")
assert.Equal(
t,
logs.AllUntimed()[0].Message,
"logger.Warn",
"Expected first logged message to be warn level message",
)
})
}
func TestSugarLnWithOptionsIncreaseLevel(t *testing.T) {
withSugar(t, DebugLevel, nil, func(logger *SugaredLogger, logs *observer.ObservedLogs) {
logger = logger.WithOptions(IncreaseLevel(WarnLevel))
logger.Infoln("logger.Infoln")
logger.Warnln("logger.Warnln")
logger.Errorln("logger.Errorln")
require.Equal(t, 2, logs.Len(), "expected only warn + error logs due to IncreaseLevel.")
assert.Equal(
t,
logs.AllUntimed()[0].Message,
"logger.Warnln",
"Expected first logged message to be warn level message",
)
})
}
func BenchmarkSugarSingleStrArg(b *testing.B) {
withSugar(b, InfoLevel, nil /* opts* */, func(log *SugaredLogger, logs *observer.ObservedLogs) {
for i := 0; i < b.N; i++ {
log.Info("hello world")
}
})
}
func BenchmarkLnSugarSingleStrArg(b *testing.B) {
withSugar(b, InfoLevel, nil /* opts* */, func(log *SugaredLogger, logs *observer.ObservedLogs) {
for i := 0; i < b.N; i++ {
log.Infoln("hello world")
}
})
}