-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors_test.go
More file actions
483 lines (387 loc) · 10.6 KB
/
errors_test.go
File metadata and controls
483 lines (387 loc) · 10.6 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
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
package ewrap
import (
"errors"
"fmt"
"strings"
"sync"
"testing"
)
// MockLogger implements the logger.Logger interface for testing.
type MockLogger struct {
mu sync.Mutex
logs []LogEntry
called map[string]int
}
type LogEntry struct {
Level string
Msg string
Args []any
}
func (m *MockLogger) Info(msg string, args ...any) {
m.mu.Lock()
defer m.mu.Unlock()
m.logs = append(m.logs, LogEntry{Level: "info", Msg: msg, Args: args})
}
func (m *MockLogger) Debug(msg string, args ...any) {
m.mu.Lock()
defer m.mu.Unlock()
m.logs = append(m.logs, LogEntry{Level: "debug", Msg: msg, Args: args})
m.called["debug"]++
}
func (m *MockLogger) Error(msg string, args ...any) {
m.mu.Lock()
defer m.mu.Unlock()
m.logs = append(m.logs, LogEntry{Level: "error", Msg: msg, Args: args})
m.called["error"]++
}
func NewMockLogger() *MockLogger {
return &MockLogger{
logs: make([]LogEntry, 0),
called: make(map[string]int),
}
}
func (m *MockLogger) GetLogs() []LogEntry {
m.mu.Lock()
defer m.mu.Unlock()
return m.logs
}
func (m *MockLogger) GetCallCount(level string) int {
m.mu.Lock()
defer m.mu.Unlock()
return m.called[level]
}
func TestNew(t *testing.T) {
t.Run("creates error with message", func(t *testing.T) {
err := New("test error")
if err.Error() != "test error" {
t.Errorf("expected 'test error', got '%s'", err.Error())
}
if len(err.stack) == 0 {
t.Error("expected stack trace to be captured")
}
if err.metadata == nil {
t.Error("expected metadata to be initialized")
}
})
t.Run("applies options", func(t *testing.T) {
mockLogger := NewMockLogger()
err := New("test error", WithLogger(mockLogger))
if err.logger != mockLogger {
t.Error("expected logger to be set")
}
if mockLogger.GetCallCount("debug") != 1 {
t.Error("expected logger debug to be called once")
}
})
}
func TestNewf(t *testing.T) {
err := Newf("test error %d", 42)
expected := "test error 42"
if err.Error() != expected {
t.Errorf("expected '%s', got '%s'", expected, err.Error())
}
}
func TestWrap(t *testing.T) {
t.Run("wraps nil error returns nil", func(t *testing.T) {
result := Wrap(nil, "test")
if result != nil {
t.Error("expected nil when wrapping nil error")
}
})
t.Run("wraps standard error", func(t *testing.T) {
originalErr := errors.New("original error")
wrapped := Wrap(originalErr, "wrapped")
if wrapped.msg != "wrapped" {
t.Errorf("expected message 'wrapped', got '%s'", wrapped.msg)
}
if !errors.Is(wrapped.cause, originalErr) {
t.Error("expected cause to be set to original error")
}
expected := "wrapped: original error"
if wrapped.Error() != expected {
t.Errorf("expected '%s', got '%s'", expected, wrapped.Error())
}
})
t.Run("wraps custom Error preserving stack and metadata", func(t *testing.T) {
original := New("original").WithMetadata("key", "value")
wrapped := Wrap(original, "wrapped")
if len(wrapped.stack) == 0 {
t.Error("expected stack trace to be preserved")
}
if val, ok := wrapped.GetMetadata("key"); !ok || val != "value" {
t.Error("expected metadata to be preserved")
}
})
}
func TestWrapf(t *testing.T) {
t.Run("wraps nil error returns nil", func(t *testing.T) {
result := Wrapf(nil, "test %d", 42)
if result != nil {
t.Error("expected nil when wrapping nil error")
}
})
t.Run("wraps with formatted message", func(t *testing.T) {
originalErr := errors.New("original")
wrapped := Wrapf(originalErr, "wrapped %d", 42)
expected := "wrapped 42: original"
if wrapped.Error() != expected {
t.Errorf("expected '%s', got '%s'", expected, wrapped.Error())
}
})
}
func TestError_Error(t *testing.T) {
t.Run("returns message when no cause", func(t *testing.T) {
err := New("test message")
if err.Error() != "test message" {
t.Errorf("expected 'test message', got '%s'", err.Error())
}
})
t.Run("returns message with cause", func(t *testing.T) {
cause := errors.New("cause error")
err := Wrap(cause, "wrapped")
expected := "wrapped: cause error"
if err.Error() != expected {
t.Errorf("expected '%s', got '%s'", expected, err.Error())
}
})
}
func TestError_Cause(t *testing.T) {
t.Run("returns nil for new error", func(t *testing.T) {
err := New("test")
if err.Cause() != nil {
t.Error("expected nil cause for new error")
}
})
t.Run("returns cause for wrapped error", func(t *testing.T) {
cause := errors.New("original")
wrapped := Wrap(cause, "wrapped")
if !errors.Is(wrapped.Cause(), cause) {
t.Error("expected cause to match original error")
}
})
}
func TestError_WithMetadata(t *testing.T) {
err := New("test")
result := err.WithMetadata("key", "value")
if result != err {
t.Error("expected WithMetadata to return same error instance")
}
val, ok := err.GetMetadata("key")
if !ok {
t.Error("expected metadata to be set")
}
if val != "value" {
t.Errorf("expected 'value', got '%v'", val)
}
}
func TestError_WithContext(t *testing.T) {
err := New("test")
ctx := &ErrorContext{}
result := err.WithContext(ctx)
if result != err {
t.Error("expected WithContext to return same error instance")
}
retrievedCtx := err.GetErrorContext()
if retrievedCtx != ctx {
t.Error("expected context to be set")
}
}
func TestError_GetMetadata(t *testing.T) {
err := New("test").WithMetadata("key", "value")
t.Run("existing key", func(t *testing.T) {
val, ok := err.GetMetadata("key")
if !ok {
t.Error("expected key to exist")
}
if val != "value" {
t.Errorf("expected 'value', got '%v'", val)
}
})
t.Run("non-existing key", func(t *testing.T) {
val, ok := err.GetMetadata("nonexistent")
if ok {
t.Error("expected key to not exist")
}
if val != nil {
t.Errorf("expected nil value, got '%v'", val)
}
})
}
func TestError_GetMetadataValue(t *testing.T) {
err := New("test").WithMetadata("count", 5)
val, ok := GetMetadataValue[int](err, "count")
if !ok || val != 5 {
t.Errorf("expected typed metadata 5, got %v (ok=%v)", val, ok)
}
_, ok = GetMetadataValue[int](err, "missing")
if ok {
t.Error("expected missing key to return ok=false")
}
}
func TestWithRecoverySuggestion(t *testing.T) {
mockLogger := NewMockLogger()
rs := &RecoverySuggestion{Message: "restart"}
err := New("test", WithLogger(mockLogger), WithRecoverySuggestion(rs))
logs := mockLogger.GetLogs()
infoCount := 0
for _, l := range logs {
if l.Level == "info" {
infoCount++
}
}
if infoCount != 1 {
t.Error("expected info log when adding recovery suggestion")
}
retrieved, ok := GetMetadataValue[*RecoverySuggestion](err, "recovery_suggestion")
if !ok || retrieved.Message != rs.Message {
t.Error("expected recovery suggestion metadata to be set")
}
err.Log()
logs = mockLogger.GetLogs()
found := false
for _, entry := range logs {
if entry.Level == "error" {
for i := 0; i < len(entry.Args); i += 2 {
if entry.Args[i] == "recovery_message" && entry.Args[i+1] == rs.Message {
found = true
}
}
}
}
if !found {
t.Error("expected recovery_message in error log")
}
}
func TestError_Stack(t *testing.T) {
err := New("test")
stack := err.Stack()
if stack == "" {
t.Error("expected non-empty stack trace")
}
// Should not contain runtime frames or error package frames
if strings.Contains(stack, "runtime/") {
t.Error("stack should not contain runtime frames")
}
if strings.Contains(stack, "ewrap/errors.go") {
t.Error("stack should not contain error package frames")
}
}
func TestError_Log(t *testing.T) {
t.Run("does nothing when no logger", func(t *testing.T) {
err := New("test")
err.Log() // Should not panic
})
t.Run("logs with logger", func(t *testing.T) {
mockLogger := NewMockLogger()
err := New("test", WithLogger(mockLogger)).WithMetadata("key", "value")
err.Log()
if mockLogger.GetCallCount("error") != 1 {
t.Error("expected error log to be called once")
}
logs := mockLogger.GetLogs()
if len(logs) < 2 { // At least creation debug log and error log
t.Error("expected at least 2 log entries")
}
})
t.Run("logs with cause", func(t *testing.T) {
mockLogger := NewMockLogger()
cause := errors.New("original")
err := Wrap(cause, "wrapped", WithLogger(mockLogger))
err.Log()
if mockLogger.GetCallCount("error") != 1 {
t.Error("expected error log to be called once")
}
})
}
func TestCaptureStack(t *testing.T) {
stack := CaptureStack()
if len(stack) == 0 {
t.Error("expected non-empty stack trace")
}
}
func TestError_Is(t *testing.T) {
t.Run("returns false for nil target", func(t *testing.T) {
err := New("test")
if errors.Is(err, nil) {
t.Error("expected false for nil target")
}
})
t.Run("matches sentinel error", func(t *testing.T) {
sentinel := errors.New("sentinel")
wrapped := Wrap(sentinel, "wrapped")
if !errors.Is(wrapped, sentinel) {
t.Error("expected true for sentinel error in chain")
}
})
t.Run("matches ewrap sentinel", func(t *testing.T) {
sentinel := New("sentinel")
wrapped := Wrap(sentinel, "wrapped")
if !errors.Is(wrapped, sentinel) {
t.Error("expected true for ewrap sentinel in chain")
}
})
t.Run("prevents infinite recursion with self-reference", func(t *testing.T) {
err1 := New("error1")
err2 := New("error2")
// This would create a cycle if not handled properly
if errors.Is(err1, err2) {
t.Error("expected false for different errors")
}
})
t.Run("non-matching error", func(t *testing.T) {
err := New("test error")
target := errors.New("other")
if errors.Is(err, target) {
t.Error("expected false for non-matching error")
}
})
}
func TestError_Unwrap(t *testing.T) {
t.Run("returns nil for new error", func(t *testing.T) {
err := New("test")
if err.Unwrap() != nil {
t.Error("expected nil for new error")
}
})
t.Run("returns cause for wrapped error", func(t *testing.T) {
cause := errors.New("original")
wrapped := Wrap(cause, "wrapped")
if !errors.Is(wrapped.Unwrap(), cause) {
t.Error("expected unwrap to return cause")
}
})
}
func TestWithLogger(t *testing.T) {
mockLogger := NewMockLogger()
option := WithLogger(mockLogger)
err := &Error{
msg: "test",
metadata: make(map[string]any),
stack: CaptureStack(),
}
option(err)
if err.logger != mockLogger {
t.Error("expected logger to be set")
}
if mockLogger.GetCallCount("debug") != 1 {
t.Error("expected debug log to be called once")
}
}
func TestConcurrentAccess(t *testing.T) {
err := New("test")
// Test concurrent metadata access
var wg sync.WaitGroup
for i := range 100 {
wg.Add(2)
go func(i int) {
defer wg.Done()
err.WithMetadata(fmt.Sprintf("key%d", i), i)
}(i)
go func(i int) {
defer wg.Done()
err.GetMetadata(fmt.Sprintf("key%d", i))
}(i)
}
wg.Wait()
// Should not panic or race
}