-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathclient_test.go
1568 lines (1407 loc) · 37 KB
/
client_test.go
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
// Copyright (c) 2017, 2019 Tim Heckman
// Use of this source code is governed by the MIT License that can be found in
// the LICENSE file at the root of this repository.
package ipdata
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
)
// testErrCheck looks to see if errContains is a substring of err.Error(). If
// not, this calls t.Fatal(). It also calls t.Fatal() if there was an error, but
// errContains is empty. Returns true if you should continue running the test,
// or false if you should stop the test.
func testErrCheck(t *testing.T, name string, errContains string, err error) bool {
t.Helper()
if len(errContains) > 0 {
if err == nil {
t.Fatalf("%s error = <nil>, should contain %q", name, errContains)
return false
}
if errStr := err.Error(); !strings.Contains(errStr, errContains) {
t.Fatalf("%s error = %q, should contain %q", name, errStr, errContains)
return false
}
return false
}
if err != nil && len(errContains) == 0 {
t.Fatalf("%s unexpected error: %v", name, err)
return false
}
return true
}
func testAuthMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "failed to parse form: %v", err)
return
}
if r.FormValue("api-key") != "testAPIkey" {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, `{"message":%q}`, `You have either exceeded your quota or that API key does not exist. Get a free API Key at https://ipdata.co/registration.html or contact [email protected] to upgrade or register for a paid plan at https://ipdata.co/pricing.html.`)
return
}
next(w, r)
}
}
func testBulkHTTPServer() *httptest.Server {
mux := http.NewServeMux()
mux.HandleFunc("/bulk", testAuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "method %s not permitted, want %s", r.Method, http.MethodPost)
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "failed to read body: %v", err)
return
}
var ips []string
if err := json.Unmarshal(body, &ips); err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "failed to parse JSON body: %v", err)
return
}
switch n := len(ips); n {
case 2:
if ips[0] == "1.1.1.1" {
if ips[1] == "8.8.8.8" {
fmt.Fprint(w, testBulkJSONValid)
return
} else if ips[1] == "8.8.4.4" || ips[1] == "4.4.2.2" {
if ips[1] == "8.8.4.4" {
w.WriteHeader(http.StatusForbidden)
}
fmt.Fprint(w, "{invalid json")
return
}
}
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `ip slice wrong inputs, want ["1.1.1.1","8.8.8.8"] got: %#v`, ips)
return
case 3:
if ips[0] == "1.1.1.1" && ips[1] == "8.8.8.8" && ips[2] == "127.0.0.1" {
fmt.Fprint(w, testBulkJSONWithLocalhost)
return
}
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `ip slice wrong inputs, want ["1.1.1.1","8.8.8.8","127.0.0.1"] got: %#v`, ips)
return
default:
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "ip slice wrong length, want 2 or 3 got %d: %#v", n, ips)
return
}
}))
return httptest.NewServer(mux)
}
func testHTTPServer(addr string) (net.Listener, *http.Server, error) {
if addr == "" {
addr = "127.0.0.1:0"
}
mux := http.NewServeMux()
amw := func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "failed to parse form: %v", err)
return
}
if r.FormValue("api-key") != "testAPIkey" {
w.WriteHeader(http.StatusUnauthorized)
_, _ = io.WriteString(w, "API key does not exist.")
return
}
next(w, r)
}
}
// 200 response code
mux.HandleFunc("/76.14.47.42", amw(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, testJSONValid)
}))
// 200 response code -- invalid JSON
mux.HandleFunc("/76.14.42.42", amw(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, "{")
}))
// 400 response code
mux.HandleFunc("/192.168.0.1", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `{"message": "192.168.0.1 is a private IP address"}`)
})
mux.HandleFunc("/bacon", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `{"message": "bacon does not appear to be an IPv4 or IPv6 address"}`)
})
// 401 response code
mux.HandleFunc("/8.8.4.4", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
_, _ = io.WriteString(w, `{"message": "API key does not exist."}`)
})
mux.HandleFunc("/8.4.0.3", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
_, _ = io.WriteString(w, `{"message": "unexpected HTTP status code"}`)
})
// 429 response code
mux.HandleFunc("/8.8.8.8", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
_, _ = io.WriteString(
w,
`{"message":"You have either exceeded your quota or that API key does not exist. Get a free API Key at https://ipdata.co/registration.html or contact [email protected] to upgrade or register for a paid plan at https://ipdata.co/pricing.html."}`,
)
})
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, nil, err
}
server := &http.Server{
Addr: l.Addr().String(),
Handler: mux,
ReadTimeout: 2 * time.Second,
ReadHeaderTimeout: time.Second,
WriteTimeout: time.Second,
IdleTimeout: time.Second,
}
go func() {
_ = server.Serve(l)
}()
return l, server, nil
}
func TestNewClient(t *testing.T) {
tests := []struct {
name string
i string
e string
k string
err string
}{
{
name: "no_api_key",
e: "https://api.ipdata.co/",
err: "apiKey cannot be an empty string",
},
{
name: "with_api_key",
i: "testAPIkey",
e: "https://api.ipdata.co/",
k: "testAPIkey",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c, err := NewClient(tt.i)
if cont := testErrCheck(t, "NewClient()", tt.err, err); !cont {
return
}
if c.e != tt.e {
t.Fatalf("cc.e = %q,want %q", c.e, tt.e)
}
if c.k != tt.k {
t.Fatalf("cc.k = %q,want %q", c.k, tt.k)
}
if c.c == nil {
t.Fatal("cc.c should not be nil")
}
})
}
}
const tjFlagURL = "https://ipdata.co/flags/us.png"
func Test_client_Lookup(t *testing.T) {
ln, srvr, err := testHTTPServer("")
if err != nil {
t.Fatalf(`testHTTPServer("") returned unexpected error: %s`, err)
}
defer func() {
_ = srvr.Close()
_ = ln.Close()
}()
if err != nil {
t.Fatalf("failed to parse URL: %s", err)
}
c := Client{
c: newHTTPClient(),
e: "http://" + ln.Addr().String() + "/",
k: "testAPIkey",
}
tests := []struct {
name string
i string
o IP
e string
}{
{
name: "invalid_json",
i: "76.14.42.42",
e: "failed to parse JSON: unexpected end of JSON input",
},
{
name: "private_ipv4",
i: "192.168.0.1",
e: "192.168.0.1 is a private IP address",
},
{
name: "invalid_ip",
i: "bacon",
e: "bacon does not appear to be an IPv4 or IPv6 address",
},
{
name: "rate_limited",
i: "8.8.8.8",
e: "You have either exceeded your quota or that API key does not exist. Get a free API Key at https://ipdata.co/registration.html or contact [email protected] to upgrade or register for a paid plan at https://ipdata.co/pricing.html.",
},
{
name: "valid_address",
i: "76.14.47.42",
o: IP{
IP: "76.14.47.42",
ASN: ASN{
ASN: "AS11404",
Name: "vanoppen.biz LLC",
Domain: "wavebroadband.com",
Route: "76.14.0.0/17",
Type: "isp",
},
Organization: "vanoppen.biz LLC",
City: "San Francisco",
Region: "California",
Postal: "94132",
CountryName: "United States",
CountryCode: "US",
Flag: tjFlagURL,
EmojiUnicode: `"U+1F1FA U+1F1F8"`,
ContinentName: "North America",
ContinentCode: "NA",
Latitude: 37.723,
Longitude: -122.4842,
CallingCode: "1",
Languages: []Language{},
Currency: &Currency{
Name: "US Dollar",
Code: "USD",
Symbol: "$",
Native: "$",
Plural: "US dollars",
},
TimeZone: &TimeZone{
Name: "America/Los_Angeles",
Abbreviation: "PST",
Offset: "-0800",
IsDST: false,
CurrentTime: "2019-02-27T15:00:32.745936-08:00",
},
Threat: &Threat{
IsTOR: false,
IsProxy: false,
IsAnonymous: false,
IsKnownAttacker: false,
IsKnownAbuser: false,
IsThreat: true,
IsBogon: false,
},
},
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
var ip IP
var err error
ip, err = c.Lookup(tt.i)
if len(tt.e) > 0 {
if err == nil {
t.Fatal("error expected but was nil")
}
if !strings.Contains(err.Error(), tt.e) {
t.Fatalf("error message %q not found in error: %s", tt.e, err)
}
return
}
if err != nil {
t.Fatalf("Lookup(%q) unexpected error: %s", tt.i, err)
}
if a, b := ip.IP, tt.o.IP; a != b {
t.Errorf("ip.IP = %q, want %q", a, b)
}
if ip.ASN != tt.o.ASN {
t.Errorf("ip.ASN = %q, want %q", ip.ASN, tt.o.ASN)
}
if ip.Organization != tt.o.Organization {
t.Errorf("ip.Organization = %q, want %q", ip.Organization, tt.o.Organization)
}
if ip.City != tt.o.City {
t.Errorf("ip.City = %q, want %q", ip.City, tt.o.City)
}
if ip.Region != tt.o.Region {
t.Errorf("ip.Region = %q, want %q", ip.Region, tt.o.Region)
}
if ip.Postal != tt.o.Postal {
t.Errorf("ip.Postal = %q, want %q", ip.Postal, tt.o.Postal)
}
if ip.CountryName != tt.o.CountryName {
t.Errorf("ip.CountryName = %q, want %q", ip.CountryName, tt.o.CountryName)
}
if ip.CountryCode != tt.o.CountryCode {
t.Errorf("ip.CountryCode = %q, want %q", ip.CountryCode, tt.o.CountryCode)
}
if a, b := ip.Flag, tt.o.Flag; a != b {
t.Errorf("ip.Flag = %q, want %q", a, b)
}
if ip.ContinentName != tt.o.ContinentName {
t.Errorf("ip.ContinentName = %q, want %q", ip.ContinentName, tt.o.ContinentName)
}
if ip.ContinentCode != tt.o.ContinentCode {
t.Errorf("ip.ContinentCode = %q, want %q", ip.ContinentCode, tt.o.ContinentCode)
}
if ip.Latitude != tt.o.Latitude {
t.Errorf("ip.Latitude = %f, want %f", ip.Latitude, tt.o.Latitude)
}
if ip.Longitude != tt.o.Longitude {
t.Errorf("ip.Longitude = %f, want %f", ip.Longitude, tt.o.Longitude)
}
if ip.CallingCode != tt.o.CallingCode {
t.Errorf("ip.CallingCode = %q, want %q", ip.CallingCode, tt.o.CallingCode)
}
if *ip.Currency != *tt.o.Currency {
t.Errorf("ip.Currency = %#v, want %#v", ip.Currency, tt.o.Currency)
}
if a, b := *ip.TimeZone, *tt.o.TimeZone; a != b {
t.Errorf("ip.TimeZone = %#v, want %#v", a, b)
}
if a, b := *ip.Threat, *tt.o.Threat; a != b {
t.Errorf("ip.Threat = %#v, want %#v", a, b)
}
})
}
}
func Test_client_RawLookup(t *testing.T) {
ln, srvr, err := testHTTPServer("")
if err != nil {
t.Fatalf(`testHTTPServer("") returned unexpected error: %s`, err)
}
defer func() {
_ = srvr.Close()
_ = ln.Close()
}()
c := Client{
c: newHTTPClient(),
e: "http://" + ln.Addr().String() + "/",
k: "testAPIkey",
}
tests := []struct {
c Client
name string
i string
o string
e string
}{
{
c: c,
name: "invalid_request",
i: "%ƒail",
e: "error building request to look up %ƒail",
},
{
c: c,
name: "private_ipv4",
i: "192.168.0.1",
e: "192.168.0.1 is a private IP address",
},
{
c: c,
name: "invalid_ip",
i: "bacon",
e: "bacon does not appear to be an IPv4 or IPv6 address",
},
{
c: c,
name: "rate_limited",
i: "8.8.8.8",
e: "You have either exceeded your quota or that API key does not exist. Get a free API Key at https://ipdata.co/registration.html or contact [email protected] to upgrade or register for a paid plan at https://ipdata.co/pricing.html.",
},
{
c: c,
name: "unexpected_error",
i: "8.4.0.3",
e: "unexpected HTTP status code",
},
{
c: c,
name: "invalid_api-key",
i: "8.8.4.4",
e: "API key does not exist.",
},
{
c: c,
name: "valid_address",
i: "76.14.47.42",
o: testJSONValid,
},
{
c: Client{c: newHTTPClient(), e: "http://127.0.0.1:8404/", k: "testAPIkey"},
name: "tcp_conn_err",
i: "76.14.47.42",
e: `http request to "http://127.0.0.1:8404/76.14.47.42" failed`,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
var resp *http.Response
var err error
resp, err = tt.c.RawLookup(tt.i)
if len(tt.e) > 0 {
if err == nil {
t.Fatal("error expected but was nil")
}
if !strings.Contains(err.Error(), tt.e) {
t.Fatalf("error message %q not found in error: %s", tt.e, err)
}
return
}
if err != nil {
t.Fatalf("RawLookup(%q) unexpected error: %s", tt.i, err)
}
defer func() {
_, _ = io.Copy(ioutil.Discard, resp.Body)
_ = resp.Body.Close()
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("unexpected error reading response body: %s", err)
}
if str := string(body); str != tt.o {
t.Fatalf("resp.Body = %q, want %q", str, tt.o)
}
})
}
}
func mustParseURL(u string) *url.URL {
v, err := url.Parse(u)
if err != nil {
panic(err)
}
return v
}
func Test_newGetRequestWithContext(t *testing.T) {
tests := []struct {
name string
url string
key string
want *http.Request
err string
}{
{
name: "no_url",
err: "url cannot be an empty string",
},
{
name: "no_api_key",
url: "http://localhost/",
err: "apiKey cannot be an empty string",
},
{
name: "url",
key: "abc123",
url: "http://localhost/",
want: &http.Request{
Header: map[string][]string{
"User-Agent": {userAgent},
"Accept": {"application/json"},
},
URL: mustParseURL("http://localhost/?api-key=abc123"),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := newGetRequestWithContext(context.Background(), tt.url, tt.key)
if cont := testErrCheck(t, "newGetRequestWithContext()", tt.err, err); !cont {
return
}
if gots, wants := got.URL.String(), tt.want.URL.String(); gots != wants {
t.Fatalf("got.URL = %q, want %q", gots, wants)
}
if gots, wants := got.Header.Get("User-Agent"), tt.want.Header.Get("User-Agent"); gots != wants {
t.Fatalf("User-Agent = %q, want %q", gots, wants)
}
if gots, wants := got.Header.Get("Accept"), tt.want.Header.Get("Accept"); gots != wants {
t.Fatalf("Accept = %q, want %q", gots, wants)
}
})
}
}
func Test_newBulkPostRequestWithContext(t *testing.T) {
tests := []struct {
name string
url string
key string
ips []string
want *http.Request
err string
}{
{
name: "no_url",
err: "url cannot be an empty string",
},
{
name: "no_api_key",
url: "http://localhost/",
err: "apiKey cannot be an empty string",
},
{
name: "no_ips",
key: "abc123",
url: "http://localhost/",
err: "must provide at least one IP",
},
{
name: "url",
key: "abc123",
url: "http://localhost/",
ips: []string{"8.8.8.8", "8.8.4.4"},
want: &http.Request{
Header: map[string][]string{
"User-Agent": {userAgent},
"Accept": {"application/json"},
"Content-Type": {"application/json"},
},
URL: mustParseURL("http://localhost/?api-key=abc123"),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := newBulkPostRequestWithContext(context.Background(), tt.url, tt.key, tt.ips)
if cont := testErrCheck(t, "newBulkPostRequestWithContext()", tt.err, err); !cont {
return
}
if gots, wants := got.URL.String(), tt.want.URL.String(); gots != wants {
t.Fatalf("got.URL = %q, want %q", gots, wants)
}
if gots, wants := got.Header.Get("User-Agent"), tt.want.Header.Get("User-Agent"); gots != wants {
t.Fatalf("User-Agent = %q, want %q", gots, wants)
}
if gots, wants := got.Header.Get("Content-Type"), tt.want.Header.Get("Content-Type"); gots != wants {
t.Fatalf("Content-Type = %q, want %q", gots, wants)
}
})
}
}
func Test_decodeIP(t *testing.T) {
tests := []struct {
name string
i string
o IP
e string
}{
{
name: "invalid_json",
i: "garbage",
e: "failed to parse JSON:",
},
{
name: "valid_json",
i: testJSONValid,
o: IP{
IP: "76.14.47.42",
ASN: ASN{
ASN: "AS11404",
Name: "vanoppen.biz LLC",
Domain: "wavebroadband.com",
Route: "76.14.0.0/17",
Type: "isp",
},
Organization: "vanoppen.biz LLC",
City: "San Francisco",
Region: "California",
Postal: "94132",
CountryName: "United States",
CountryCode: "US",
Flag: tjFlagURL,
EmojiUnicode: `U+1F1FA U+1F1F8`,
ContinentName: "North America",
ContinentCode: "NA",
Latitude: 37.723,
Longitude: -122.4842,
CallingCode: "1",
IsEU: true,
Languages: []Language{},
Currency: &Currency{
Name: "US Dollar",
Code: "USD",
Symbol: "$",
Native: "$",
Plural: "US dollars",
},
TimeZone: &TimeZone{
Name: "America/Los_Angeles",
Abbreviation: "PST",
Offset: "-0800",
IsDST: false,
CurrentTime: "2019-02-27T15:00:32.745936-08:00",
},
Threat: &Threat{
IsTOR: false,
IsProxy: false,
IsAnonymous: false,
IsKnownAttacker: false,
IsKnownAbuser: false,
IsThreat: true,
IsBogon: false,
},
},
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
ip, err := decodeIP(strings.NewReader(tt.i))
if len(tt.e) > 0 {
if err == nil {
t.Fatal("error expected but was nil")
}
if !strings.Contains(err.Error(), tt.e) {
t.Fatalf("error message %q not found in error: %s", tt.e, err)
}
return
}
if err != nil {
t.Fatalf("DecodeIP(%+v) returned an unexpected error: %s", tt.i, err)
}
if a, b := ip.IP, tt.o.IP; a != b {
t.Errorf("ip.IP = %q, want %q", a, b)
}
if ip.ASN != tt.o.ASN {
t.Errorf("ip.ASN = %q, want %q", ip.ASN, tt.o.ASN)
}
if ip.Organization != tt.o.Organization {
t.Errorf("ip.Organization = %q, want %q", ip.Organization, tt.o.Organization)
}
if ip.City != tt.o.City {
t.Errorf("ip.City = %q, want %q", ip.City, tt.o.City)
}
if ip.Region != tt.o.Region {
t.Errorf("ip.Region = %q, want %q", ip.Region, tt.o.Region)
}
if ip.Postal != tt.o.Postal {
t.Errorf("ip.Postal = %q, want %q", ip.Postal, tt.o.Postal)
}
if ip.CountryName != tt.o.CountryName {
t.Errorf("ip.CountryName = %q, want %q", ip.CountryName, tt.o.CountryName)
}
if ip.CountryCode != tt.o.CountryCode {
t.Errorf("ip.CountryCode = %q, want %q", ip.CountryCode, tt.o.CountryCode)
}
if a, b := ip.Flag, tt.o.Flag; a != b {
t.Errorf("ip.Flag = %q, want %q", a, b)
}
if ip.ContinentName != tt.o.ContinentName {
t.Errorf("ip.ContinentName = %q, want %q", ip.ContinentName, tt.o.ContinentName)
}
if ip.ContinentCode != tt.o.ContinentCode {
t.Errorf("ip.ContinentCode = %q, want %q", ip.ContinentCode, tt.o.ContinentCode)
}
if ip.Latitude != tt.o.Latitude {
t.Errorf("ip.Latitude = %f, want %f", ip.Latitude, tt.o.Latitude)
}
if ip.Longitude != tt.o.Longitude {
t.Errorf("ip.Longitude = %f, want %f", ip.Longitude, tt.o.Longitude)
}
if ip.CallingCode != tt.o.CallingCode {
t.Errorf("ip.CallingCode = %q, want %q", ip.CallingCode, tt.o.CallingCode)
}
if ip.IsEU != tt.o.IsEU {
t.Errorf("ip.IsEU = %v, want %v", ip.IsEU, tt.o.IsEU)
}
if ip.EmojiUnicode != tt.o.EmojiUnicode {
t.Errorf("ip.EmojiUnicode = %q, want %q", ip.EmojiUnicode, tt.o.EmojiUnicode)
}
if a, b := len(ip.Languages), len(tt.o.Languages); a != b {
t.Errorf("len(ip.Languages) = %d, want %d", a, b)
}
fn := func(t *testing.T, x, y []Language) {
t.Helper()
for i := range tt.o.Languages {
if i >= len(ip.Languages) {
t.Errorf("ip.Languages[%d] = [not present], want %#v", i, tt.o.Languages[i])
continue
}
a, b := ip.Languages[i], tt.o.Languages[i]
if a != b {
t.Errorf("ip.Languages[%d] = %#v, want %#v", i, a, b)
}
}
}
if len(ip.Languages) >= len(tt.o.Languages) {
fn(t, ip.Languages, tt.o.Languages)
} else {
fn(t, tt.o.Languages, ip.Languages)
}
if *ip.Currency != *tt.o.Currency {
t.Errorf("ip.Currency = %#v, want %#v", ip.Currency, tt.o.Currency)
}
if a, b := *ip.TimeZone, *tt.o.TimeZone; a != b {
t.Errorf("ip.TimeZone = %#v, want %#v", a, b)
}
if a, b := *ip.Threat, *tt.o.Threat; a != b {
t.Errorf("ip.Threat = %#v, want %#v", a, b)
}
})
}
}
func TestClient_RawBulkLookup(t *testing.T) {
server := testBulkHTTPServer()
defer func() {
server.CloseClientConnections()
server.Close()
}()
client := &Client{
c: newHTTPClient(),
e: "http://127.0.0.1:9085/",
}
tests := []struct {
name string
ips []string
setKey string
serverURL string
wantStatus int
wantBody string
err string
}{
{
name: "no_api_key",
err: "error building bulk lookup request: apiKey cannot be an empty string",
},
{
name: "no_ips",
setKey: "badAPIkey",
err: "error building bulk lookup request: must provide at least one IP",
},
{
name: "bad_host",
ips: []string{"1.1.1.1", "8.8.8.8"},
err: `http request to "http://127.0.0.1:9085/bulk" failed: Post http://127.0.0.1:9085/bulk?api-key=badAPIkey: dial tcp 127.0.0.1:9085: connect: connection refused`,
},
{
name: "bad_api_key",
ips: []string{"1.1.1.1", "8.8.8.8"},
serverURL: server.URL + "/",
err: `You have either exceeded your quota or that API key does not exist. Get a free API Key at https://ipdata.co/registration.html or contact [email protected] to upgrade or register for a paid plan at https://ipdata.co/pricing.html.`,
},
{
name: "bad_json",
ips: []string{"1.1.1.1", "8.8.4.4"},
setKey: "testAPIkey",
err: `request failed (unexpected response): 403 Forbidden: invalid character 'i' looking for beginning of object key string`,
},
{
name: "good_ips",
ips: []string{"1.1.1.1", "8.8.8.8"},
wantStatus: 200,
wantBody: testBulkJSONValid,
},
{
name: "good_ips_with_localhost",
ips: []string{"1.1.1.1", "8.8.8.8", "127.0.0.1"},
wantStatus: 200,
wantBody: testBulkJSONWithLocalhost,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.setKey != "" {
client.k = tt.setKey
}
if tt.serverURL != "" {
client.e = tt.serverURL
}
got, err := client.RawBulkLookup(tt.ips)
if cont := testErrCheck(t, "client.RawBulkLookup()", tt.err, err); !cont {
return
}
defer func() {
_, _ = io.Copy(ioutil.Discard, got.Body)
_ = got.Body.Close()
}()
if got.StatusCode != tt.wantStatus {
t.Fatalf("got.StatusCode = %d, want %d", got.StatusCode, tt.wantStatus)
}
body, err := ioutil.ReadAll(got.Body)
testErrCheck(t, "ioutil.ReadAll()", "", err)
if b := string(body); b != tt.wantBody {
t.Fatalf("got.Body = %q, want %q", b, tt.wantBody)
}
})
}
}
func TestClient_BulkLookup(t *testing.T) {
server := testBulkHTTPServer()
defer func() {
server.CloseClientConnections()