-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_test.go
95 lines (81 loc) · 2.53 KB
/
get_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
package publicip
import (
"os"
"testing"
"github.com/stretchr/testify/require"
"github.com/jarcoal/httpmock"
"gopkg.in/resty.v1"
)
func TestMain(m *testing.M) {
//prevent execution of default client
httpmock.ActivateNonDefault(resty.DefaultClient.GetClient())
returnCode := m.Run()
httpmock.DeactivateAndReset()
os.Exit(returnCode)
}
func TestSetMirrors(t *testing.T) {
newMirrors := []string{
"https://www.google.com",
"https://www.msn.com",
}
require.NotEqual(t, newMirrors, mirrors)
SetMirrors(newMirrors)
require.Equal(t, newMirrors, mirrors, "mirrors should be overriden")
}
func TestGet(t *testing.T) {
restyClient := resty.New()
httpmock.ActivateNonDefault(restyClient.GetClient())
HttpClient = restyClient
fixture := `1.2.3.4`
responder := httpmock.NewStringResponder(503, fixture)
//lets assume that all mirrors have failed so far.
for _, url := range mirrors {
httpmock.RegisterResponder("GET", url, responder)
}
res, err := Get()
require.Equal(t, "", res)
require.Error(t, err)
require.IsType(t, MirrorsExausted{}, err)
//ok, lets return a valid result
httpmock.Reset()
responder = httpmock.NewStringResponder(200, fixture)
for _, url := range mirrors {
httpmock.RegisterResponder("GET", url, responder)
}
res, err = Get()
require.NoError(t, err)
require.Equal(t, fixture, res)
}
func TestDownload(t *testing.T) {
restyClient := resty.New()
httpmock.ActivateNonDefault(restyClient.GetClient())
res, err := download(restyClient, "")
require.Error(t, err)
require.Empty(t, res)
fixture := `error`
responder := httpmock.NewStringResponder(503, fixture)
testUrl := "https://api.ipify.org"
httpmock.RegisterResponder("GET", testUrl, responder)
res, err = download(restyClient, testUrl)
require.Error(t, err)
require.IsType(t, DownloadError{}, err)
require.Equal(t, err.(DownloadError).Url, testUrl)
require.Equal(t, err.(DownloadError).StatusCode, 503)
require.Equal(t, err.(DownloadError).Body, []byte(fixture))
//invalid response
httpmock.Reset()
fixture = `not an ip`
responder = httpmock.NewStringResponder(200, fixture)
httpmock.RegisterResponder("GET", testUrl, responder)
res, err = download(restyClient, testUrl)
require.Error(t, err)
require.IsType(t, InvalidResponseError{}, err)
require.Equal(t, err.(InvalidResponseError).Response, fixture)
httpmock.Reset()
fixture = `1.2.3.4`
responder = httpmock.NewStringResponder(200, fixture)
httpmock.RegisterResponder("GET", testUrl, responder)
res, err = download(restyClient, testUrl)
require.NoError(t, err)
require.Equal(t, fixture, res)
}