-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_test.go
92 lines (74 loc) · 2.06 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
package extremeiplookup
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func setupTest(t *testing.T) (*Client, *http.ServeMux) {
t.Helper()
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
client := NewClient("secret")
client.baseURL, _ = url.Parse(server.URL)
client.HTTPClient = server.Client()
return client, mux
}
func testHandler(filename string) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet {
http.Error(rw, fmt.Sprintf("unsupported method: %s", req.Method), http.StatusMethodNotAllowed)
return
}
file, err := os.Open(filepath.Join("fixtures", filename))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
defer func() { _ = file.Close() }()
_, err = io.Copy(rw, file)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
}
}
func TestClient_Lookup_error(t *testing.T) {
client, mux := setupTest(t)
mux.HandleFunc("/json/109.236.91.3", testHandler("fail.json"))
ipInfo, err := client.Lookup(context.Background(), "109.236.91.3")
require.Error(t, err)
require.Nil(t, ipInfo)
}
func TestClient_Lookup(t *testing.T) {
client, mux := setupTest(t)
mux.HandleFunc("/json/109.236.91.3", testHandler("success.json"))
ipInfo, err := client.Lookup(context.Background(), "109.236.91.3")
require.NoError(t, err)
expected := &IPInfo{
Query: "109.236.91.3",
IPType: "Residential",
Continent: "Europe",
CountryCode: "NL",
Country: "Netherlands",
Region: "Zuid-Holland",
City: "Naaldwijk",
Latitude: "51.99417",
Longitude: "4.20972",
IPName: "customer.worldstream.nl",
Organization: "WorldStream B.V.",
ISP: "WorldStream B.V.",
Timezone: "Europe/Amsterdam",
UTCOffset: "+01:00",
Status: "success",
}
assert.Equal(t, expected, ipInfo)
}