Repository navigation
Expand file tree
/
Copy pathevent_test.go
More file actions
396 lines (322 loc) · 10.5 KB
/
Copy pathevent_test.go
File metadata and controls
396 lines (322 loc) · 10.5 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
package axio
import (
"context"
"encoding/json"
"errors"
"strings"
"sync"
"testing"
"time"
)
func TestEvent_ContextPropagation(t *testing.T) {
t.Run("round_trip_through_context", func(t *testing.T) {
logger, _ := newEventLogger(t)
event := logger.Event("checkout")
ctx := WithEvent(context.Background(), event)
retrieved := EventFromContext(ctx)
if retrieved != event {
t.Error("expected same event from context")
}
})
t.Run("returns_nil_when_no_event_in_context", func(t *testing.T) {
retrieved := EventFromContext(context.Background())
if retrieved != nil {
t.Error("expected nil when no event in context")
}
})
}
func TestEvent_Add(t *testing.T) {
t.Run("adds_flat_fields_to_output", func(t *testing.T) {
logger, output := newEventLogger(t)
event := logger.Event("checkout")
event.Add("user_id", "usr_456")
event.Add("cart_total", 15999)
event.Add("premium", true)
event.Emit(context.Background())
result := parseEventJSON(t, output.String())
assertEqual(t, result["user_id"].(string), "usr_456")
assertEqual(t, result["cart_total"].(float64), float64(15999))
assertEqual(t, result["premium"].(bool), true)
})
t.Run("primitive_value_does_not_allocate", func(t *testing.T) {
event := &Event{annotations: make(Annotations, 0, 1)}
count, ratio, index := 15999, 0.75, 0
users := []string{"usr_456", "usr_789"}
tests := []struct {
name string
add func()
}{
{
name: "int",
add: func() {
count++
event.Add("count", count)
},
},
{
name: "float64",
add: func() {
ratio += 0.25
event.Add("ratio", ratio)
},
},
{
name: "string",
add: func() {
index++
event.Add("user_id", users[index%len(users)])
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
allocations := testing.AllocsPerRun(100, func() {
event.annotations = event.annotations[:0]
test.add()
})
if allocations != 0 {
t.Errorf("Add allocated %v times per call, want 0", allocations)
}
})
}
})
}
func TestEvent_With(t *testing.T) {
t.Run("accepts_annotations", func(t *testing.T) {
logger, output := newEventLogger(t)
event := logger.Event("http_request")
event.With(
Field("method", "POST"),
Field("url", "/api/checkout"),
)
event.Emit(context.Background())
result := parseEventJSON(t, output.String())
assertEqual(t, result["method"].(string), "POST")
assertEqual(t, result["url"].(string), "/api/checkout")
})
t.Run("accepts_annotable_types", func(t *testing.T) {
logger, output := newEventLogger(t)
event := logger.Event("http_request")
event.With(Field("http", HTTP{
Method: "POST",
URL: "/api/checkout",
StatusCode: 201,
LatencyMS: 45,
}))
event.Emit(context.Background())
result := parseEventJSON(t, output.String())
assertEqual(t, result["method"].(string), "POST")
assertEqual(t, result["url"].(string), "/api/checkout")
assertEqual(t, result["status_code"].(float64), float64(201))
assertEqual(t, result["latency"].(float64), float64(45))
})
t.Run("supports_nested_maps", func(t *testing.T) {
logger, output := newEventLogger(t)
event := logger.Event("checkout")
event.Add("user", map[string]any{
"id": "usr_456",
"subscription": "premium",
})
event.Emit(context.Background())
result := parseEventJSON(t, output.String())
userMap, ok := result["user"].(map[string]any)
if !ok {
t.Fatal("expected user to be a nested object")
}
assertEqual(t, userMap["id"].(string), "usr_456")
assertEqual(t, userMap["subscription"].(string), "premium")
})
}
func TestEvent_SetError(t *testing.T) {
t.Run("records_error_in_output", func(t *testing.T) {
logger, output := newEventLogger(t)
event := logger.Event("checkout")
event.SetError(errors.New("card declined"))
event.Emit(context.Background())
result := parseEventJSON(t, output.String())
assertEqual(t, result["error"].(string), "card declined")
})
t.Run("records_error_with_details", func(t *testing.T) {
logger, output := newEventLogger(t)
event := logger.Event("checkout")
event.SetError(errors.New("card declined"),
Field("error_code", "card_declined"),
Field("error_retriable", false),
)
event.Emit(context.Background())
result := parseEventJSON(t, output.String())
assertEqual(t, result["error"].(string), "card declined")
assertEqual(t, result["error_code"].(string), "card_declined")
assertEqual(t, result["error_retriable"].(bool), false)
})
t.Run("no_error_field_when_not_set", func(t *testing.T) {
logger, output := newEventLogger(t)
event := logger.Event("checkout")
event.Emit(context.Background())
result := parseEventJSON(t, output.String())
if _, ok := result["error"]; ok {
t.Error("event without error should not have error field")
}
})
}
func TestEvent_Emit(t *testing.T) {
t.Run("emits_event_with_name_and_duration", func(t *testing.T) {
logger, output := newEventLogger(t)
event := logger.Event("checkout")
event.Emit(context.Background())
result := parseEventJSON(t, output.String())
// Must have event name
assertEqual(t, result["event"].(string), "checkout")
// Must have duration_ms
if _, ok := result["duration_ms"]; !ok {
t.Error("expected duration_ms field in output")
}
// Must have timestamp
if _, ok := result["timestamp"]; !ok {
t.Error("expected timestamp field in output")
}
// Must NOT have level
if _, ok := result["level"]; ok {
t.Error("event output should not contain level field")
}
// Must NOT have caller
if _, ok := result["caller"]; ok {
t.Error("event output should not contain caller field")
}
// Must NOT have logger name: the root logger has none
if _, ok := result["logger"]; ok {
t.Error("event output should not contain logger field")
}
// Must NOT have stacktrace
if _, ok := result["stacktrace"]; ok {
t.Error("event output should not contain stacktrace field")
}
})
t.Run("empty_event_has_name_and_duration_only", func(t *testing.T) {
logger, output := newEventLogger(t)
event := logger.Event("ping")
event.Emit(context.Background())
result := parseEventJSON(t, output.String())
// Only timestamp, event, duration_ms should be present
assertEqual(t, result["event"].(string), "ping")
if _, ok := result["duration_ms"]; !ok {
t.Error("expected duration_ms")
}
if _, ok := result["timestamp"]; !ok {
t.Error("expected timestamp")
}
})
t.Run("concurrent_enrichment_is_safe", func(t *testing.T) {
logger, output := newEventLogger(t)
event := logger.Event("concurrent")
var waitGroup sync.WaitGroup
for index := 0; index < 100; index++ {
waitGroup.Add(1)
go func(number int) {
defer waitGroup.Done()
event.Add("field", number)
}(index)
}
waitGroup.Wait()
event.Emit(context.Background())
if output.String() == "" {
t.Error("expected event output after concurrent enrichment")
}
})
t.Run("pii_masking_works_on_event_fields", func(t *testing.T) {
logger, output := newEventLogger(t, WithPII([]PIIPattern{PatternCPF}, DefaultSensitiveFields()))
event := logger.Event("checkout")
event.Add("document", "123.456.789-01")
event.Emit(context.Background())
content := output.String()
if strings.Contains(content, "123.456.789-01") {
t.Error("CPF should have been masked by PII hook")
}
if !strings.Contains(content, "***.***.***-**") {
t.Error("expected masked CPF pattern in output")
}
})
t.Run("pii_masking_works_on_error_details", func(t *testing.T) {
logger, output := newEventLogger(t, WithPII([]PIIPattern{PatternCPF}, DefaultSensitiveFields()))
event := logger.Event("checkout")
event.SetError(errors.New("validation failed"),
Field("customer_document", "123.456.789-01"),
)
event.Emit(context.Background())
content := output.String()
if strings.Contains(content, "123.456.789-01") {
t.Error("CPF in error details should have been masked by PII hook")
}
if !strings.Contains(content, "***.***.***-**") {
t.Error("expected masked CPF pattern in error details")
}
})
t.Run("timestamp_is_event_start_time", func(t *testing.T) {
logger, output := newEventLogger(t)
event := logger.Event("checkout")
startTime := event.startTime
// Sleep to create a measurable gap between start and emit
time.Sleep(50 * time.Millisecond)
event.Emit(context.Background())
result := parseEventJSON(t, output.String())
timestampStr := result["timestamp"].(string)
parsed, parseErr := time.Parse(time.RFC3339Nano, timestampStr)
assertNoError(t, parseErr)
// Timestamp must equal the start time, not the emit time.
// With 50ms sleep, if timestamp were time.Now() at emit,
// the diff would be >= 50ms.
diff := parsed.Sub(startTime.UTC())
if diff < 0 {
diff = -diff
}
if diff > 5*time.Millisecond {
t.Errorf("timestamp should equal start time, but diff was %v (timestamp=%v, startTime=%v)",
diff, parsed, startTime.UTC())
}
})
}
func TestEvent_Emit_Idempotent(t *testing.T) {
logger, output := newEventLogger(t)
event := logger.Event("once")
ctx := context.Background()
event.Emit(ctx)
event.Emit(ctx)
content := output.String()
lines := strings.Split(strings.TrimRight(content, "\n"), "\n")
if len(lines) != 1 {
t.Fatalf("expected exactly one emitted line, got %d:\n%s", len(lines), content)
}
result := parseEventJSON(t, lines[0])
assertEqual(t, result["event"].(string), "once")
}
func TestEvent_Emit_HookChangesName(t *testing.T) {
rename := &testHook{name: "rename", process: func(_ context.Context, entry *Entry) error {
entry.Message = "checkout_v2"
return nil
}}
logger, output := newEventLogger(t, WithHooks(rename))
logger.Event("checkout").Emit(context.Background())
result := parseEventJSON(t, output.String())
assertEqual(t, result["event"].(string), "checkout_v2")
}
// newEventLogger returns a logger built with options over a JSON output, closed
// when the test ends, to derive the events under test from, and that output.
func newEventLogger(t *testing.T, options ...Option) (Logger, *bufferOutput) {
t.Helper()
output := newBufferOutput(FormatJSON)
logger, err := New(minimalConfig(), append([]Option{WithOutputs(output)}, options...)...)
if err != nil {
t.Fatalf("new logger: %v", err)
}
t.Cleanup(func() { assertNoError(t, logger.Close()) })
return logger, output
}
// parseEventJSON parses a single JSON line from event output.
func parseEventJSON(t *testing.T, content string) map[string]any {
t.Helper()
var result map[string]any
if err := json.Unmarshal([]byte(strings.TrimSpace(content)), &result); err != nil {
t.Fatalf("failed to parse event JSON: %v\ncontent: %s", err, content)
}
return result
}