-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrific_test.go
More file actions
1887 lines (1555 loc) · 46.2 KB
/
errific_test.go
File metadata and controls
1887 lines (1555 loc) · 46.2 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 errific
import (
"encoding/json"
"errors"
"io"
"strings"
"sync"
"testing"
"time"
)
func TestErrNew(t *testing.T) {
Configure(OutputPretty)
t.Run("basic error", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New()
if err.Error() == "" {
t.Error("expected non-empty error message")
}
if !strings.Contains(err.Error(), "test error") {
t.Errorf("expected error message to contain 'test error', got: %s", err.Error())
}
if !errors.Is(err, ErrTest) {
t.Error("expected errors.Is to match ErrTest")
}
})
t.Run("with wrapped error", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New(io.EOF)
if !errors.Is(err, ErrTest) {
t.Error("expected errors.Is to match ErrTest")
}
if !errors.Is(err, io.EOF) {
t.Error("expected errors.Is to match io.EOF")
}
if !strings.Contains(err.Error(), "EOF") {
t.Errorf("expected error message to contain 'EOF', got: %s", err.Error())
}
})
t.Run("with multiple wrapped errors", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New(io.EOF, io.ErrUnexpectedEOF)
if !errors.Is(err, io.EOF) {
t.Error("expected errors.Is to match io.EOF")
}
if !errors.Is(err, io.ErrUnexpectedEOF) {
t.Error("expected errors.Is to match io.ErrUnexpectedEOF")
}
})
}
func TestErrErrorf(t *testing.T) {
Configure(OutputPretty)
t.Run("formatted error", func(t *testing.T) {
var ErrTest Err = "test error: %s %d"
err := ErrTest.Errorf("hello", 42)
if !strings.Contains(err.Error(), "hello") {
t.Errorf("expected error message to contain 'hello', got: %s", err.Error())
}
if !strings.Contains(err.Error(), "42") {
t.Errorf("expected error message to contain '42', got: %s", err.Error())
}
if !errors.Is(err, ErrTest) {
t.Error("expected errors.Is to match ErrTest")
}
})
t.Run("with wrapped error", func(t *testing.T) {
var ErrTest Err = "test error: %w"
err := ErrTest.Errorf(io.EOF)
if !errors.Is(err, io.EOF) {
t.Error("expected errors.Is to match io.EOF")
}
})
}
func TestErrWithf(t *testing.T) {
Configure(OutputPretty)
t.Run("basic withf", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.Withf("detail: %s", "info")
if !strings.Contains(err.Error(), "test error") {
t.Errorf("expected error message to contain 'test error', got: %s", err.Error())
}
if !strings.Contains(err.Error(), "detail: info") {
t.Errorf("expected error message to contain 'detail: info', got: %s", err.Error())
}
})
t.Run("chained withf", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.Withf("first %d", 1).Withf("second %d", 2)
msg := err.Error()
if !strings.Contains(msg, "first 1") {
t.Errorf("expected error message to contain 'first 1', got: %s", msg)
}
if !strings.Contains(msg, "second 2") {
t.Errorf("expected error message to contain 'second 2', got: %s", msg)
}
})
}
func TestErrWrapf(t *testing.T) {
Configure(OutputPretty)
t.Run("basic wrapf", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.Wrapf("wrapped: %w", io.EOF)
if !errors.Is(err, io.EOF) {
t.Error("expected errors.Is to match io.EOF")
}
if !strings.Contains(err.Error(), "wrapped") {
t.Errorf("expected error message to contain 'wrapped', got: %s", err.Error())
}
})
t.Run("chained wrapf", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.Wrapf("first %d", 1).Wrapf("second %d", 2)
msg := err.Error()
if !strings.Contains(msg, "first 1") {
t.Errorf("expected error message to contain 'first 1', got: %s", msg)
}
if !strings.Contains(msg, "second 2") {
t.Errorf("expected error message to contain 'second 2', got: %s", msg)
}
})
}
func TestErrificJoin(t *testing.T) {
Configure(OutputPretty)
var ErrTest Err = "test error"
err := ErrTest.New().Join(io.EOF, io.ErrUnexpectedEOF)
if !errors.Is(err, io.EOF) {
t.Error("expected errors.Is to match io.EOF")
}
if !errors.Is(err, io.ErrUnexpectedEOF) {
t.Error("expected errors.Is to match io.ErrUnexpectedEOF")
}
}
func TestConfigureCallerOption(t *testing.T) {
t.Run("suffix", func(t *testing.T) {
Configure(OutputPretty, Suffix)
var ErrTest Err = "test"
err := ErrTest.New()
msg := err.Error()
// Should end with [location]
if !strings.Contains(msg, "[") || !strings.HasSuffix(msg, "]") {
t.Errorf("expected suffix format, got: %s", msg)
}
if strings.HasPrefix(msg, "[") {
t.Errorf("expected suffix not prefix, got: %s", msg)
}
})
t.Run("prefix", func(t *testing.T) {
Configure(OutputPretty, Prefix)
var ErrTest Err = "test"
err := ErrTest.New()
msg := err.Error()
// Should start with [location]
if !strings.HasPrefix(msg, "[") {
t.Errorf("expected prefix format, got: %s", msg)
}
})
t.Run("disabled", func(t *testing.T) {
Configure(OutputPretty, Disabled)
var ErrTest Err = "test"
err := ErrTest.New()
msg := err.Error()
// Should not contain brackets
if strings.Contains(msg, "[") || strings.Contains(msg, "]") {
t.Errorf("expected no caller info, got: %s", msg)
}
})
}
func TestConfigureLayoutOption(t *testing.T) {
t.Run("newline", func(t *testing.T) {
Configure(OutputPretty, Newline)
var ErrTest Err = "test"
err := ErrTest.New(io.EOF, io.ErrUnexpectedEOF)
msg := err.Error()
// Should contain newlines
if !strings.Contains(msg, "\n") {
t.Errorf("expected newline layout, got: %s", msg)
}
})
t.Run("inline", func(t *testing.T) {
Configure(OutputPretty, Inline)
var ErrTest Err = "test"
err := ErrTest.New(io.EOF, io.ErrUnexpectedEOF)
msg := err.Error()
// Should contain ↩ symbol
if !strings.Contains(msg, "↩") {
t.Errorf("expected inline layout with ↩, got: %s", msg)
}
// Should not contain newlines (except maybe in caller/stack)
lines := strings.Split(msg, "\n")
if len(lines) > 2 { // Allow for potential stack traces
t.Errorf("expected inline layout with minimal newlines, got: %s", msg)
}
})
}
func TestConfigureWithStack(t *testing.T) {
t.Run("with stack", func(t *testing.T) {
Configure(WithStack)
var ErrTest Err = "test"
// Create error in a helper function to ensure stack has frames
err := helperFunctionForStack(ErrTest)
msg := err.Error()
// The error message should still be valid
if !strings.Contains(msg, "test") {
t.Errorf("expected error message to contain 'test', got: %s", msg)
}
// WithStack configuration should not cause errors
if msg == "" {
t.Error("expected non-empty error message")
}
})
t.Run("without stack", func(t *testing.T) {
Configure(OutputPretty) // Default is without stack
var ErrTest Err = "test"
err := ErrTest.New()
msg := err.Error()
// Should be a simple error message
if msg == "" {
t.Error("expected non-empty error message")
}
if !strings.Contains(msg, "test") {
t.Errorf("expected error message to contain 'test', got: %s", msg)
}
})
}
func TestWithStackContents(t *testing.T) {
Configure(OutputPretty, WithStack)
t.Run("stack contains expected file and function", func(t *testing.T) {
var ErrTest Err = "test error"
err := helperFunctionForStackTrace(ErrTest)
msg := err.Error()
// Should contain the helper function name
if !strings.Contains(msg, "helperFunctionForStackTrace") {
t.Errorf("expected stack to contain 'helperFunctionForStackTrace', got: %s", msg)
}
// Should contain the test file name
if !strings.Contains(msg, "errific_test.go") {
t.Errorf("expected stack to contain 'errific_test.go', got: %s", msg)
}
// Should NOT contain _testmain.go (it's filtered out)
if strings.Contains(msg, "_testmain.go") {
t.Errorf("expected stack to NOT contain '_testmain.go', got: %s", msg)
}
})
t.Run("stack with bubbled errors", func(t *testing.T) {
var ErrRoot Err = "root error"
var ErrTop Err = "top error"
err1 := helperCreateRootError(ErrRoot)
err2 := helperWrapError(ErrTop, err1)
msg := err2.Error()
// Should contain both helper function names
if !strings.Contains(msg, "helperCreateRootError") {
t.Errorf("expected stack to contain 'helperCreateRootError', got: %s", msg)
}
if !strings.Contains(msg, "helperWrapError") {
t.Errorf("expected stack to contain 'helperWrapError', got: %s", msg)
}
// Should contain file name
if !strings.Contains(msg, "errific_test.go") {
t.Errorf("expected stack to contain 'errific_test.go', got: %s", msg)
}
// Should NOT contain _testmain.go
if strings.Contains(msg, "_testmain.go") {
t.Errorf("expected stack to NOT contain '_testmain.go', got: %s", msg)
}
// Should contain both error messages
if !strings.Contains(msg, "root error") {
t.Errorf("expected message to contain 'root error', got: %s", msg)
}
if !strings.Contains(msg, "top error") {
t.Errorf("expected message to contain 'top error', got: %s", msg)
}
})
t.Run("stack trace format", func(t *testing.T) {
var ErrTest Err = "format test"
err := helperFunctionForStackTrace(ErrTest)
msg := err.Error()
// Stack should be indented with spaces
if !strings.Contains(msg, "\n ") {
t.Errorf("expected stack frames to be indented, got: %s", msg)
}
// Stack should contain colon separator (file:line.function format)
lines := strings.Split(msg, "\n")
foundStackLine := false
for _, line := range lines {
trimmed := strings.TrimSpace(line)
// Look for lines containing errific_test.go with line number
if strings.Contains(trimmed, "errific_test.go:") && strings.Contains(trimmed, ".") {
foundStackLine = true
// Verify format: file:line.function (e.g., "errific/errific_test.go:350.func3")
parts := strings.Split(trimmed, ":")
if len(parts) < 2 {
t.Errorf("expected stack line to have file:line format, got: %s", line)
}
}
}
if !foundStackLine {
t.Errorf("expected to find stack trace line with errific_test.go, got: %s", msg)
}
})
}
// Helper functions for stack trace testing
func helperFunctionForStackTrace(e Err) errific {
return e.New()
}
func helperCreateRootError(e Err) errific {
return e.New(io.EOF)
}
func helperWrapError(e Err, wrapped error) errific {
return e.New(wrapped)
}
// Helper function to create errors with a deeper stack
func helperFunctionForStack(e Err) errific {
return e.New(io.EOF)
}
func TestConfigureTrimPrefixes(t *testing.T) {
Configure(TrimPrefixes("/usr/local/go/", "/home/user/"))
var ErrTest Err = "test"
err := ErrTest.New()
msg := err.Error()
// Should not contain the trimmed prefixes
if strings.Contains(msg, "/usr/local/go/") {
t.Errorf("expected trimmed prefix, got: %s", msg)
}
if strings.Contains(msg, "/home/user/") {
t.Errorf("expected trimmed prefix, got: %s", msg)
}
}
func TestConfigureTrimCWD(t *testing.T) {
Configure(TrimCWD)
var ErrTest Err = "test"
err := ErrTest.New()
msg := err.Error()
// Should have relative paths
if !strings.Contains(msg, "errific") {
t.Errorf("expected relative path, got: %s", msg)
}
}
func TestConcurrentConfigure(t *testing.T) {
// Test that concurrent Configure calls don't cause races
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
switch n % 4 {
case 0:
Configure(Suffix)
case 1:
Configure(Prefix)
case 2:
Configure(Disabled)
case 3:
Configure(Newline)
}
}(i)
}
wg.Wait()
}
func TestConcurrentErrorCreation(t *testing.T) {
Configure(OutputPretty)
var ErrTest Err = "test"
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
err := ErrTest.New(io.EOF)
if !errors.Is(err, ErrTest) {
t.Error("expected errors.Is to match ErrTest")
}
_ = err.Error()
}()
}
wg.Wait()
}
func TestUnwrap(t *testing.T) {
Configure(OutputPretty)
var (
Err1 Err = "error 1"
Err2 Err = "error 2"
)
err1 := Err1.New(io.EOF)
err2 := Err2.New(err1)
// Test that unwrap chain works
if !errors.Is(err2, Err2) {
t.Error("expected errors.Is to match Err2")
}
if !errors.Is(err2, Err1) {
t.Error("expected errors.Is to match Err1")
}
if !errors.Is(err2, io.EOF) {
t.Error("expected errors.Is to match io.EOF")
}
}
func TestCircularReferenceFixed(t *testing.T) {
Configure(OutputPretty)
var ErrTest Err = "test"
err := ErrTest.Withf("detail %d", 1)
// This should not cause infinite loop
msg := err.Error()
if msg == "" {
t.Error("expected non-empty error message")
}
// Make sure the error chain is valid
// errific.Unwrap() returns []error, so we can't use errors.Unwrap
// Instead, verify that errors.Is works properly
if !errors.Is(err, ErrTest) {
t.Error("expected errors.Is to match ErrTest")
}
}
func BenchmarkErrNew(b *testing.B) {
Configure(OutputPretty)
var ErrTest Err = "test error"
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = ErrTest.New()
}
}
func BenchmarkErrNewWithWrap(b *testing.B) {
Configure(OutputPretty)
var ErrTest Err = "test error"
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = ErrTest.New(io.EOF)
}
}
func BenchmarkErrError(b *testing.B) {
Configure(OutputPretty)
var ErrTest Err = "test error"
err := ErrTest.New(io.EOF)
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = err.Error()
}
}
func BenchmarkErrWithStack(b *testing.B) {
Configure(WithStack)
var ErrTest Err = "test error"
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = ErrTest.New()
}
}
// ============================================================================
// Phase 1 Feature Tests: Context, Codes, Categories, Retry, JSON
// ============================================================================
func TestWithContext(t *testing.T) {
Configure(OutputPretty)
t.Run("basic context", func(t *testing.T) {
var ErrTest Err = "test error"
ctx := Context{
"query": "SELECT * FROM users",
"duration_ms": 1500,
}
err := ErrTest.New().WithContext(ctx)
extractedCtx := GetContext(err)
if extractedCtx == nil {
t.Fatal("expected non-nil context")
}
if extractedCtx["query"] != "SELECT * FROM users" {
t.Errorf("expected query in context, got: %v", extractedCtx)
}
if extractedCtx["duration_ms"] != 1500 {
t.Errorf("expected duration_ms in context, got: %v", extractedCtx)
}
})
t.Run("chained context", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New().
WithContext(Context{"key1": "value1"}).
WithContext(Context{"key2": "value2"})
ctx := GetContext(err)
if ctx["key1"] != "value1" {
t.Error("expected key1 in context")
}
if ctx["key2"] != "value2" {
t.Error("expected key2 in context")
}
})
t.Run("nil context on non-errific error", func(t *testing.T) {
err := errors.New("standard error")
ctx := GetContext(err)
if ctx != nil {
t.Error("expected nil context for standard error")
}
})
}
func TestWithCode(t *testing.T) {
Configure(OutputPretty)
t.Run("basic code", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New().WithCode("DB_TIMEOUT")
code := GetCode(err)
if code != "DB_TIMEOUT" {
t.Errorf("expected code 'DB_TIMEOUT', got: %s", code)
}
})
t.Run("empty code on non-errific error", func(t *testing.T) {
err := errors.New("standard error")
code := GetCode(err)
if code != "" {
t.Error("expected empty code for standard error")
}
})
}
func TestWithCategory(t *testing.T) {
Configure(OutputPretty)
t.Run("basic category", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New().WithCategory(CategoryNetwork)
category := GetCategory(err)
if category != CategoryNetwork {
t.Errorf("expected category 'network', got: %s", category)
}
})
t.Run("all categories", func(t *testing.T) {
categories := []Category{
CategoryClient,
CategoryServer,
CategoryNetwork,
CategoryValidation,
CategoryNotFound,
CategoryUnauthorized,
CategoryTimeout,
}
for _, cat := range categories {
var ErrTest Err = "test"
err := ErrTest.New().WithCategory(cat)
if GetCategory(err) != cat {
t.Errorf("expected category %s, got: %s", cat, GetCategory(err))
}
}
})
}
func TestRetryMetadata(t *testing.T) {
Configure(OutputPretty)
t.Run("retryable", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New().WithRetryable(true)
if !IsRetryable(err) {
t.Error("expected error to be retryable")
}
})
t.Run("not retryable", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New().WithRetryable(false)
if IsRetryable(err) {
t.Error("expected error to not be retryable")
}
})
t.Run("retry after", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New().WithRetryAfter(5 * time.Second)
after := GetRetryAfter(err)
if after != 5*time.Second {
t.Errorf("expected retry after 5s, got: %v", after)
}
})
t.Run("max retries", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New().WithMaxRetries(3)
max := GetMaxRetries(err)
if max != 3 {
t.Errorf("expected max retries 3, got: %d", max)
}
})
t.Run("complete retry configuration", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New().
WithRetryable(true).
WithRetryAfter(10 * time.Second).
WithMaxRetries(5)
if !IsRetryable(err) {
t.Error("expected retryable")
}
if GetRetryAfter(err) != 10*time.Second {
t.Error("expected retry after 10s")
}
if GetMaxRetries(err) != 5 {
t.Error("expected max retries 5")
}
})
}
func TestWithHTTPStatus(t *testing.T) {
Configure(OutputPretty)
t.Run("basic http status", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New().WithHTTPStatus(503)
status := GetHTTPStatus(err)
if status != 503 {
t.Errorf("expected status 503, got: %d", status)
}
})
t.Run("common http statuses", func(t *testing.T) {
testCases := []struct {
status int
desc string
}{
{400, "Bad Request"},
{401, "Unauthorized"},
{403, "Forbidden"},
{404, "Not Found"},
{500, "Internal Server Error"},
{503, "Service Unavailable"},
}
for _, tc := range testCases {
ErrTest := Err(tc.desc)
err := ErrTest.New().WithHTTPStatus(tc.status)
if GetHTTPStatus(err) != tc.status {
t.Errorf("expected status %d for %s", tc.status, tc.desc)
}
}
})
}
func TestJSONSerialization(t *testing.T) {
Configure(OutputPretty)
t.Run("basic json", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New()
jsonBytes, jsonErr := json.Marshal(err)
if jsonErr != nil {
t.Fatalf("failed to marshal error: %v", jsonErr)
}
var result map[string]interface{}
if jsonErr := json.Unmarshal(jsonBytes, &result); jsonErr != nil {
t.Fatalf("failed to unmarshal JSON: %v", jsonErr)
}
if result["error"] != "test error" {
t.Errorf("expected error message in JSON, got: %v", result)
}
})
t.Run("json with all metadata", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New(io.EOF).
WithCode("TEST_001").
WithCategory(CategoryServer).
WithContext(Context{"key": "value"}).
WithRetryable(true).
WithRetryAfter(5 * time.Second).
WithMaxRetries(3).
WithHTTPStatus(503)
jsonBytes, jsonErr := json.Marshal(err)
if jsonErr != nil {
t.Fatalf("failed to marshal error: %v", jsonErr)
}
var result map[string]interface{}
if jsonErr := json.Unmarshal(jsonBytes, &result); jsonErr != nil {
t.Fatalf("failed to unmarshal JSON: %v", jsonErr)
}
// Check all fields
if result["code"] != "TEST_001" {
t.Errorf("expected code in JSON, got: %v", result["code"])
}
if result["category"] != "server" {
t.Errorf("expected category in JSON, got: %v", result["category"])
}
if result["retryable"] != true {
t.Errorf("expected retryable in JSON, got: %v", result["retryable"])
}
if result["max_retries"] != float64(3) {
t.Errorf("expected max_retries in JSON, got: %v", result["max_retries"])
}
if result["http_status"] != float64(503) {
t.Errorf("expected http_status in JSON, got: %v", result["http_status"])
}
// Check context
ctx, ok := result["context"].(map[string]interface{})
if !ok || ctx["key"] != "value" {
t.Errorf("expected context in JSON, got: %v", result["context"])
}
// Check wrapped errors
wrapped, ok := result["wrapped"].([]interface{})
if !ok || len(wrapped) == 0 {
t.Errorf("expected wrapped errors in JSON, got: %v", result["wrapped"])
}
})
t.Run("json pretty print", func(t *testing.T) {
var ErrTest Err = "test error"
err := ErrTest.New().
WithCode("ERR_001").
WithContext(Context{"request_id": "abc123"})
jsonBytes, _ := json.MarshalIndent(err, "", " ")
jsonStr := string(jsonBytes)
if !strings.Contains(jsonStr, "ERR_001") {
t.Error("expected code in pretty JSON")
}
if !strings.Contains(jsonStr, "abc123") {
t.Error("expected request_id in pretty JSON")
}
})
}
func TestAIAgentScenario(t *testing.T) {
Configure(OutputPretty)
t.Run("database timeout scenario", func(t *testing.T) {
// Simulate a database timeout error with full AI-agent metadata
var ErrDBTimeout Err = "database query timeout"
err := ErrDBTimeout.New(io.EOF).
WithCode("DB_TIMEOUT_001").
WithCategory(CategoryNetwork).
WithContext(Context{
"query": "SELECT * FROM large_table",
"duration_ms": 30000,
"table": "large_table",
}).
WithRetryable(true).
WithRetryAfter(5 * time.Second).
WithMaxRetries(3).
WithHTTPStatus(503)
// AI agent can now make decisions
if IsRetryable(err) {
retryAfter := GetRetryAfter(err)
maxRetries := GetMaxRetries(err)
// AI knows to retry after 5 seconds, max 3 times
if retryAfter != 5*time.Second {
t.Error("AI should know to wait 5 seconds")
}
if maxRetries != 3 {
t.Error("AI should know max 3 retries")
}
} else {
t.Error("AI should know this is retryable")
}
// AI can extract context for logging
ctx := GetContext(err)
if ctx["table"] != "large_table" {
t.Error("AI should know which table failed")
}
// AI can respond with correct HTTP status
status := GetHTTPStatus(err)
if status != 503 {
t.Error("AI should return 503 Service Unavailable")
}
// AI can serialize for monitoring
jsonBytes, _ := json.Marshal(err)
if len(jsonBytes) == 0 {
t.Error("AI should be able to serialize error")
}
})
t.Run("validation error scenario", func(t *testing.T) {
var ErrValidation Err = "validation failed"
err := ErrValidation.New().
WithCode("VAL_EMAIL_INVALID").
WithCategory(CategoryValidation).
WithContext(Context{
"field": "email",
"value": "invalid",
}).
WithRetryable(false).
WithHTTPStatus(400)
// AI knows not to retry validation errors
if IsRetryable(err) {
t.Error("AI should not retry validation errors")
}
// AI returns 400 Bad Request
if GetHTTPStatus(err) != 400 {
t.Error("AI should return 400 for validation")
}
// AI can tell user which field failed
ctx := GetContext(err)
if ctx["field"] != "email" {
t.Error("AI should know email field failed")
}
})
}
// Phase 2A: MCP & RAG Integration Tests
func TestPhase2A_CorrelationID(t *testing.T) {
Configure(OutputPretty)
var ErrTest Err = "test error"
t.Run("with correlation ID", func(t *testing.T) {
err := ErrTest.New().WithCorrelationID("corr-12345")
id := GetCorrelationID(err)
if id != "corr-12345" {
t.Errorf("expected correlation ID 'corr-12345', got '%s'", id)
}
})
t.Run("without correlation ID", func(t *testing.T) {
err := ErrTest.New()
id := GetCorrelationID(err)
if id != "" {
t.Errorf("expected empty correlation ID, got '%s'", id)
}
})
t.Run("nil error", func(t *testing.T) {
id := GetCorrelationID(nil)
if id != "" {
t.Errorf("expected empty correlation ID for nil, got '%s'", id)
}
})
}
func TestPhase2A_RequestID(t *testing.T) {
Configure(OutputPretty)
var ErrTest Err = "test error"
err := ErrTest.New().WithRequestID("req-67890")
id := GetRequestID(err)
if id != "req-67890" {
t.Errorf("expected request ID 'req-67890', got '%s'", id)
}
}
func TestPhase2A_UserID(t *testing.T) {
Configure(OutputPretty)
var ErrTest Err = "test error"
err := ErrTest.New().WithUserID("user-123")
id := GetUserID(err)