-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_test.go
More file actions
1046 lines (929 loc) · 29.5 KB
/
client_test.go
File metadata and controls
1046 lines (929 loc) · 29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
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 rdapapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// mockServer creates a test server that returns predefined responses.
func mockServer(t *testing.T, routes map[string]mockRoute) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Strip query string for route matching.
path := r.URL.Path
route, ok := routes[path]
if !ok {
t.Errorf("unexpected request path: %s", path)
w.WriteHeader(http.StatusNotFound)
return
}
// Let the route handler validate request details if needed.
if route.check != nil {
route.check(t, r)
}
for k, v := range route.headers {
w.Header().Set(k, v)
}
w.WriteHeader(route.status)
_, _ = w.Write([]byte(route.body))
}))
}
type mockRoute struct {
status int
body string
headers map[string]string
check func(t *testing.T, r *http.Request)
}
// --- Constructor tests ---
func TestNewClientDefaults(t *testing.T) {
c := NewClient("test-key")
if c.apiKey != "test-key" {
t.Errorf("apiKey = %q, want %q", c.apiKey, "test-key")
}
if c.baseURL != defaultBaseURL {
t.Errorf("baseURL = %q, want %q", c.baseURL, defaultBaseURL)
}
if c.httpClient.Timeout != defaultTimeout {
t.Errorf("Timeout = %v, want %v", c.httpClient.Timeout, defaultTimeout)
}
if !strings.HasPrefix(c.userAgent, "rdapapi-go/") {
t.Errorf("userAgent = %q, want prefix %q", c.userAgent, "rdapapi-go/")
}
}
func TestNewClientWithBaseURL(t *testing.T) {
c := NewClient("key", WithBaseURL("https://custom.api.com/v1"))
if c.baseURL != "https://custom.api.com/v1" {
t.Errorf("baseURL = %q, want %q", c.baseURL, "https://custom.api.com/v1")
}
}
func TestNewClientWithTimeout(t *testing.T) {
c := NewClient("key", WithTimeout(5*time.Second))
if c.httpClient.Timeout != 5*time.Second {
t.Errorf("Timeout = %v, want %v", c.httpClient.Timeout, 5*time.Second)
}
}
func TestNewClientWithHTTPClient(t *testing.T) {
custom := &http.Client{Timeout: 99 * time.Second}
c := NewClient("key", WithHTTPClient(custom))
if c.httpClient != custom {
t.Error("httpClient was not set to custom client")
}
}
// --- Header tests ---
func TestRequestHeaders(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/domain/example.com": {
status: 200,
body: `{"domain":"example.com","status":[],"registrar":{},"dates":{},"nameservers":[],"dnssec":false,"entities":{},"meta":{"rdap_server":"","raw_rdap_url":"","cached":false,"cache_expires":""}}`,
check: func(t *testing.T, r *http.Request) {
t.Helper()
if got := r.Header.Get("Authorization"); got != "Bearer test-key-123" {
t.Errorf("Authorization = %q, want %q", got, "Bearer test-key-123")
}
if got := r.Header.Get("User-Agent"); !strings.HasPrefix(got, "rdapapi-go/") {
t.Errorf("User-Agent = %q, want prefix %q", got, "rdapapi-go/")
}
if got := r.Header.Get("Accept"); got != "application/json" {
t.Errorf("Accept = %q, want %q", got, "application/json")
}
},
},
})
defer srv.Close()
c := NewClient("test-key-123", WithBaseURL(srv.URL))
_, err := c.Domain(context.Background(), "example.com")
if err != nil {
t.Fatalf("Domain() error: %v", err)
}
}
// --- Domain tests ---
func TestDomainLookup(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/domain/google.com": {
status: 200,
body: `{"domain":"google.com","handle":"D-123","status":["client transfer prohibited"],"registrar":{"name":"MarkMonitor"},"dates":{"registered":"1997-09-15T04:00:00Z"},"nameservers":["ns1.google.com"],"dnssec":false,"entities":{},"meta":{"rdap_server":"https://rdap.markmonitor.com","raw_rdap_url":"https://rdap.markmonitor.com/rdap/domain/google.com","cached":false,"cache_expires":""}}`,
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
resp, err := c.Domain(context.Background(), "google.com")
if err != nil {
t.Fatalf("Domain() error: %v", err)
}
if resp.Domain != "google.com" {
t.Errorf("Domain = %q, want %q", resp.Domain, "google.com")
}
if resp.Registrar.Name == nil || *resp.Registrar.Name != "MarkMonitor" {
t.Errorf("Registrar.Name = %v, want MarkMonitor", resp.Registrar.Name)
}
}
func TestDomainWithFollow(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/domain/example.com": {
status: 200,
body: `{"domain":"example.com","status":[],"registrar":{},"dates":{},"nameservers":[],"dnssec":false,"entities":{},"meta":{"rdap_server":"","raw_rdap_url":"","cached":false,"cache_expires":"","followed":true}}`,
check: func(t *testing.T, r *http.Request) {
t.Helper()
if got := r.URL.Query().Get("follow"); got != "true" {
t.Errorf("follow query = %q, want %q", got, "true")
}
},
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
resp, err := c.Domain(context.Background(), "example.com", WithFollow())
if err != nil {
t.Fatalf("Domain() error: %v", err)
}
if resp.Meta.Followed == nil || !*resp.Meta.Followed {
t.Error("Meta.Followed should be true")
}
}
func TestDomainWithoutFollow(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/domain/example.com": {
status: 200,
body: `{"domain":"example.com","status":[],"registrar":{},"dates":{},"nameservers":[],"dnssec":false,"entities":{},"meta":{"rdap_server":"","raw_rdap_url":"","cached":false,"cache_expires":""}}`,
check: func(t *testing.T, r *http.Request) {
t.Helper()
if got := r.URL.Query().Get("follow"); got != "" {
t.Errorf("follow query = %q, want empty (no follow)", got)
}
},
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.Domain(context.Background(), "example.com")
if err != nil {
t.Fatalf("Domain() error: %v", err)
}
}
// --- IP tests ---
func TestIPLookup(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/ip/8.8.8.8": {
status: 200,
body: `{"handle":"NET-8-8-8-0-1","name":"LVLT-GOGL-8-8-8","start_address":"8.8.8.0","end_address":"8.8.8.255","ip_version":"v4","status":["active"],"dates":{},"entities":{},"cidr":["8.8.8.0/24"],"remarks":[],"meta":{"rdap_server":"https://rdap.arin.net","raw_rdap_url":"","cached":false,"cache_expires":""}}`,
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
resp, err := c.IP(context.Background(), "8.8.8.8")
if err != nil {
t.Fatalf("IP() error: %v", err)
}
if resp.Handle == nil || *resp.Handle != "NET-8-8-8-0-1" {
t.Errorf("Handle = %v, want NET-8-8-8-0-1", resp.Handle)
}
if resp.IPVersion == nil || *resp.IPVersion != "v4" {
t.Errorf("IPVersion = %v, want v4", resp.IPVersion)
}
}
// --- ASN tests ---
func TestASNLookup(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/asn/15169": {
status: 200,
body: `{"handle":"AS15169","name":"GOOGLE","start_autnum":15169,"end_autnum":15169,"status":["active"],"dates":{},"entities":{},"remarks":[],"meta":{"rdap_server":"https://rdap.arin.net","raw_rdap_url":"","cached":false,"cache_expires":""}}`,
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
resp, err := c.ASN(context.Background(), "15169")
if err != nil {
t.Fatalf("ASN() error: %v", err)
}
if resp.Handle == nil || *resp.Handle != "AS15169" {
t.Errorf("Handle = %v, want AS15169", resp.Handle)
}
}
func TestASNLookupStripsPrefix(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/asn/15169": {
status: 200,
body: `{"handle":"AS15169","name":"GOOGLE","start_autnum":15169,"end_autnum":15169,"status":[],"dates":{},"entities":{},"remarks":[],"meta":{"rdap_server":"","raw_rdap_url":"","cached":false,"cache_expires":""}}`,
check: func(t *testing.T, r *http.Request) {
t.Helper()
// The path should be /asn/15169 (prefix stripped).
if !strings.HasSuffix(r.URL.Path, "/asn/15169") {
t.Errorf("path = %q, want suffix /asn/15169", r.URL.Path)
}
},
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
// Test with "AS" prefix.
_, err := c.ASN(context.Background(), "AS15169")
if err != nil {
t.Fatalf("ASN(AS15169) error: %v", err)
}
}
func TestASNLookupLowercasePrefix(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/asn/15169": {
status: 200,
body: `{"handle":"AS15169","status":[],"dates":{},"entities":{},"remarks":[],"meta":{"rdap_server":"","raw_rdap_url":"","cached":false,"cache_expires":""}}`,
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
// Test with lowercase "as" prefix.
_, err := c.ASN(context.Background(), "as15169")
if err != nil {
t.Fatalf("ASN(as15169) error: %v", err)
}
}
func TestASNInvalidInput(t *testing.T) {
c := NewClient("key")
_, err := c.ASN(context.Background(), "NOTANUMBER")
if err == nil {
t.Fatal("expected error for non-numeric ASN")
}
if !strings.Contains(err.Error(), "invalid ASN") {
t.Errorf("error = %q, want 'invalid ASN'", err.Error())
}
_, err = c.ASN(context.Background(), "AS")
if err == nil {
t.Fatal("expected error for empty ASN after prefix strip")
}
}
// --- Nameserver tests ---
func TestNameserverLookup(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/nameserver/ns1.google.com": {
status: 200,
body: `{"ldh_name":"ns1.google.com","handle":"NS-001","ip_addresses":{"v4":["216.239.32.10"],"v6":[]},"status":["active"],"dates":{},"entities":{},"meta":{"rdap_server":"","raw_rdap_url":"","cached":false,"cache_expires":""}}`,
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
resp, err := c.Nameserver(context.Background(), "ns1.google.com")
if err != nil {
t.Fatalf("Nameserver() error: %v", err)
}
if resp.LDHName != "ns1.google.com" {
t.Errorf("LDHName = %q, want %q", resp.LDHName, "ns1.google.com")
}
}
// --- Entity tests ---
func TestEntityLookup(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/entity/GOGL": {
status: 200,
body: `{"handle":"GOGL","name":"Google LLC","roles":["registrant"],"status":["active"],"dates":{},"remarks":[],"public_ids":[],"entities":{},"autnums":[],"networks":[],"meta":{"rdap_server":"","raw_rdap_url":"","cached":false,"cache_expires":""}}`,
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
resp, err := c.Entity(context.Background(), "GOGL")
if err != nil {
t.Fatalf("Entity() error: %v", err)
}
if resp.Handle == nil || *resp.Handle != "GOGL" {
t.Errorf("Handle = %v, want GOGL", resp.Handle)
}
if resp.Name == nil || *resp.Name != "Google LLC" {
t.Errorf("Name = %v, want Google LLC", resp.Name)
}
}
// --- Bulk domain tests ---
func TestBulkDomains(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/domains/bulk": {
status: 200,
body: `{
"results": [
{
"domain": "example.com",
"status": "success",
"data": {
"domain": "example.com",
"status": ["active"],
"registrar": {"name": "Test Registrar"},
"dates": {},
"nameservers": [],
"dnssec": false,
"entities": {},
"meta": {"rdap_server": "", "raw_rdap_url": "", "cached": false, "cache_expires": ""}
},
"meta": {
"rdap_server": "https://rdap.verisign.com",
"raw_rdap_url": "https://rdap.verisign.com/com/v1/domain/example.com",
"cached": true,
"cache_expires": "2024-12-01T00:00:00Z"
}
},
{
"domain": "nope.example",
"status": "error",
"error": "not_found",
"message": "No RDAP data found"
}
],
"summary": {"total": 2, "successful": 1, "failed": 1}
}`,
check: func(t *testing.T, r *http.Request) {
t.Helper()
if r.Method != http.MethodPost {
t.Errorf("Method = %q, want POST", r.Method)
}
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
t.Errorf("Content-Type = %q, want application/json", ct)
}
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("failed to decode body: %v", err)
}
domains, ok := body["domains"].([]any)
if !ok || len(domains) != 2 {
t.Errorf("body.domains = %v, want 2 domains", body["domains"])
}
},
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
resp, err := c.BulkDomains(context.Background(), []string{"example.com", "nope.example"})
if err != nil {
t.Fatalf("BulkDomains() error: %v", err)
}
if len(resp.Results) != 2 {
t.Fatalf("Results len = %d, want 2", len(resp.Results))
}
// Verify meta was merged into data.
r0 := resp.Results[0]
if r0.Data == nil {
t.Fatal("Results[0].Data is nil")
}
if r0.Data.Meta.RDAPServer != "https://rdap.verisign.com" {
t.Errorf("Data.Meta.RDAPServer = %q, want %q", r0.Data.Meta.RDAPServer, "https://rdap.verisign.com")
}
if !r0.Data.Meta.Cached {
t.Error("Data.Meta.Cached = false, want true (merged from result level)")
}
if r0.RawMeta != nil {
t.Error("RawMeta should be nil after merge")
}
// Error result.
r1 := resp.Results[1]
if r1.Status != "error" {
t.Errorf("Results[1].Status = %q, want error", r1.Status)
}
if r1.Data != nil {
t.Error("Results[1].Data should be nil for error result")
}
if resp.Summary.Total != 2 {
t.Errorf("Summary.Total = %d, want 2", resp.Summary.Total)
}
}
func TestBulkDomainsWithFollow(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/domains/bulk": {
status: 200,
body: `{"results":[],"summary":{"total":0,"successful":0,"failed":0}}`,
check: func(t *testing.T, r *http.Request) {
t.Helper()
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("failed to decode body: %v", err)
}
follow, ok := body["follow"].(bool)
if !ok || !follow {
t.Errorf("body.follow = %v, want true", body["follow"])
}
},
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.BulkDomains(context.Background(), []string{"example.com"}, WithFollow())
if err != nil {
t.Fatalf("BulkDomains() error: %v", err)
}
}
// --- Error handling tests ---
func TestErrorResponses(t *testing.T) {
tests := []struct {
name string
status int
body string
headers map[string]string
checkErr func(t *testing.T, err error)
}{
{
name: "400 ValidationError",
status: 400,
body: `{"error":"invalid_input","message":"Invalid domain name"}`,
checkErr: func(t *testing.T, err error) {
var target *ValidationError
if !errors.As(err, &target) {
t.Fatal("expected ValidationError")
}
if target.StatusCode != 400 {
t.Errorf("StatusCode = %d, want 400", target.StatusCode)
}
if target.Code != "invalid_input" {
t.Errorf("Code = %q, want invalid_input", target.Code)
}
},
},
{
name: "401 AuthenticationError",
status: 401,
body: `{"error":"unauthenticated","message":"Invalid API key"}`,
checkErr: func(t *testing.T, err error) {
var target *AuthenticationError
if !errors.As(err, &target) {
t.Fatal("expected AuthenticationError")
}
},
},
{
name: "403 SubscriptionRequiredError",
status: 403,
body: `{"error":"subscription_required","message":"No active subscription"}`,
checkErr: func(t *testing.T, err error) {
var target *SubscriptionRequiredError
if !errors.As(err, &target) {
t.Fatal("expected SubscriptionRequiredError")
}
},
},
{
name: "404 NotFoundError",
status: 404,
body: `{"error":"not_found","message":"No RDAP data found"}`,
checkErr: func(t *testing.T, err error) {
var target *NotFoundError
if !errors.As(err, &target) {
t.Fatal("expected NotFoundError")
}
},
},
{
name: "429 RateLimitError",
status: 429,
body: `{"error":"rate_limited","message":"Rate limit exceeded"}`,
headers: map[string]string{"Retry-After": "30"},
checkErr: func(t *testing.T, err error) {
var target *RateLimitError
if !errors.As(err, &target) {
t.Fatal("expected RateLimitError")
}
if target.RetryAfter != 30 {
t.Errorf("RetryAfter = %d, want 30", target.RetryAfter)
}
},
},
{
name: "429 RateLimitError without Retry-After",
status: 429,
body: `{"error":"rate_limited","message":"Rate limit exceeded"}`,
checkErr: func(t *testing.T, err error) {
var target *RateLimitError
if !errors.As(err, &target) {
t.Fatal("expected RateLimitError")
}
if target.RetryAfter != 0 {
t.Errorf("RetryAfter = %d, want 0", target.RetryAfter)
}
},
},
{
name: "502 UpstreamError",
status: 502,
body: `{"error":"upstream_error","message":"Upstream RDAP server failed"}`,
checkErr: func(t *testing.T, err error) {
var target *UpstreamError
if !errors.As(err, &target) {
t.Fatal("expected UpstreamError")
}
},
},
{
name: "503 TemporarilyUnavailableError",
status: 503,
body: `{"error":"temporarily_unavailable","message":"Data for this domain is temporarily unavailable."}`,
headers: map[string]string{"Retry-After": "300"},
checkErr: func(t *testing.T, err error) {
var target *TemporarilyUnavailableError
if !errors.As(err, &target) {
t.Fatal("expected TemporarilyUnavailableError")
}
if target.RetryAfter != 300 {
t.Errorf("RetryAfter = %d, want 300", target.RetryAfter)
}
},
},
{
name: "503 TemporarilyUnavailableError without Retry-After",
status: 503,
body: `{"error":"temporarily_unavailable","message":"Data for this domain is temporarily unavailable."}`,
checkErr: func(t *testing.T, err error) {
var target *TemporarilyUnavailableError
if !errors.As(err, &target) {
t.Fatal("expected TemporarilyUnavailableError")
}
if target.RetryAfter != 0 {
t.Errorf("RetryAfter = %d, want 0", target.RetryAfter)
}
},
},
{
name: "500 unknown error",
status: 500,
body: `{"error":"server_error","message":"Internal server error"}`,
checkErr: func(t *testing.T, err error) {
// Should be a base APIError.
var apiErr *APIError
if !errors.As(err, &apiErr) {
t.Fatal("expected APIError for 500")
}
if apiErr.StatusCode != 500 {
t.Errorf("StatusCode = %d, want 500", apiErr.StatusCode)
}
if !strings.Contains(err.Error(), "Internal server error") {
t.Errorf("error message = %q, want to contain 'Internal server error'", err.Error())
}
},
},
{
name: "invalid JSON body",
status: 400,
body: `not json at all`,
checkErr: func(t *testing.T, err error) {
var target *ValidationError
if !errors.As(err, &target) {
t.Fatal("expected ValidationError even with invalid JSON body")
}
// Falls back to "HTTP 400" message.
if target.Code != "unknown_error" {
t.Errorf("Code = %q, want unknown_error", target.Code)
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/domain/test.com": {
status: tt.status,
body: tt.body,
headers: tt.headers,
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.Domain(context.Background(), "test.com")
if err == nil {
t.Fatal("expected error, got nil")
}
tt.checkErr(t, err)
})
}
}
// --- Context cancellation ---
func TestContextCancellation(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/domain/slow.com": {
status: 200,
body: `{"domain":"slow.com","status":[],"registrar":{},"dates":{},"nameservers":[],"dnssec":false,"entities":{},"meta":{"rdap_server":"","raw_rdap_url":"","cached":false,"cache_expires":""}}`,
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
ctx, cancel := context.WithCancel(context.Background())
cancel() // Cancel immediately.
_, err := c.Domain(ctx, "slow.com")
if err == nil {
t.Fatal("expected error from cancelled context")
}
}
// --- Invalid URL ---
func TestInvalidBaseURL(t *testing.T) {
c := NewClient("key", WithBaseURL("://invalid"))
_, err := c.Domain(context.Background(), "test.com")
if err == nil {
t.Fatal("expected error for invalid base URL")
}
}
// --- Version ---
func TestVersionIsSet(t *testing.T) {
if Version == "" {
t.Error("Version should not be empty")
}
}
func TestUserAgentContainsVersion(t *testing.T) {
c := NewClient("key")
want := "rdapapi-go/" + Version
if c.userAgent != want {
t.Errorf("userAgent = %q, want %q", c.userAgent, want)
}
}
// --- BulkDomains meta merge edge cases ---
func TestBulkDomainsNoMetaMergeOnError(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/domains/bulk": {
status: 200,
body: `{
"results": [
{
"domain": "fail.example",
"status": "error",
"error": "not_found",
"message": "No data"
}
],
"summary": {"total": 1, "successful": 0, "failed": 1}
}`,
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
resp, err := c.BulkDomains(context.Background(), []string{"fail.example"})
if err != nil {
t.Fatalf("BulkDomains() error: %v", err)
}
if resp.Results[0].Data != nil {
t.Error("Data should be nil for error result")
}
}
func TestBulkDomainsSuccessWithoutMeta(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/domains/bulk": {
status: 200,
body: `{
"results": [
{
"domain": "example.com",
"status": "success",
"data": {
"domain": "example.com",
"status": [],
"registrar": {},
"dates": {},
"nameservers": [],
"dnssec": false,
"entities": {},
"meta": {"rdap_server": "original", "raw_rdap_url": "", "cached": false, "cache_expires": ""}
}
}
],
"summary": {"total": 1, "successful": 1, "failed": 0}
}`,
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
resp, err := c.BulkDomains(context.Background(), []string{"example.com"})
if err != nil {
t.Fatalf("BulkDomains() error: %v", err)
}
// No result-level meta, so data.meta should remain original.
if resp.Results[0].Data.Meta.RDAPServer != "original" {
t.Errorf("Meta.RDAPServer = %q, want 'original'", resp.Results[0].Data.Meta.RDAPServer)
}
}
// --- POST body for bulk ---
func TestBulkDomainsPostBody(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/domains/bulk": {
status: 200,
body: `{"results":[],"summary":{"total":0,"successful":0,"failed":0}}`,
check: func(t *testing.T, r *http.Request) {
t.Helper()
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("decode body: %v", err)
}
domains := body["domains"].([]any)
if len(domains) != 3 {
t.Errorf("domains len = %d, want 3", len(domains))
}
// follow should not be present when not set.
if _, ok := body["follow"]; ok {
t.Error("follow should not be in body when WithFollow is not used")
}
},
},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.BulkDomains(context.Background(), []string{"a.com", "b.com", "c.com"})
if err != nil {
t.Fatalf("BulkDomains() error: %v", err)
}
}
// --- Unmarshal error paths ---
func TestDomainInvalidJSON(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/domain/bad.com": {status: 200, body: `not json`},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.Domain(context.Background(), "bad.com")
if err == nil {
t.Fatal("expected unmarshal error")
}
if !strings.Contains(err.Error(), "decoding response") {
t.Errorf("error = %q, want 'decoding response'", err.Error())
}
}
func TestIPInvalidJSON(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/ip/1.2.3.4": {status: 200, body: `{bad`},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.IP(context.Background(), "1.2.3.4")
if err == nil {
t.Fatal("expected unmarshal error")
}
if !strings.Contains(err.Error(), "decoding response") {
t.Errorf("error = %q, want 'decoding response'", err.Error())
}
}
func TestASNInvalidJSON(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/asn/99999": {status: 200, body: `{bad`},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.ASN(context.Background(), "99999")
if err == nil {
t.Fatal("expected unmarshal error")
}
if !strings.Contains(err.Error(), "decoding response") {
t.Errorf("error = %q, want 'decoding response'", err.Error())
}
}
func TestNameserverInvalidJSON(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/nameserver/ns.bad.com": {status: 200, body: `{bad`},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.Nameserver(context.Background(), "ns.bad.com")
if err == nil {
t.Fatal("expected unmarshal error")
}
if !strings.Contains(err.Error(), "decoding response") {
t.Errorf("error = %q, want 'decoding response'", err.Error())
}
}
func TestEntityInvalidJSON(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/entity/BAD": {status: 200, body: `{bad`},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.Entity(context.Background(), "BAD")
if err == nil {
t.Fatal("expected unmarshal error")
}
if !strings.Contains(err.Error(), "decoding response") {
t.Errorf("error = %q, want 'decoding response'", err.Error())
}
}
func TestBulkDomainsInvalidJSON(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/domains/bulk": {status: 200, body: `{bad`},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.BulkDomains(context.Background(), []string{"a.com"})
if err == nil {
t.Fatal("expected unmarshal error")
}
if !strings.Contains(err.Error(), "decoding response") {
t.Errorf("error = %q, want 'decoding response'", err.Error())
}
}
// --- doPost marshal error ---
func TestBulkDomainsInvalidBody(t *testing.T) {
c := NewClient("key", WithBaseURL("https://localhost"))
// Pass an unmarshalable value via a channel (channels can't be JSON marshaled).
// We can't directly test this through BulkDomains since it always passes valid data.
// Instead, test the doPost internal path with an invalid base URL to cover the request-creation error.
c.baseURL = "://invalid"
_, err := c.BulkDomains(context.Background(), []string{"a.com"})
if err == nil {
t.Fatal("expected error")
}
}
// --- Error responses on each endpoint ---
func TestIPErrorResponse(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/ip/1.2.3.4": {status: 404, body: `{"error":"not_found","message":"No data"}`},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.IP(context.Background(), "1.2.3.4")
if err == nil {
t.Fatal("expected error")
}
var target *NotFoundError
if !errors.As(err, &target) {
t.Errorf("expected NotFoundError, got %T", err)
}
}
func TestASNErrorResponse(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/asn/99999": {status: 401, body: `{"error":"unauthenticated","message":"Bad key"}`},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.ASN(context.Background(), "99999")
if err == nil {
t.Fatal("expected error")
}
var target *AuthenticationError
if !errors.As(err, &target) {
t.Errorf("expected AuthenticationError, got %T", err)
}
}
func TestNameserverErrorResponse(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/nameserver/ns.bad.com": {status: 429, body: `{"error":"rate_limited","message":"Too many"}`, headers: map[string]string{"Retry-After": "10"}},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.Nameserver(context.Background(), "ns.bad.com")
if err == nil {
t.Fatal("expected error")
}
var target *RateLimitError
if !errors.As(err, &target) {
t.Errorf("expected RateLimitError, got %T", err)
}
}
func TestEntityErrorResponse(t *testing.T) {
srv := mockServer(t, map[string]mockRoute{
"/entity/BAD": {status: 502, body: `{"error":"upstream_error","message":"Upstream fail"}`},
})
defer srv.Close()
c := NewClient("key", WithBaseURL(srv.URL))
_, err := c.Entity(context.Background(), "BAD")
if err == nil {
t.Fatal("expected error")
}
var target *UpstreamError
if !errors.As(err, &target) {
t.Errorf("expected UpstreamError, got %T", err)
}
}
// --- doPost marshal error (line 96-98) ---
func TestDoPostMarshalError(t *testing.T) {
c := NewClient("key", WithBaseURL("https://localhost"))
// Channels cannot be JSON marshaled.
_, err := c.doPost(context.Background(), "/test", map[string]any{"bad": make(chan int)})
if err == nil {
t.Fatal("expected marshal error")
}
if !strings.Contains(err.Error(), "marshaling body") {