-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy patherrors_test.go
More file actions
1473 lines (1318 loc) · 44.7 KB
/
errors_test.go
File metadata and controls
1473 lines (1318 loc) · 44.7 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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package errors provides a robust error handling library with support for
// error wrapping, stack traces, context storage, and retry mechanisms.
// This test file verifies the correctness of the error type and its methods,
// ensuring proper behavior for creation, wrapping, inspection, and serialization.
// Tests cover edge cases, standard library compatibility, and thread-safety.
package errors
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"sync"
"testing"
"time"
)
// customError is a test-specific error type for verifying error wrapping and traversal.
type customError struct {
msg string
cause error
}
func (e *customError) Error() string {
return e.msg
}
func (e *customError) Cause() error {
return e.cause
}
// TestErrorNew verifies that New creates an error with the specified message
// and does not capture a stack trace, ensuring lightweight error creation.
func TestErrorNew(t *testing.T) {
err := New("test error")
defer err.Free()
if err.Error() != "test error" {
t.Errorf("New() error message = %v, want %v", err.Error(), "test error")
}
if len(err.Stack()) != 0 {
t.Errorf("New() should not capture stack trace, got %d frames", len(err.Stack()))
}
}
// TestErrorNewf checks that Newf formats the error message correctly using
// the provided format string and arguments, without capturing a stack trace.
func TestErrorNewf(t *testing.T) {
err := Newf("test %s %d", "error", 42)
defer err.Free()
want := "test error 42"
if err.Error() != want {
t.Errorf("Newf() error message = %v, want %v", err.Error(), want)
}
if len(err.Stack()) != 0 {
t.Errorf("Newf() should not capture stack trace, got %d frames", len(err.Stack()))
}
}
// TestErrorNamed ensures that Named creates a named error with the given name
// and captures a stack trace for debugging purposes.
func TestErrorNamed(t *testing.T) {
err := Named("test_name")
defer err.Free()
if err.Error() != "test_name" {
t.Errorf("Named() error message = %v, want %v", err.Error(), "test_name")
}
if len(err.Stack()) == 0 {
t.Errorf("Named() should capture stack trace")
}
}
// TestErrorMethods tests the core methods of the Error type, including context
// addition, wrapping, message formatting, stack tracing, and metadata handling.
func TestErrorMethods(t *testing.T) {
err := New("base error")
defer err.Free()
// Test With for adding key-value context.
err = err.With("key", "value")
if err.Context()["key"] != "value" {
t.Errorf("With() failed, context[key] = %v, want %v", err.Context()["key"], "value")
}
// Test Wrap for setting a cause.
cause := New("cause error")
defer cause.Free()
err = err.Wrap(cause)
if err.Unwrap() != cause {
t.Errorf("Wrap() failed, unwrapped = %v, want %v", err.Unwrap(), cause)
}
// Test Msgf for updating the error message.
err = err.Msgf("new message %d", 123)
if err.Error() != "new message 123: cause error" {
t.Errorf("Msgf() failed, error = %v, want %v", err.Error(), "new message 123: cause error")
}
// Test stack absence initially.
stackLen := len(err.Stack())
if stackLen != 0 {
t.Errorf("Initial stack length should be 0, got %d", stackLen)
}
// Test Trace for capturing a stack trace.
err = err.Trace()
if len(err.Stack()) == 0 {
t.Errorf("Trace() should capture a stack trace, got no frames")
}
// Test WithCode for setting an HTTP status code.
err = err.WithCode(400)
if err.Code() != 400 {
t.Errorf("WithCode() failed, code = %d, want 400", err.Code())
}
// Test WithCategory for setting a category.
err = err.WithCategory("test_category")
if Category(err) != "test_category" {
t.Errorf("WithCategory() failed, category = %v, want %v", Category(err), "test_category")
}
// Test Increment for counting occurrences.
err = err.Increment()
if err.Count() != 1 {
t.Errorf("Increment() failed, count = %d, want 1", err.Count())
}
}
// TestErrorIs verifies that Is correctly identifies errors by name or through
// wrapping, including compatibility with standard library errors.
func TestErrorIs(t *testing.T) {
err := Named("test_error")
defer err.Free()
err2 := Named("test_error")
defer err2.Free()
err3 := Named("other_error")
defer err3.Free()
// Test matching same-named errors.
if !err.Is(err2) {
t.Errorf("Is() failed, %v should match %v", err, err2)
}
// Test non-matching names.
if err.Is(err3) {
t.Errorf("Is() failed, %v should not match %v", err, err3)
}
// Test wrapped error matching.
wrappedErr := Named("wrapper")
defer wrappedErr.Free()
cause := Named("cause_error")
defer cause.Free()
wrappedErr = wrappedErr.Wrap(cause)
if !wrappedErr.Is(cause) {
t.Errorf("Is() failed, wrapped error should match cause; wrappedErr = %+v, cause = %+v", wrappedErr, cause)
}
// Test wrapping standard library error.
stdErr := errors.New("std error")
wrappedErr = wrappedErr.Wrap(stdErr)
if !wrappedErr.Is(stdErr) {
t.Errorf("Is() failed, should match stdlib error")
}
}
// TestErrorAs checks that As unwraps to the correct error type, supporting
// both custom *Error and standard library errors.
func TestErrorAs(t *testing.T) {
err := New("base").Wrap(Named("target"))
defer err.Free()
var target *Error
if !As(err, &target) {
t.Errorf("As() failed, should unwrap to *Error")
}
if target.name != "target" {
t.Errorf("As() unwrapped to wrong error, got %v, want %v", target.name, "target")
}
stdErr := errors.New("std error")
err = New("wrapper").Wrap(stdErr)
defer err.Free()
var stdTarget error
if !As(err, &stdTarget) {
t.Errorf("As() failed, should unwrap to stdlib error")
}
if stdTarget != stdErr {
t.Errorf("As() unwrapped to wrong error, got %v, want %v", stdTarget, stdErr)
}
}
// TestErrorCount verifies that Count tracks per-instance error occurrences.
func TestErrorCount(t *testing.T) {
err := New("unnamed")
defer err.Free()
if err.Count() != 0 {
t.Errorf("Count() on new error should be 0, got %d", err.Count())
}
err = Named("test_count").Increment()
if err.Count() != 1 {
t.Errorf("Count() after Increment() should be 1, got %d", err.Count())
}
}
// TestErrorCode ensures that Code correctly sets and retrieves HTTP status codes.
func TestErrorCode(t *testing.T) {
err := New("unnamed")
defer err.Free()
if err.Code() != 0 {
t.Errorf("Code() on new error should be 0, got %d", err.Code())
}
err = Named("test_code").WithCode(400)
if err.Code() != 400 {
t.Errorf("Code() after WithCode(400) should be 400, got %d", err.Code())
}
}
// TestErrorMarshalJSON verifies that JSON serialization includes all expected
// fields: message, context, cause, code, and stack (when present).
func TestErrorMarshalJSON(t *testing.T) {
// Test basic error with context, code, and cause.
err := New("test").
With("key", "value").
WithCode(400).
Wrap(Named("cause"))
defer err.Free()
data, e := json.Marshal(err)
if e != nil {
t.Fatalf("MarshalJSON() failed: %v", e)
}
want := map[string]interface{}{
"message": "test",
"context": map[string]interface{}{"key": "value"},
"cause": map[string]interface{}{"name": "cause"},
"code": float64(400),
}
var got map[string]interface{}
if err := json.Unmarshal(data, &got); err != nil {
t.Fatalf("Unmarshal failed: %v", err)
}
if got["message"] != want["message"] {
t.Errorf("MarshalJSON() message = %v, want %v", got["message"], want["message"])
}
if !reflect.DeepEqual(got["context"], want["context"]) {
t.Errorf("MarshalJSON() context = %v, want %v", got["context"], want["context"])
}
if cause, ok := got["cause"].(map[string]interface{}); !ok || cause["name"] != "cause" {
t.Errorf("MarshalJSON() cause = %v, want %v", got["cause"], want["cause"])
}
if code, ok := got["code"].(float64); !ok || code != 400 {
t.Errorf("MarshalJSON() code = %v, want %v", got["code"], 400)
}
// Test error with stack trace.
t.Run("WithStack", func(t *testing.T) {
err := New("test").WithStack().WithCode(500)
defer err.Free()
data, e := json.Marshal(err)
if e != nil {
t.Fatalf("MarshalJSON() failed: %v", e)
}
var got map[string]interface{}
if err := json.Unmarshal(data, &got); err != nil {
t.Fatalf("Unmarshal failed: %v", err)
}
if _, ok := got["stack"].([]interface{}); !ok || len(got["stack"].([]interface{})) == 0 {
t.Error("MarshalJSON() should include non-empty stack")
}
if code, ok := got["code"].(float64); !ok || code != 500 {
t.Errorf("MarshalJSON() code = %v, want 500", got["code"])
}
})
}
// TestErrorEdgeCases verifies behavior for unusual inputs, such as nil errors,
// empty names, and standard library error wrapping.
func TestErrorEdgeCases(t *testing.T) {
// Test nil error handling.
var nilErr *Error
if nilErr.Is(nil) {
t.Errorf("nil.Is(nil) should be false, got true")
}
if Is(nilErr, New("test")) {
t.Errorf("Is(nil, non-nil) should be false")
}
// Test empty name mismatch.
err := New("empty name")
defer err.Free()
if err.Is(Named("")) {
t.Errorf("Error with empty name should not match unnamed error")
}
// Test wrapping standard library error.
stdErr := errors.New("std error")
customErr := New("custom").Wrap(stdErr)
defer customErr.Free()
if !Is(customErr, stdErr) {
t.Errorf("Is() should match stdlib error through wrapping")
}
// Test As with nil error.
var nilTarget *Error
if As(nilErr, &nilTarget) {
t.Errorf("As(nil, &nilTarget) should return false")
}
// Additional edge case: Wrapping nil error.
t.Run("WrapNil", func(t *testing.T) {
err := New("wrapper").Wrap(nil)
defer err.Free()
if err.Unwrap() != nil {
t.Errorf("Wrap(nil) should set cause to nil, got %v", err.Unwrap())
}
if err.Error() != "wrapper" {
t.Errorf("Wrap(nil) should preserve message, got %v, want %v", err.Error(), "wrapper")
}
})
}
// TestErrorRetryWithCallback verifies the retry mechanism, ensuring the callback
// is invoked correctly and retries exhaust as expected for retryable errors.
func TestErrorRetryWithCallback(t *testing.T) {
// Test retry with multiple attempts.
attempts := 0
retry := NewRetry(
WithMaxAttempts(3),
WithDelay(1*time.Millisecond),
WithOnRetry(func(attempt int, err error) {
attempts++
}),
)
err := retry.Execute(func() error {
return New("retry me").WithRetryable()
})
if attempts != 3 {
t.Errorf("Expected 3 retry attempts, got %d", attempts)
}
if err == nil {
t.Error("Expected retry to exhaust with error, got nil")
}
// Test zero max attempts, expecting one initial attempt (not a retry).
t.Run("ZeroAttempts", func(t *testing.T) {
attempts := 0
retry := NewRetry(
WithMaxAttempts(0),
WithOnRetry(func(attempt int, err error) {
attempts++
}),
)
err := retry.Execute(func() error {
return New("retry me").WithRetryable()
})
// Expect one attempt, as Execute runs the function once before checking retries.
if attempts != 1 {
t.Errorf("Expected 1 attempt (initial execution), got %d", attempts)
}
if err == nil {
t.Error("Expected error, got nil")
}
})
}
// TestErrorStackPresence confirms stack trace behavior for New and Trace methods.
func TestErrorStackPresence(t *testing.T) {
// New should not capture stack.
err := New("test")
if len(err.Stack()) != 0 {
t.Error("New() should not capture stack")
}
// Trace should capture stack.
traced := Trace("test")
if len(traced.Stack()) == 0 {
t.Error("Trace() should capture stack")
}
}
// TestErrorStackDepth ensures that stack traces respect the configured maximum depth.
func TestErrorStackDepth(t *testing.T) {
err := Trace("test")
frames := err.Stack()
if len(frames) > currentConfig.stackDepth {
t.Errorf("Stack depth %d exceeds configured max %d", len(frames), currentConfig.stackDepth)
}
}
// TestErrorTransform verifies Transform behavior for nil, non-*Error, and *Error inputs.
func TestErrorTransform(t *testing.T) {
// Test nil input.
t.Run("NilError", func(t *testing.T) {
result := Transform(nil, func(e *Error) {})
if result != nil {
t.Error("Should return nil for nil input")
}
})
// Test standard library error.
t.Run("NonErrorType", func(t *testing.T) {
stdErr := errors.New("standard")
transformed := Transform(stdErr, func(e *Error) {})
if transformed == nil {
t.Error("Should not return nil for non-nil input")
}
if transformed.Error() != "standard" {
t.Errorf("Should preserve original message, got %q, want %q", transformed.Error(), "standard")
}
if transformed == stdErr {
t.Error("Should return a new *Error, not the original")
}
})
// Test transforming *Error.
t.Run("TransformError", func(t *testing.T) {
orig := New("original")
defer orig.Free()
transformed := Transform(orig, func(e *Error) {
e.With("key", "value")
})
defer transformed.Free()
if transformed == orig {
t.Error("Should return a copy, not the original")
}
if transformed.Error() != "original" {
t.Errorf("Should preserve original message, got %q, want %q", transformed.Error(), "original")
}
if transformed.Context()["key"] != "value" {
t.Error("Should apply transformations, context missing 'key'='value'")
}
})
}
// TestErrorWalk ensures Walk traverses the error chain correctly, visiting all errors.
func TestErrorWalk(t *testing.T) {
err1 := &customError{msg: "first error", cause: nil}
err2 := &customError{msg: "second error", cause: err1}
err3 := &customError{msg: "third error", cause: err2}
var errorsWalked []string
Walk(err3, func(e error) {
errorsWalked = append(errorsWalked, e.Error())
})
expected := []string{"third error", "second error", "first error"}
if !reflect.DeepEqual(errorsWalked, expected) {
t.Errorf("Walk() = %v; want %v", errorsWalked, expected)
}
}
// TestErrorFind verifies Find locates the first error matching the predicate.
func TestErrorFind(t *testing.T) {
err1 := &customError{msg: "first error", cause: nil}
err2 := &customError{msg: "second error", cause: err1}
err3 := &customError{msg: "third error", cause: err2}
// Find existing error.
found := Find(err3, func(e error) bool {
return e.Error() == "second error"
})
if found == nil || found.Error() != "second error" {
t.Errorf("Find() = %v; want 'second error'", found)
}
// Find non-existent error.
found = Find(err3, func(e error) bool {
return e.Error() == "non-existent error"
})
if found != nil {
t.Errorf("Find() = %v; want nil", found)
}
}
// TestErrorTraceStackContent checks that Trace captures meaningful stack frames.
func TestErrorTraceStackContent(t *testing.T) {
err := Trace("test")
defer err.Free()
frames := err.Stack()
if len(frames) == 0 {
t.Fatal("Trace() should capture stack frames")
}
found := false
for _, frame := range frames {
if strings.Contains(frame, "testing.tRunner") {
found = true
break
}
}
if !found {
t.Errorf("Trace() stack does not contain testing.tRunner, got: %v", frames)
}
}
// TestErrorWithStackContent ensures WithStack captures meaningful stack frames.
func TestErrorWithStackContent(t *testing.T) {
err := New("test").WithStack()
defer err.Free()
frames := err.Stack()
if len(frames) == 0 {
t.Fatal("WithStack() should capture stack frames")
}
found := false
for _, frame := range frames {
if strings.Contains(frame, "testing.tRunner") {
found = true
break
}
}
if !found {
t.Errorf("WithStack() stack does not contain testing.tRunner, got: %v", frames)
}
}
// TestErrorWrappingChain verifies a complex error chain with multiple layers,
// ensuring correct message propagation, context isolation, and stack behavior.
func TestErrorWrappingChain(t *testing.T) {
databaseErr := New("connection timeout").
With("timeout_sec", 5).
With("server", "db01.prod")
defer databaseErr.Free()
businessErr := New("failed to process user 12345").
With("user_id", "12345").
With("stage", "processing").
Wrap(databaseErr)
defer businessErr.Free()
apiErr := New("API request failed").
WithCode(500).
WithStack().
Wrap(businessErr)
defer apiErr.Free()
// Verify full error message.
expectedFullMessage := "API request failed: failed to process user 12345: connection timeout"
if apiErr.Error() != expectedFullMessage {
t.Errorf("Full error message mismatch\ngot: %q\nwant: %q", apiErr.Error(), expectedFullMessage)
}
// Verify error chain.
chain := UnwrapAll(apiErr)
if len(chain) != 3 {
t.Fatalf("Expected chain length 3, got %d", len(chain))
}
tests := []struct {
index int
expected string
}{
{0, "API request failed"},
{1, "failed to process user 12345"},
{2, "connection timeout"},
}
for _, tt := range tests {
if chain[tt.index].Error() != tt.expected {
t.Errorf("Chain position %d mismatch\ngot: %q\nwant: %q", tt.index, chain[tt.index].Error(), tt.expected)
}
}
// Verify Is checks.
if !errors.Is(apiErr, databaseErr) {
t.Error("Is() should match the database error in the chain")
}
// Verify context isolation.
if ctx := businessErr.Context(); ctx["timeout_sec"] != nil {
t.Error("Business error should not have database context")
}
// Verify stack presence.
if stack := apiErr.Stack(); len(stack) == 0 {
t.Error("API error should have stack trace")
}
if stack := businessErr.Stack(); len(stack) != 0 {
t.Error("Business error should not have stack trace")
}
// Verify code propagation.
if apiErr.Code() != 500 {
t.Error("API error should have code 500")
}
if businessErr.Code() != 0 {
t.Error("Business error should have no code")
}
}
// TestErrorExampleOutput verifies that formatted output includes all relevant
// details, such as message, context, code, and stack, for a realistic error chain.
func TestErrorExampleOutput(t *testing.T) {
databaseErr := New("connection timeout").
With("timeout_sec", 5).
With("server", "db01.prod")
businessErr := New("failed to process user 12345").
With("user_id", "12345").
With("stage", "processing").
Wrap(databaseErr)
apiErr := New("API request failed").
WithCode(500).
WithStack().
Wrap(businessErr)
chain := UnwrapAll(apiErr)
for _, err := range chain {
if e, ok := err.(*Error); ok {
formatted := e.Format()
if formatted == "" {
t.Error("Format() returned empty string")
}
if !strings.Contains(formatted, "Error: "+e.Error()) {
t.Errorf("Format() output missing error message: %q", formatted)
}
if e == apiErr {
if !strings.Contains(formatted, "Code: 500") {
t.Error("Format() missing code for API error")
}
if !strings.Contains(formatted, "Stack:") {
t.Error("Format() missing stack for API error")
}
}
if e == businessErr {
if ctx := e.Context(); ctx != nil {
if !strings.Contains(formatted, "Context:") {
t.Error("Format() missing context for business error")
}
for k := range ctx {
if !strings.Contains(formatted, k) {
t.Errorf("Format() missing context key %q", k)
}
}
}
}
}
}
if !errors.Is(apiErr, errors.New("connection timeout")) {
t.Error("Is() failed to match connection timeout error")
}
}
// TestErrorFullChain tests a complex chain with mixed error types (custom and standard),
// verifying wrapping, unwrapping, and compatibility with standard library functions.
func TestErrorFullChain(t *testing.T) {
stdErr := errors.New("file not found")
authErr := Named("AuthError").WithCode(401)
storageErr := Wrapf(stdErr, "storage failed")
authErrWrapped := Wrap(storageErr, authErr)
wrapped := Wrapf(authErrWrapped, "request failed")
var targetAuth *Error
expectedTopLevelMsg := "request failed: AuthError: storage failed: file not found"
if !errors.As(wrapped, &targetAuth) || targetAuth.Error() != expectedTopLevelMsg {
t.Errorf("stderrors.As(wrapped, &targetAuth) failed, got %v, want %q", targetAuth.Error(), expectedTopLevelMsg)
}
var targetAuthPtr *Error
if !As(wrapped, &targetAuthPtr) || targetAuthPtr.Name() != "AuthError" || targetAuthPtr.Code() != 401 {
t.Errorf("As(wrapped, &targetAuthPtr) failed, got name=%s, code=%d; want AuthError, 401", targetAuthPtr.Name(), targetAuthPtr.Code())
}
if !Is(wrapped, authErr) {
t.Errorf("Is(wrapped, authErr) failed, expected true")
}
if !errors.Is(wrapped, authErr) {
t.Errorf("stderrors.Is(wrapped, authErr) failed, expected true")
}
if !Is(wrapped, stdErr) {
t.Errorf("Is(wrapped, stdErr) failed, expected true")
}
if !errors.Is(wrapped, stdErr) {
t.Errorf("stderrors.Is(wrapped, stdErr) failed, expected true")
}
chain := UnwrapAll(wrapped)
if len(chain) != 4 {
t.Errorf("UnwrapAll(wrapped) length = %d, want 4", len(chain))
}
expected := []string{
"request failed",
"AuthError",
"storage failed",
"file not found",
}
for i, err := range chain {
if err.Error() != expected[i] {
t.Errorf("UnwrapAll[%d] = %v, want %v", i, err.Error(), expected[i])
}
}
}
// TestErrorUnwrapAllMessageIsolation ensures UnwrapAll preserves individual error messages.
func TestErrorUnwrapAllMessageIsolation(t *testing.T) {
inner := New("inner")
middle := New("middle").Wrap(inner)
outer := New("outer").Wrap(middle)
chain := UnwrapAll(outer)
if chain[0].Error() != "outer" {
t.Errorf("Expected 'outer', got %q", chain[0].Error())
}
if chain[1].Error() != "middle" {
t.Errorf("Expected 'middle', got %q", chain[1].Error())
}
if chain[2].Error() != "inner" {
t.Errorf("Expected 'inner', got %q", chain[2].Error())
}
}
// TestErrorIsEmpty verifies IsEmpty behavior for various error states, including
// nil, empty messages, and errors with causes or templates.
func TestErrorIsEmpty(t *testing.T) {
tests := []struct {
name string
err *Error
expected bool
}{
{"nil error", nil, true},
{"empty error", New(""), true},
{"named empty", Named(""), true},
{"with empty template", New("").WithTemplate(""), true},
{"with message", New("test"), false},
{"with name", Named("test"), false},
{"with template", New("").WithTemplate("template"), false},
{"with cause", New("").Wrap(New("cause")), false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.err != nil {
defer tt.err.Free()
}
if got := tt.err.IsEmpty(); got != tt.expected {
t.Errorf("IsEmpty() = %v, want %v", got, tt.expected)
}
})
}
}
// TestErrorIsNull verifies IsNull behavior for null and non-null errors, including
// SQL null values in context or causes.
func TestErrorIsNull(t *testing.T) {
nullString := sql.NullString{Valid: false}
validString := sql.NullString{String: "test", Valid: true}
tests := []struct {
name string
err *Error
expected bool
}{
{"nil error", nil, true},
{"empty error", New(""), false},
{"with NULL context", New("").With("data", nullString), true},
{"with valid context", New("").With("data", validString), false},
{"with NULL cause", New("").Wrap(New("NULL value").With("data", nullString)), true},
{"with valid cause", New("").Wrap(New("valid value").With("data", validString)), false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.err != nil {
defer tt.err.Free()
}
if got := tt.err.IsNull(); got != tt.expected {
t.Errorf("IsNull() = %v, want %v", got, tt.expected)
}
})
}
}
// TestErrorFromContext ensures FromContext enhances errors with context information,
// such as deadlines and cancellations.
func TestErrorFromContext(t *testing.T) {
// Test nil error.
t.Run("nil error returns nil", func(t *testing.T) {
ctx := context.Background()
if FromContext(ctx, nil) != nil {
t.Error("Expected nil for nil input error")
}
})
// Test deadline exceeded.
t.Run("deadline exceeded", func(t *testing.T) {
deadline := time.Now().Add(-1 * time.Hour)
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
err := errors.New("operation failed")
cerr := FromContext(ctx, err)
if !IsTimeout(cerr) {
t.Error("Expected timeout error")
}
if !HasContextKey(cerr, "deadline") {
t.Error("Expected deadline in context")
}
})
// Test cancelled context.
t.Run("cancelled context", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := errors.New("operation failed")
cerr := FromContext(ctx, err)
if !HasContextKey(cerr, "cancelled") {
t.Error("Expected cancelled flag")
}
})
}
// TestContextStorage verifies the smallContext optimization and its expansion
// to a full map, including thread-safety under concurrent access.
func TestContextStorage(t *testing.T) {
// Test smallContext for first 4 items.
t.Run("stores first 4 items in smallContext", func(t *testing.T) {
Configure(Config{DisablePooling: true})
err := New("test")
err.With("a", 1)
err.With("b", 2)
err.With("c", 3)
err.With("d", 4)
if err.smallCount != 4 {
t.Errorf("expected smallCount=4, got %d", err.smallCount)
}
if err.context != nil {
t.Error("expected context map to be nil")
}
})
// Test expansion to map on 5th item.
t.Run("switches to map on 5th item", func(t *testing.T) {
Configure(Config{DisablePooling: true})
err := New("test")
err.With("a", 1)
err.With("b", 2)
err.With("c", 3)
err.With("d", 4)
err.With("e", 5)
if err.context == nil {
t.Error("expected context map to be initialized")
}
if len(err.context) != 5 {
t.Errorf("expected 5 items in map, got %d", len(err.context))
}
})
// Test preservation of all context items.
t.Run("preserves all context items", func(t *testing.T) {
err := New("test")
items := []struct {
k string
v interface{}
}{
{"a", 1}, {"b", 2}, {"c", 3},
{"d", 4}, {"e", 5}, {"f", 6},
}
for _, item := range items {
err.With(item.k, item.v)
}
ctx := err.Context()
if len(ctx) != len(items) {
t.Errorf("expected %d items, got %d", len(items), len(ctx))
}
for _, item := range items {
if val, ok := ctx[item.k]; !ok || val != item.v {
t.Errorf("missing item %s in context", item.k)
}
}
})
// Test concurrent access safety.
t.Run("concurrent access", func(t *testing.T) {
Configure(Config{DisablePooling: true})
err := New("test")
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
err.With("a", 1)
err.With("b", 2)
err.With("c", 3)
}()
go func() {
defer wg.Done()
err.With("d", 4)
err.With("e", 5)
err.With("f", 6)
}()
wg.Wait()
ctx := err.Context()
if len(ctx) != 6 {
t.Errorf("expected 6 items, got %d", len(ctx))
}
})
}
// TestNewf verifies Newf behavior, including %w wrapping, formatting, and error cases.
// TestNewf verifies Newf behavior, including %w wrapping, formatting, and error cases.
// It now expects the string output for %w cases to match fmt.Errorf.
func TestNewf(t *testing.T) {
// Reusable error instances for testing %w
stdErrorInstance := errors.New("std error")
customErrorInstance := New("custom error") // Assuming this exists in your tests
firstErrorInstance := New("first")
secondErrorInstance := New("second")
tests := []struct {
name string
format string
args []interface{}
wantFinalMsg string // EXPECTATION UPDATED TO MATCH fmt.Errorf
wantInternalMsg string // This field might be less relevant now, maybe remove? Kept for reference.
wantCause error
wantErrFormat bool // Indicates if Newf itself should return a format error message
}{
// Basic formatting (no change needed)
{
name: "simple string",
format: "simple %s",
args: []interface{}{"test"},
wantFinalMsg: "simple test",
wantInternalMsg: "simple test", // Stays same as FinalMsg when no %w
},
{
name: "complex format without %w",
format: "code=%d msg=%s",
args: []interface{}{123, "hello"},
wantFinalMsg: "code=123 msg=hello",
wantInternalMsg: "code=123 msg=hello",
},
{
name: "empty format no args",
format: "",
args: []interface{}{},
wantFinalMsg: "",
wantInternalMsg: "",
},
// %w wrapping cases (EXPECTATIONS UPDATED)
{
name: "wrap standard error",
format: "prefix %w",
args: []interface{}{stdErrorInstance},
wantFinalMsg: "prefix std error", // Matches fmt.Errorf output
wantInternalMsg: "prefix std error", // Now wantInternalMsg matches FinalMsg for %w
wantCause: stdErrorInstance,
},
{
name: "wrap custom error",
format: "prefix %w",
args: []interface{}{customErrorInstance},
wantFinalMsg: "prefix custom error", // Matches fmt.Errorf output
wantInternalMsg: "prefix custom error",
wantCause: customErrorInstance,
},
{
name: "%w at start",
format: "%w suffix",
args: []interface{}{stdErrorInstance},
wantFinalMsg: "std error suffix", // Matches fmt.Errorf output
wantInternalMsg: "std error suffix",
wantCause: stdErrorInstance,
},
{
name: "%w with flags (flags ignored by %w)",
format: "prefix %+w suffix", // fmt.Errorf ignores flags like '+' for %w
args: []interface{}{stdErrorInstance},
wantFinalMsg: "prefix std error suffix", // Matches fmt.Errorf output
wantInternalMsg: "prefix std error suffix",
wantCause: stdErrorInstance,
},
{
name: "no space around %w",
format: "prefix%wsuffix",
args: []interface{}{stdErrorInstance},
wantFinalMsg: "prefixstd errorsuffix", // Matches fmt.Errorf output
wantInternalMsg: "prefixstd errorsuffix",
wantCause: stdErrorInstance,