-
Notifications
You must be signed in to change notification settings - Fork 0
/
maxmind_test.go
109 lines (88 loc) · 2.85 KB
/
maxmind_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
package geo
import (
"embed"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
//go:embed test/MaxMind-DB/test-data/*.mmdb
var embedFS embed.FS
const (
maxmindCountryTestDB string = "test/MaxMind-DB/test-data/GeoIP2-Country-Test.mmdb" // test database, only covers NA, EU, AS continents
)
type countryLookupTest struct {
ip string
expectedCountryCode string
expectedCountryAlpha3Code string
expectedContinentCode string
expectedUnknown bool
expectedError bool
}
func TestCountryLookupWithMaxmind(t *testing.T) {
file, err := embedFS.Open(maxmindCountryTestDB)
if err != nil {
t.Fatal(fmt.Errorf("embedFS.Open: %w", err))
}
maxmind, err := NewMaxMindFromReader(file)
if err != nil {
t.Fatal(fmt.Errorf("NewMaxMindn: %w", err))
}
assert.Equal(t, true, maxmind.IsTestDB(), "not a test db")
ipTests := []countryLookupTest{
{
ip: "::149.101.100.0",
expectedCountryCode: "US",
expectedCountryAlpha3Code: "USA",
expectedContinentCode: "NA",
expectedUnknown: false,
expectedError: false,
},
{
ip: "81.2.69.142",
expectedCountryCode: "GB",
expectedCountryAlpha3Code: "GBR",
expectedContinentCode: "EU",
expectedUnknown: false,
expectedError: false,
},
{
ip: "2001:218::",
expectedCountryCode: "JP",
expectedCountryAlpha3Code: "JPN",
expectedContinentCode: "AS",
expectedUnknown: false,
expectedError: false,
},
{
ip: "1", // wrong ip
expectedCountryCode: "",
expectedContinentCode: "",
expectedCountryAlpha3Code: "",
expectedUnknown: false,
expectedError: true,
},
{
ip: "127.0.0.1", // local ip
expectedCountryCode: "ZZ",
expectedContinentCode: "ZZ",
expectedCountryAlpha3Code: "ZZZ",
expectedUnknown: true,
expectedError: false,
},
}
for _, test := range ipTests {
country, err := maxmind.CountryByIPString(test.ip)
if test.expectedError {
assert.NotNil(t, err, "expected error")
assert.Nil(t, country, "expected country to be nil ")
continue
}
assert.Nil(t, err, "expected no error")
assert.NotNil(t, country, "expected country to not be nil ")
assert.Equal(t, test.expectedUnknown, country.IsUnknown(), "expected country does not match unknown expectation")
assert.Equal(t, test.expectedCountryCode, country.CountryAlpha2Code(), "mismatch country code")
assert.Equal(t, test.expectedCountryAlpha3Code, country.CountryAlpha3Code(), "mismatch country alpha3 code")
assert.Equal(t, test.expectedContinentCode, country.ContinentCode(), "mismatch continent code")
}
assert.Nil(t, nil, maxmind.Close(), "close the reader should not generate an error")
}