forked from alecthomas/geoip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeoip_test.go
56 lines (53 loc) · 1.07 KB
/
geoip_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
package geoip
import (
"fmt"
"math/rand"
"net"
"strings"
"testing"
)
func TestGeoIpLookup(t *testing.T) {
db, err := New()
if err != nil {
t.Fatal(err)
}
cases := []struct {
ip net.IP
country Country
}{
{net.ParseIP("8.8.8.8"), Country{"US", "United States"}},
{net.ParseIP("8.8.8.8").To4(), Country{"US", "United States"}},
{net.ParseIP("8.8.8.8").To4()[:3], Country{}},
{net.ParseIP("8.8.8.8")[:15], Country{}},
{nil, Country{}},
}
for _, c := range cases {
var country Country
if ct := db.Lookup(c.ip); ct != nil {
country = *ct
}
if country != c.country {
t.Errorf("%s (%#v) expected %v, got %v", c.ip, c.ip, c.country, country)
}
}
}
func BenchmarkGeoIpLookup(t *testing.B) {
db, err := New()
if err != nil {
panic(err.Error())
}
ips := []net.IP{}
for i := 0; i < 1000; i++ {
ip := ""
for j := 0; j < 4; j++ {
ip += fmt.Sprintf("%d.", rand.Int()%255)
}
ip = strings.TrimRight(ip, ".")
ips = append(ips, net.ParseIP(ip))
}
t.ResetTimer()
for i := 0; i < t.N; i++ {
ip := ips[rand.Int()%len(ips)]
db.Lookup(ip)
}
}