-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy patherrors_test.go
More file actions
1017 lines (947 loc) · 29.6 KB
/
errors_test.go
File metadata and controls
1017 lines (947 loc) · 29.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
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 twelvedata
import (
"errors"
"fmt"
"net/http"
"strings"
"testing"
"github.com/guregu/null/v6"
"github.com/soulgarden/twelvedata/response"
)
func TestNewHTTPError(t *testing.T) {
tests := []struct {
name string
statusCode int
body []byte
apiError *response.Error
wantType string
}{
{
name: "bad request with api error",
statusCode: http.StatusBadRequest,
body: []byte(`{"code":400,"message":"Invalid parameter","status":"error"}`),
apiError: &response.Error{
Code: null.IntFrom(400),
Message: "Invalid parameter",
Status: "error",
},
wantType: "*twelvedata.BadRequestError",
},
{
name: "unauthorized error",
statusCode: http.StatusUnauthorized,
body: []byte(`{"code":401,"message":"Invalid API key","status":"error"}`),
apiError: &response.Error{
Code: null.IntFrom(401),
Message: "Invalid API key",
Status: "error",
},
wantType: "*twelvedata.UnauthorizedError",
},
{
name: "not found error",
statusCode: http.StatusNotFound,
body: []byte(`Not Found`),
apiError: nil,
wantType: "*twelvedata.NotFoundError",
},
{
name: "rate limit error",
statusCode: http.StatusTooManyRequests,
body: []byte(`{"code":429,"message":"Rate limit exceeded","status":"error"}`),
apiError: &response.Error{
Code: null.IntFrom(429),
Message: "Rate limit exceeded",
Status: "error",
},
wantType: "*twelvedata.TooManyRequestsError",
},
{
name: "internal server error",
statusCode: http.StatusInternalServerError,
body: []byte(`Internal Server Error`),
apiError: nil,
wantType: "*twelvedata.InternalServerError",
},
{
name: "generic http error",
statusCode: http.StatusBadGateway,
body: []byte(`Bad Gateway`),
apiError: nil,
wantType: "*twelvedata.HTTPError",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := NewHTTPError(tt.statusCode, tt.body, "https://api.twelvedata.com/test", tt.apiError, nil)
// Check error type
gotType := getErrorType(err)
if gotType != tt.wantType {
t.Errorf("NewHTTPError() type = %v, want %v", gotType, tt.wantType)
}
// Check that error implements error interface
if err.Error() == "" {
t.Errorf("NewHTTPError() error message is empty")
}
})
}
}
func TestErrorTypeCheckers(t *testing.T) {
tests := []struct {
name string
err error
checkers map[string]func(error) bool
expected map[string]bool
}{
{
name: "bad request error",
err: NewHTTPError(http.StatusBadRequest, []byte(""), "", nil, nil),
checkers: map[string]func(error) bool{
"IsBadRequestError": IsBadRequestError,
"IsUnauthorizedError": IsUnauthorizedError,
"IsNotFoundError": IsNotFoundError,
"IsRateLimitError": IsRateLimitError,
"IsHTTPError": IsHTTPError,
},
expected: map[string]bool{
"IsBadRequestError": true,
"IsUnauthorizedError": false,
"IsNotFoundError": false,
"IsRateLimitError": false,
"IsHTTPError": true,
},
},
{
name: "unauthorized error",
err: NewHTTPError(http.StatusUnauthorized, []byte(""), "", nil, nil),
checkers: map[string]func(error) bool{
"IsBadRequestError": IsBadRequestError,
"IsUnauthorizedError": IsUnauthorizedError,
"IsNotFoundError": IsNotFoundError,
"IsRateLimitError": IsRateLimitError,
"IsHTTPError": IsHTTPError,
},
expected: map[string]bool{
"IsBadRequestError": false,
"IsUnauthorizedError": true,
"IsNotFoundError": false,
"IsRateLimitError": false,
"IsHTTPError": true,
},
},
{
name: "timeout error",
err: &TimeoutError{Message: "Request timeout"},
checkers: map[string]func(error) bool{
"IsTimeoutError": IsTimeoutError,
"IsNetworkError": IsNetworkError,
"IsHTTPError": IsHTTPError,
},
expected: map[string]bool{
"IsTimeoutError": true,
"IsNetworkError": false,
"IsHTTPError": false,
},
},
{
name: "network error",
err: &NetworkError{Message: "Connection refused", Cause: nil},
checkers: map[string]func(error) bool{
"IsTimeoutError": IsTimeoutError,
"IsNetworkError": IsNetworkError,
"IsHTTPError": IsHTTPError,
},
expected: map[string]bool{
"IsTimeoutError": false,
"IsNetworkError": true,
"IsHTTPError": false,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for checkerName, checker := range tt.checkers {
result := checker(tt.err)
expected := tt.expected[checkerName]
if result != expected {
t.Errorf("%s() = %v, want %v", checkerName, result, expected)
}
}
})
}
}
func TestErrorMessages(t *testing.T) {
tests := []struct {
name string
err error
contains string
}{
{
name: "bad request error with api error",
err: &BadRequestError{
HTTPError: HTTPError{StatusCode: 400, Message: "Bad Request"},
APIError: &response.Error{
Code: null.IntFrom(400),
Message: "Invalid parameter",
Status: "error",
},
},
contains: "HTTP 400 Bad Request: code: 400, message: Invalid parameter, status: error",
},
{
name: "unauthorized error without api error",
err: &UnauthorizedError{
HTTPError: HTTPError{StatusCode: 401, Message: "Unauthorized"},
APIError: nil,
},
contains: "HTTP 401 Unauthorized: Invalid API key or authentication failed",
},
{
name: "timeout error",
err: &TimeoutError{
Message: "Request timeout after 30 seconds",
},
contains: "Request Timeout: Request timeout after 30 seconds",
},
{
name: "network error with cause",
err: &NetworkError{
Message: "Connection failed",
Cause: http.ErrHandlerTimeout,
},
contains: "Network Error: Connection failed",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
errMsg := tt.err.Error()
if errMsg != tt.contains {
t.Errorf("Error() = %q, want %q", errMsg, tt.contains)
}
})
}
}
func TestNetworkErrorUnwrap(t *testing.T) {
originalErr := http.ErrHandlerTimeout
networkErr := &NetworkError{
Message: "Connection failed",
Cause: originalErr,
}
if unwrapped := networkErr.Unwrap(); !errors.Is(unwrapped, originalErr) {
t.Errorf("NetworkError.Unwrap() = %v, want %v", unwrapped, originalErr)
}
}
func TestWebSocketErrors(t *testing.T) {
tests := []struct {
name string
err error
checkers map[string]func(error) bool
expected map[string]bool
}{
{
name: "websocket connection error",
err: &WSConnectionError{
URL: "wss://ws.twelvedata.com/v1/quotes/price",
Message: "Failed to establish connection",
Cause: errors.New("connection refused"),
},
checkers: map[string]func(error) bool{
"IsWSConnectionError": IsWSConnectionError,
"IsWSMessageError": IsWSMessageError,
"IsWSError": IsWSError,
"IsHTTPError": IsHTTPError,
},
expected: map[string]bool{
"IsWSConnectionError": true,
"IsWSMessageError": false,
"IsWSError": true,
"IsHTTPError": false,
},
},
{
name: "websocket message error",
err: &WSMessageError{
Message: "Failed to write ping",
Data: []byte("ping data"),
Cause: errors.New("write timeout"),
},
checkers: map[string]func(error) bool{
"IsWSConnectionError": IsWSConnectionError,
"IsWSMessageError": IsWSMessageError,
"IsWSSubscriptionError": IsWSSubscriptionError,
"IsWSError": IsWSError,
},
expected: map[string]bool{
"IsWSConnectionError": false,
"IsWSMessageError": true,
"IsWSSubscriptionError": false,
"IsWSError": true,
},
},
{
name: "websocket subscription error",
err: &WSSubscriptionError{
Symbols: []string{"AAPL", "GOOGL"},
Message: "Subscription failed",
Cause: errors.New("invalid symbols"),
},
checkers: map[string]func(error) bool{
"IsWSSubscriptionError": IsWSSubscriptionError,
"IsWSError": IsWSError,
"IsNetworkError": IsNetworkError,
},
expected: map[string]bool{
"IsWSSubscriptionError": true,
"IsWSError": true,
"IsNetworkError": false,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for checkerName, checker := range tt.checkers {
result := checker(tt.err)
expected := tt.expected[checkerName]
if result != expected {
t.Errorf("%s() = %v, want %v for error: %v", checkerName, result, expected, tt.err)
}
}
// Test error message format
if tt.err.Error() == "" {
t.Errorf("Error message should not be empty")
}
// Test Unwrap functionality if applicable
if unwrapper, ok := tt.err.(interface{ Unwrap() error }); ok {
if unwrapper.Unwrap() == nil {
t.Errorf("Expected error to wrap another error, but Unwrap() returned nil")
}
}
})
}
}
func TestErrorContextAndURL(t *testing.T) {
testURL := "https://api.twelvedata.com/stocks?apikey=test"
tests := []struct {
name string
err error
expectsURL bool
expectedURL string
}{
{
name: "http error with url context",
err: NewHTTPError(http.StatusBadRequest, []byte("test"), testURL, nil, nil),
expectsURL: true,
expectedURL: testURL,
},
{
name: "websocket connection error with url",
err: &WSConnectionError{
URL: "wss://ws.twelvedata.com/v1/quotes/price",
Message: "Connection failed",
Cause: errors.New("network error"),
},
expectsURL: true,
expectedURL: "wss://ws.twelvedata.com/v1/quotes/price",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
errMsg := tt.err.Error()
if tt.expectsURL && !strings.Contains(errMsg, tt.expectedURL) {
t.Errorf("Expected error message to contain URL %q, got: %q", tt.expectedURL, errMsg)
}
})
}
}
func TestErrorChaining(t *testing.T) {
originalErr := errors.New("original network error")
networkErr := &NetworkError{
Message: "Connection failed",
Cause: originalErr,
}
wrappedErr := fmt.Errorf("service unavailable: %w", networkErr)
// Test that we can find the original error through the chain
if !errors.Is(wrappedErr, originalErr) {
t.Errorf("Expected wrapped error to contain original error")
}
// Test that our error checkers work with wrapped errors
if !IsNetworkError(wrappedErr) {
t.Errorf("Expected IsNetworkError to work with wrapped errors")
}
// Test unwrapping chain
var netErr *NetworkError
if !errors.As(wrappedErr, &netErr) {
t.Errorf("Expected errors.As to extract NetworkError from wrapped error")
}
if !errors.Is(netErr.Unwrap(), originalErr) {
t.Errorf("Expected NetworkError.Unwrap() to return original error")
}
}
func TestMalformedResponseHandling(t *testing.T) {
tests := []struct {
name string
statusCode int
body []byte
apiError *response.Error
url string
}{
{
name: "malformed json body",
statusCode: http.StatusBadRequest,
body: []byte("{invalid json"),
apiError: nil,
url: "https://api.twelvedata.com/test",
},
{
name: "empty body with error status",
statusCode: http.StatusInternalServerError,
body: []byte(""),
apiError: nil,
url: "https://api.twelvedata.com/test",
},
{
name: "non-json error response",
statusCode: http.StatusBadGateway,
body: []byte("Bad Gateway"),
apiError: nil,
url: "https://api.twelvedata.com/test",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := NewHTTPError(tt.statusCode, tt.body, tt.url, tt.apiError, nil)
if err == nil {
t.Errorf("Expected error, got nil")
return
}
if !IsHTTPError(err) {
t.Errorf("Expected IsHTTPError to return true")
}
errMsg := err.Error()
if errMsg == "" {
t.Errorf("Error message should not be empty")
}
// Verify URL is included in error message
if !strings.Contains(errMsg, tt.url) {
t.Errorf("Expected error message to contain URL %q, got: %q", tt.url, errMsg)
}
})
}
}
func TestDomainErrorParsing(t *testing.T) {
tests := []struct {
name string
apiError *response.Error
statusCode int
url string
expectedType string
expectedCheck func(error) bool
expectedMsg string
}{
{
name: "symbol not found error",
apiError: &response.Error{
Code: null.IntFrom(400),
Message: "**AAPL** not found: symbol may be delisted",
Status: "error",
},
statusCode: 400,
url: "https://api.twelvedata.com/stocks",
expectedType: "SymbolNotFoundError",
expectedCheck: IsSymbolNotFoundError,
expectedMsg: "Symbol Not Found: AAPL - **AAPL** not found: symbol may be delisted",
},
{
name: "new symbol not found error",
apiError: &response.Error{
Code: null.IntFrom(400),
Message: "**GOOGL** with specified criteria not found: check your parameters",
Status: "error",
},
statusCode: 400,
url: "https://api.twelvedata.com/stocks",
expectedType: "SymbolNotFoundError",
expectedCheck: IsSymbolNotFoundError,
expectedMsg: "Symbol Not Found: GOOGL - **GOOGL** with specified criteria not found: check your parameters",
},
{
name: "plan limitation error",
apiError: &response.Error{
Code: null.IntFrom(403),
Message: "Real-time data is not available with your plan",
Status: "error",
},
statusCode: 403,
url: "https://api.twelvedata.com/time_series",
expectedType: "PlanLimitationError",
expectedCheck: IsPlanLimitationError,
expectedMsg: "Plan Limitation: Real-time data is not available with your plan",
},
{
name: "demo API key limitation error",
apiError: &response.Error{
Code: null.IntFrom(403),
Message: "The 'demo' API key is only used for initial familiarity. To become a full user, you can request your own API key at https://twelvedata.com/pricing. It is absolutely free, and it's yours for a lifetime. It only takes 10 seconds to obtain your own API key!",
Status: "error",
},
statusCode: 403,
url: "https://api.twelvedata.com/dividends_calendar",
expectedType: "PlanLimitationError",
expectedCheck: IsPlanLimitationError,
expectedMsg: "Plan Limitation: The 'demo' API key is only used for initial familiarity. To become a full user, you can request your own API key at https://twelvedata.com/pricing. It is absolutely free, and it's yours for a lifetime. It only takes 10 seconds to obtain your own API key!",
},
{
name: "insufficient credits error",
apiError: &response.Error{
Code: null.IntFrom(402),
Message: "insufficient credits to complete this request",
Status: "error",
},
statusCode: 402,
url: "https://api.twelvedata.com/time_series",
expectedType: "InsufficientCreditsError",
expectedCheck: IsInsufficientCreditsError,
expectedMsg: "Insufficient Credits: insufficient credits to complete this request",
},
{
name: "invalid api key error",
apiError: &response.Error{
Code: null.IntFrom(401),
Message: "invalid api key provided",
Status: "error",
},
statusCode: 401,
url: "https://api.twelvedata.com/stocks",
expectedType: "APIKeyError",
expectedCheck: IsAPIKeyError,
expectedMsg: "API Key Error: Invalid API key provided",
},
{
name: "api key required error",
apiError: &response.Error{
Code: null.IntFrom(401),
Message: "api key is required for this endpoint",
Status: "error",
},
statusCode: 401,
url: "https://api.twelvedata.com/stocks",
expectedType: "APIKeyError",
expectedCheck: IsAPIKeyError,
expectedMsg: "API Key Error: API key is required",
},
{
name: "daily credit limit exhausted error (429 status)",
apiError: &response.Error{
Code: null.IntFrom(429),
Message: "You have run out of API credits for the day. 7662 API credits were used, with the current limit being 800. Wait for the next day or consider switching to a paid plan that will remove daily limits at https://twelvedata.com/pricing",
Status: "error",
},
statusCode: 429,
url: "https://api.twelvedata.com/usage",
expectedType: "InsufficientCreditsError",
expectedCheck: IsInsufficientCreditsError,
expectedMsg: "Insufficient Credits: You have run out of API credits for the day. 7662 API credits were used, with the current limit being 800. Wait for the next day or consider switching to a paid plan that will remove daily limits at https://twelvedata.com/pricing",
},
{
name: "daily credit limit exhausted error (200 status)",
apiError: &response.Error{
Code: null.IntFrom(429),
Message: "You have run out of API credits for the day. 5000 API credits were used, with the current limit being 800",
Status: "error",
},
statusCode: 200,
url: "https://api.twelvedata.com/usage",
expectedType: "InsufficientCreditsError",
expectedCheck: IsInsufficientCreditsError,
expectedMsg: "Insufficient Credits: You have run out of API credits for the day. 5000 API credits were used, with the current limit being 800",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ParseDomainError(tt.apiError, tt.statusCode, tt.url)
if err == nil {
t.Errorf("Expected domain error, got nil")
return
}
// Test error type checking
if !tt.expectedCheck(err) {
t.Errorf("Expected %s error checker to return true, got false", tt.expectedType)
}
// Test error message
if err.Error() != tt.expectedMsg {
t.Errorf("Expected error message %q, got %q", tt.expectedMsg, err.Error())
}
// Test that it's recognized as a domain error
if !IsDomainError(err) {
t.Errorf("Expected IsDomainError to return true")
}
// Test error unwrapping
if unwrapper, ok := err.(interface{ Unwrap() error }); ok {
if unwrapped := unwrapper.Unwrap(); unwrapped == nil {
t.Errorf("Expected error to wrap another error")
}
}
})
}
}
func TestDomainErrorCheckers(t *testing.T) {
tests := []struct {
name string
err error
checkers map[string]func(error) bool
expected map[string]bool
}{
{
name: "symbol not found error",
err: &SymbolNotFoundError{
Symbol: "AAPL",
Message: "Symbol not found",
},
checkers: map[string]func(error) bool{
"IsSymbolNotFoundError": IsSymbolNotFoundError,
"IsPlanLimitationError": IsPlanLimitationError,
"IsInsufficientCreditsError": IsInsufficientCreditsError,
"IsAPIKeyError": IsAPIKeyError,
"IsDomainError": IsDomainError,
},
expected: map[string]bool{
"IsSymbolNotFoundError": true,
"IsPlanLimitationError": false,
"IsInsufficientCreditsError": false,
"IsAPIKeyError": false,
"IsDomainError": true,
},
},
{
name: "plan limitation error",
err: &PlanLimitationError{
Feature: "Real-time data",
Plan: "basic",
Message: "Not available",
},
checkers: map[string]func(error) bool{
"IsSymbolNotFoundError": IsSymbolNotFoundError,
"IsPlanLimitationError": IsPlanLimitationError,
"IsInsufficientCreditsError": IsInsufficientCreditsError,
"IsDomainError": IsDomainError,
},
expected: map[string]bool{
"IsSymbolNotFoundError": false,
"IsPlanLimitationError": true,
"IsInsufficientCreditsError": false,
"IsDomainError": true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for checkerName, checker := range tt.checkers {
result := checker(tt.err)
expected := tt.expected[checkerName]
if result != expected {
t.Errorf("%s() = %v, want %v", checkerName, result, expected)
}
}
})
}
}
func TestErrorMessageExtraction(t *testing.T) {
tests := []struct {
name string
message string
extractor func(string) string
expected string
}{
{
name: "extract symbol from standard message",
message: "**AAPL** not found: symbol may be delisted",
extractor: extractSymbolFromMessage,
expected: "AAPL",
},
{
name: "extract symbol from criteria message",
message: "**GOOGL** with specified criteria not found",
extractor: extractSymbolFromMessage,
expected: "GOOGL",
},
{
name: "extract symbol - no symbol found",
message: "Invalid request parameters",
extractor: extractSymbolFromMessage,
expected: "",
},
{
name: "extract feature from plan message",
message: "Real-time data is not available with your plan",
extractor: extractFeatureFromMessage,
expected: "Real-time data",
},
{
name: "extract feature with prefix",
message: "The advanced analytics is not available with your plan",
extractor: extractFeatureFromMessage,
expected: "advanced analytics",
},
{
name: "extract feature - no feature found",
message: "Some other error message",
extractor: extractFeatureFromMessage,
expected: "",
},
{
name: "extract feature from exclusive message",
message: "/dividends_calendar is available exclusively with grow or pro or ultra or enterprise plans",
extractor: extractFeatureFromExclusiveMessage,
expected: "dividends calendar",
},
{
name: "extract feature from exclusive message with path",
message: "/api/v1/premium_data is available exclusively with pro plans",
extractor: extractFeatureFromExclusiveMessage,
expected: "api/v1/premium data",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := tt.extractor(tt.message)
if result != tt.expected {
t.Errorf("Expected %q, got %q", tt.expected, result)
}
})
}
}
func TestWrappedDomainErrors(t *testing.T) {
originalSymbolErr := &SymbolNotFoundError{
Symbol: "TSLA",
Message: "Symbol not found",
}
wrappedErr := fmt.Errorf("request failed: %w", originalSymbolErr)
// Test that domain error checkers work with wrapped errors
if !IsSymbolNotFoundError(wrappedErr) {
t.Errorf("Expected IsSymbolNotFoundError to work with wrapped errors")
}
if !IsDomainError(wrappedErr) {
t.Errorf("Expected IsDomainError to work with wrapped errors")
}
// Test that we can extract the original error
var symbolErr *SymbolNotFoundError
if !errors.As(wrappedErr, &symbolErr) {
t.Errorf("Expected errors.As to extract SymbolNotFoundError")
}
if symbolErr.Symbol != "TSLA" {
t.Errorf("Expected symbol TSLA, got %s", symbolErr.Symbol)
}
}
func TestWrappedErrorHandling(t *testing.T) {
tests := []struct {
name string
err error
checkers map[string]func(error) bool
expected map[string]bool
}{
{
name: "wrapped bad request error",
err: fmt.Errorf("wrapper: %w", NewHTTPError(http.StatusBadRequest, []byte(""), "", nil, nil)),
checkers: map[string]func(error) bool{
"IsBadRequestError": IsBadRequestError,
"IsHTTPError": IsHTTPError,
"IsTimeoutError": IsTimeoutError,
},
expected: map[string]bool{
"IsBadRequestError": true,
"IsHTTPError": true,
"IsTimeoutError": false,
},
},
{
name: "wrapped timeout error",
err: fmt.Errorf("connection failed: %w", &TimeoutError{Message: "Request timeout"}),
checkers: map[string]func(error) bool{
"IsTimeoutError": IsTimeoutError,
"IsNetworkError": IsNetworkError,
"IsHTTPError": IsHTTPError,
},
expected: map[string]bool{
"IsTimeoutError": true,
"IsNetworkError": false,
"IsHTTPError": false,
},
},
{
name: "wrapped network error",
err: fmt.Errorf("service unavailable: %w", &NetworkError{Message: "Connection refused", Cause: nil}),
checkers: map[string]func(error) bool{
"IsNetworkError": IsNetworkError,
"IsTimeoutError": IsTimeoutError,
"IsHTTPError": IsHTTPError,
},
expected: map[string]bool{
"IsNetworkError": true,
"IsTimeoutError": false,
"IsHTTPError": false,
},
},
{
name: "double wrapped error",
err: fmt.Errorf("outer: %w", fmt.Errorf("inner: %w", NewHTTPError(http.StatusUnauthorized, []byte(""), "", nil, nil))),
checkers: map[string]func(error) bool{
"IsUnauthorizedError": IsUnauthorizedError,
"IsHTTPError": IsHTTPError,
"IsBadRequestError": IsBadRequestError,
},
expected: map[string]bool{
"IsUnauthorizedError": true,
"IsHTTPError": true,
"IsBadRequestError": false,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for checkerName, checker := range tt.checkers {
result := checker(tt.err)
expected := tt.expected[checkerName]
if result != expected {
t.Errorf("%s() = %v, want %v for wrapped error: %v", checkerName, result, expected, tt.err)
}
}
})
}
}
// Helper function to get error type name for testing.
func getErrorType(err error) string {
{
var errCase0 *BadRequestError
var errCase1 *UnauthorizedError
var errCase2 *NotFoundError
var errCase3 *TooManyRequestsError
var errCase4 *InternalServerError
var errCase5 *HTTPError
var errCase6 *TimeoutError
var errCase7 *NetworkError
switch {
case errors.As(err, &errCase0):
return "*twelvedata.BadRequestError"
case errors.As(err, &errCase1):
return "*twelvedata.UnauthorizedError"
case errors.As(err, &errCase2):
return "*twelvedata.NotFoundError"
case errors.As(err, &errCase3):
return "*twelvedata.TooManyRequestsError"
case errors.As(err, &errCase4):
return "*twelvedata.InternalServerError"
case errors.As(err, &errCase5):
return "*twelvedata.HTTPError"
case errors.As(err, &errCase6):
return "*twelvedata.TimeoutError"
case errors.As(err, &errCase7):
return "*twelvedata.NetworkError"
default:
return "unknown"
}
}
}
// TestErrImplErrorUnwrap verifies that ErrImplError properly implements Unwrap() to enable
// errors.As and errors.Is functionality for wrapped domain-specific errors.
// This is critical for the limiter to correctly identify InsufficientCreditsError and log at WARN level.
func TestErrImplErrorUnwrap(t *testing.T) {
tests := []struct {
name string
innerErr error
expectedCheck func(error) bool
checkName string
}{
{
name: "InsufficientCreditsError wrapped in ErrImplError",
innerErr: &InsufficientCreditsError{
Message: "You have run out of API credits for the day. 8456 API credits were used, with the current limit being 800",
},
expectedCheck: IsInsufficientCreditsError,
checkName: "IsInsufficientCreditsError",
},
{
name: "PlanLimitationError wrapped in ErrImplError",
innerErr: &PlanLimitationError{
Feature: "Real-time data",
Message: "Real-time data is not available with your plan",
},
expectedCheck: IsPlanLimitationError,
checkName: "IsPlanLimitationError",
},
{
name: "SymbolNotFoundError wrapped in ErrImplError",
innerErr: &SymbolNotFoundError{
Symbol: "AAPL",
Message: "**AAPL** not found: symbol may be delisted",
},
expectedCheck: IsSymbolNotFoundError,
checkName: "IsSymbolNotFoundError",
},
{
name: "APIKeyError wrapped in ErrImplError",
innerErr: &APIKeyError{
Type: "invalid",
Message: "Invalid API key provided",
},
expectedCheck: IsAPIKeyError,
checkName: "IsAPIKeyError",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Wrap the error using NewError (creates ErrImplError)
wrappedErr := NewError[error](tt.innerErr, nil)
// Verify that the wrapper implements error interface
if wrappedErr.Error() == "" {
t.Errorf("ErrImplError.Error() should not return empty string")
}
// Verify that Unwrap() works correctly using errors.Unwrap()
unwrapped := errors.Unwrap(wrappedErr)
if unwrapped == nil {
t.Errorf("errors.Unwrap(ErrImplError) returned nil, expected %T", tt.innerErr)
return
}
// Verify unwrapped error matches original
if !errors.Is(unwrapped, tt.innerErr) {
t.Errorf("errors.Unwrap(ErrImplError) = %v, want %v", unwrapped, tt.innerErr)
}
// Verify that errors.As can find the wrapped error through ErrImplError
if !tt.expectedCheck(wrappedErr) {
t.Errorf("%s() = false for wrapped error, want true", tt.checkName)
t.Errorf("This means errors.As cannot unwrap ErrImplError to find the domain error")
}
// Verify error message contains original error message
if !strings.Contains(wrappedErr.Error(), tt.innerErr.Error()) {
t.Errorf("Wrapped error message %q does not contain original error message %q",
wrappedErr.Error(), tt.innerErr.Error())
}
})
}
}
// TestErrImplErrorUnwrapWithRealAPIError tests the complete flow:
// ParseDomainError -> NewError wrapper -> IsXXXError detection works through wrapper.
func TestErrImplErrorUnwrapWithRealAPIError(t *testing.T) {
apiError := &response.Error{
Code: null.IntFrom(429),
Message: "You have run out of API credits for the day. 8456 API credits were used, with the current limit being 800. Wait for the next day or consider switching to a paid plan.",
Status: "error",
}
domainErr := ParseDomainError(apiError, 429, "https://api.twelvedata.com/usage")
if domainErr == nil {
t.Fatalf("ParseDomainError() returned nil, expected InsufficientCreditsError")
}
if !IsInsufficientCreditsError(domainErr) {
t.Errorf("ParseDomainError() did not create InsufficientCreditsError")