-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage_test.go
More file actions
432 lines (387 loc) · 13.1 KB
/
Copy pathcoverage_test.go
File metadata and controls
432 lines (387 loc) · 13.1 KB
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
package loglayer_test
// Tests filling coverage gaps in critical paths: every LogBuilder terminal
// level method, level parsing/stringification, and edge cases for prefix +
// unknown levels.
import (
"context"
"errors"
"testing"
"go.loglayer.dev/v2"
)
func TestBuild_NoTransport(t *testing.T) {
_, err := loglayer.Build(loglayer.Config{})
if !errors.Is(err, loglayer.ErrNoTransport) {
t.Errorf("got %v, want ErrNoTransport", err)
}
}
func TestBuild_WithTransport(t *testing.T) {
log, err := loglayer.Build(loglayer.Config{Transport: discardTransport{}})
if err != nil || log == nil {
t.Errorf("Build with transport: err=%v log=%v", err, log)
}
}
func TestNew_PanicsWithoutTransport(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("expected panic with no transport")
}
}()
loglayer.New(loglayer.Config{})
}
func TestBuild_TransportAndTransports_Errors(t *testing.T) {
_, err := loglayer.Build(loglayer.Config{
Transport: discardTransport{},
Transports: []loglayer.Transport{discardTransport{}},
})
if !errors.Is(err, loglayer.ErrTransportAndTransports) {
t.Errorf("got %v, want ErrTransportAndTransports", err)
}
}
func TestNew_TransportAndTransports_Panics(t *testing.T) {
defer func() {
r := recover()
if r == nil {
t.Fatal("expected panic when both Transport and Transports are set")
}
err, ok := r.(error)
if !ok || !errors.Is(err, loglayer.ErrTransportAndTransports) {
t.Errorf("panic value: got %v, want ErrTransportAndTransports", r)
}
}()
loglayer.New(loglayer.Config{
Transport: discardTransport{},
Transports: []loglayer.Transport{discardTransport{}},
})
}
type discardTransport struct{}
func (discardTransport) ID() string { return "discard" }
func (discardTransport) IsEnabled() bool { return true }
func (discardTransport) SendToLogger(_ loglayer.TransportParams) {}
func (discardTransport) GetLoggerInstance() any { return nil }
func TestWithContext_PassesThroughToTransport(t *testing.T) {
log, lib := setup(t)
type ctxKey struct{}
ctx := context.WithValue(context.Background(), ctxKey{}, "trace-abc")
log.WithContext(ctx).Info("with ctx")
line := lib.PopLine()
if line == nil || line.Ctx == nil {
t.Fatal("expected Ctx to be set on captured line")
}
if got := line.Ctx.Value(ctxKey{}); got != "trace-abc" {
t.Errorf("ctx value not preserved: got %v", got)
}
}
func TestWithContext_BuilderChain(t *testing.T) {
log, lib := setup(t)
ctx := context.Background()
log.WithContext(ctx).
WithMetadata(loglayer.Metadata{"k": "v"}).
WithError(errors.New("boom")).
Error("chained")
line := lib.PopLine()
if line == nil {
t.Fatal("expected line")
}
if line.Ctx != ctx {
t.Errorf("Ctx mismatch: got %v", line.Ctx)
}
if line.Data["err"] == nil {
t.Errorf("err missing: %v", line.Data)
}
if m, _ := line.Metadata.(loglayer.Metadata); m["k"] != "v" {
t.Errorf("metadata missing: %v", line.Metadata)
}
}
func TestWithContext_Raw(t *testing.T) {
log, lib := setup(t)
ctx := context.Background()
log.Raw(loglayer.RawLogEntry{
LogLevel: loglayer.LogLevelInfo,
Messages: []any{"raw with ctx"},
Ctx: ctx,
})
line := lib.PopLine()
if line == nil || line.Ctx != ctx {
t.Errorf("Raw should propagate Ctx: got %v", line)
}
}
// Raw with no messages still emits a line with the configured level and
// metadata. Edge case: empty Messages slice should not panic and should
// not be silently dropped.
func TestRaw_EmptyMessages(t *testing.T) {
log, lib := setup(t)
log.Raw(loglayer.RawLogEntry{
LogLevel: loglayer.LogLevelWarn,
Messages: []any{},
Metadata: map[string]any{"k": "v"},
})
line := lib.PopLine()
if line == nil {
t.Fatal("Raw with empty messages should still emit")
}
if line.Level != loglayer.LogLevelWarn {
t.Errorf("level: got %s, want warn", line.Level)
}
if len(line.Messages) != 0 {
t.Errorf("expected empty messages, got %v", line.Messages)
}
if m, _ := line.Metadata.(map[string]any); m["k"] != "v" {
t.Errorf("metadata should still flow: %v", line.Metadata)
}
}
func TestWithoutCtx_NilOnTransport(t *testing.T) {
log, lib := setup(t)
log.Info("no ctx attached")
line := lib.PopLine()
if line == nil {
t.Fatal("expected line")
}
if line.Ctx != nil {
t.Errorf("Ctx should be nil when not attached: got %v", line.Ctx)
}
}
// (*LogLayer).WithContext binds a context to all subsequent emissions from
// the returned logger. Tests the persistent-ctx semantics added to
// distinguish from per-call (*LogBuilder).WithContext.
func TestWithContext_BindsToLogger(t *testing.T) {
log, lib := setup(t)
type ctxKey struct{}
ctx := context.WithValue(context.Background(), ctxKey{}, "trace-xyz")
bound := log.WithContext(ctx)
bound.Info("first")
bound.Warn("second")
bound.WithMetadata(loglayer.Metadata{"k": "v"}).Info("third")
for i, want := range []string{"first", "second", "third"} {
line := lib.PopLine()
if line == nil {
t.Fatalf("line %d (%q): missing", i, want)
}
if line.Ctx == nil {
t.Fatalf("line %d (%q): bound ctx not propagated", i, want)
}
if got := line.Ctx.Value(ctxKey{}); got != "trace-xyz" {
t.Errorf("line %d (%q): ctx value: got %v", i, want, got)
}
}
}
// Per-call (*LogBuilder).WithContext still overrides the bound ctx for that
// emission only. The bound ctx applies again for subsequent emissions.
func TestWithContext_PerCallOverridesBound(t *testing.T) {
log, lib := setup(t)
type ctxKey struct{}
bound := context.WithValue(context.Background(), ctxKey{}, "BOUND")
override := context.WithValue(context.Background(), ctxKey{}, "OVERRIDE")
logger := log.WithContext(bound)
logger.Info("uses bound")
logger.WithContext(override).Info("uses override")
logger.Info("back to bound")
want := []string{"BOUND", "OVERRIDE", "BOUND"}
for i, expect := range want {
line := lib.PopLine()
got, _ := line.Ctx.Value(ctxKey{}).(string)
if got != expect {
t.Errorf("line %d: got ctx value %q, want %q", i, got, expect)
}
}
}
// WithContext returns a derived logger; the receiver's behavior is unchanged.
func TestWithContext_ReceiverUnchanged(t *testing.T) {
log, lib := setup(t)
ctx := context.Background()
_ = log.WithContext(ctx)
log.Info("from base logger") // should not have any ctx attached
line := lib.PopLine()
if line.Ctx != nil {
t.Errorf("base logger should not have ctx after WithContext call: got %v", line.Ctx)
}
}
// Child() inherits the parent's bound ctx; later mutations on either
// side don't bleed.
func TestWithContext_ChildInheritsAndIsolates(t *testing.T) {
log, lib := setup(t)
type ctxKey struct{}
ctx := context.WithValue(context.Background(), ctxKey{}, "parent")
parent := log.WithContext(ctx)
child := parent.Child()
child.Info("inherits parent's bound ctx")
if got := lib.PopLine().Ctx.Value(ctxKey{}); got != "parent" {
t.Errorf("child should inherit parent's bound ctx: got %v", got)
}
other := context.WithValue(context.Background(), ctxKey{}, "rebound")
rebound := child.WithContext(other)
rebound.Info("child rebinds")
if got := lib.PopLine().Ctx.Value(ctxKey{}); got != "rebound" {
t.Errorf("child rebind: got %v", got)
}
parent.Info("parent unaffected by child rebind")
if got := lib.PopLine().Ctx.Value(ctxKey{}); got != "parent" {
t.Errorf("parent's bound ctx should be unchanged: got %v", got)
}
}
// Passing nil to WithContext clears any bound ctx (returns a logger with
// no ctx bound).
func TestWithContext_NilClears(t *testing.T) {
log, lib := setup(t)
bound := log.WithContext(context.Background())
var nilCtx context.Context // typed nil; tests the clears-binding path
cleared := bound.WithContext(nilCtx)
cleared.Info("no ctx")
line := lib.PopLine()
if line.Ctx != nil {
t.Errorf("WithContext(nil) should clear bound ctx: got %v", line.Ctx)
}
}
func TestLogBuilder_AllTerminals(t *testing.T) {
cases := []struct {
name string
fn func(*loglayer.LogLayer)
level loglayer.LogLevel
}{
{"Debug", func(l *loglayer.LogLayer) { l.WithMetadata(loglayer.Metadata{"k": "v"}).Debug("msg") }, loglayer.LogLevelDebug},
{"Info", func(l *loglayer.LogLayer) { l.WithMetadata(loglayer.Metadata{"k": "v"}).Info("msg") }, loglayer.LogLevelInfo},
{"Warn", func(l *loglayer.LogLayer) { l.WithMetadata(loglayer.Metadata{"k": "v"}).Warn("msg") }, loglayer.LogLevelWarn},
{"Error", func(l *loglayer.LogLayer) { l.WithMetadata(loglayer.Metadata{"k": "v"}).Error("msg") }, loglayer.LogLevelError},
{"Fatal", func(l *loglayer.LogLayer) { l.WithMetadata(loglayer.Metadata{"k": "v"}).Fatal("msg") }, loglayer.LogLevelFatal},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
log, lib := setup(t)
c.fn(log)
line := lib.PopLine()
if line == nil {
t.Fatalf("%s: expected line", c.name)
}
if line.Level != c.level {
t.Errorf("%s: level got %s, want %s", c.name, line.Level, c.level)
}
m, ok := line.Metadata.(loglayer.Metadata)
if !ok || m["k"] != "v" {
t.Errorf("%s: metadata not preserved through builder: %+v", c.name, line.Metadata)
}
})
}
}
func TestLogBuilder_LevelFiltered_NoEntry(t *testing.T) {
log, lib := setup(t)
log.SetLevel(loglayer.LogLevelError)
log.WithMetadata(loglayer.Metadata{"x": 1}).Info("dropped")
log.WithError(errors.New("e")).Warn("dropped")
if lib.Len() != 0 {
t.Errorf("expected no captured lines (level filtered), got %d", lib.Len())
}
}
// TestFAndMAliases pins that loglayer.F is interchangeable with
// loglayer.Fields and loglayer.M with loglayer.Metadata. The aliases
// exist for shorter call sites; they MUST stay aliases (not distinct
// types) so existing code that passes loglayer.Fields keeps working.
func TestFAndMAliases(t *testing.T) {
log, lib := setup(t)
log = log.WithFields(loglayer.F{"requestId": "abc"})
log.WithMetadata(loglayer.M{"duration": 150}).Info("done")
line := lib.PopLine()
if line == nil {
t.Fatal("expected a captured line")
}
if got, _ := line.Data["requestId"].(string); got != "abc" {
t.Errorf("F should land in Fields path: got %v", line.Data)
}
m, _ := line.Metadata.(loglayer.Metadata)
if m["duration"] != 150 {
t.Errorf("M should land in Metadata path: got %v", line.Metadata)
}
}
func TestLogLevel_String(t *testing.T) {
cases := map[loglayer.LogLevel]string{
loglayer.LogLevelDebug: "debug",
loglayer.LogLevelInfo: "info",
loglayer.LogLevelWarn: "warn",
loglayer.LogLevelError: "error",
loglayer.LogLevelFatal: "fatal",
loglayer.LogLevel(999): "unknown",
}
for level, want := range cases {
if got := level.String(); got != want {
t.Errorf("LogLevel(%d).String(): got %q, want %q", level, got, want)
}
}
}
func TestParseLogLevel(t *testing.T) {
cases := []struct {
in string
want loglayer.LogLevel
ok bool
}{
{"debug", loglayer.LogLevelDebug, true},
{"info", loglayer.LogLevelInfo, true},
{"warn", loglayer.LogLevelWarn, true},
{"error", loglayer.LogLevelError, true},
{"fatal", loglayer.LogLevelFatal, true},
{"INFO", loglayer.LogLevelInfo, false}, // case-sensitive
{"", loglayer.LogLevelInfo, false},
{"unknown", loglayer.LogLevelInfo, false},
}
for _, c := range cases {
got, ok := loglayer.ParseLogLevel(c.in)
if got != c.want || ok != c.ok {
t.Errorf("ParseLogLevel(%q) = (%s, %v), want (%s, %v)", c.in, got, ok, c.want, c.ok)
}
}
}
func TestLevelState_UnknownLevelIsNoop(t *testing.T) {
log, lib := setup(t)
// Unknown levels should not panic and should be safe.
log.EnableLevel(loglayer.LogLevel(0))
log.DisableLevel(loglayer.LogLevel(999))
log.SetLevel(loglayer.LogLevel(-5)) // should not blow up
// Standard levels should still work after weird calls.
log.Info("after weird levels")
if lib.Len() != 1 {
t.Errorf("expected 1 line after edge-case level changes, got %d", lib.Len())
}
}
func TestEnableLevel_AfterSetLevel(t *testing.T) {
log, lib := setup(t)
log.SetLevel(loglayer.LogLevelError)
log.Info("dropped")
log.EnableLevel(loglayer.LogLevelInfo)
log.Info("emitted")
if lib.Len() != 1 {
t.Errorf("expected 1 line after re-enabling info, got %d", lib.Len())
}
}
func TestUnmuteMetadata(t *testing.T) {
log, lib := setup(t)
log.MuteMetadata()
log.WithMetadata(loglayer.Metadata{"a": 1}).Info("muted")
first := lib.PopLine()
if first == nil || first.Metadata != nil {
t.Errorf("muted metadata should be nil, got %+v", first)
}
log.UnmuteMetadata()
log.WithMetadata(loglayer.Metadata{"a": 1}).Info("unmuted")
second := lib.PopLine()
if second == nil || second.Metadata == nil {
t.Errorf("unmuted metadata should be present, got %+v", second)
}
}
func TestPrefix_NonStringFirstArg(t *testing.T) {
log, lib := setupWithConfig(t, loglayer.Config{Prefix: "[app]"})
// Non-string first arg should be left alone (no prefix prepended).
log.Info(42, "context")
line := lib.PopLine()
if line == nil || line.Messages[0] != 42 {
t.Errorf("non-string first arg should be untouched, got %+v", line.Messages)
}
}
func TestPrefix_EmptyMessages(t *testing.T) {
log, lib := setupWithConfig(t, loglayer.Config{Prefix: "[app]"})
// Empty messages slice should not panic.
log.Info()
line := lib.PopLine()
if line == nil {
t.Fatal("expected entry even with empty messages")
}
if len(line.Messages) != 0 {
t.Errorf("expected empty messages, got %+v", line.Messages)
}
}