-
Notifications
You must be signed in to change notification settings - Fork 0
/
httputils_test.go
executable file
·66 lines (50 loc) · 1.54 KB
/
httputils_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
package restcountries
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
)
type ClientMock struct {
DoFunc func(*http.Request) (*http.Response, error)
}
func (c *ClientMock) Do(req *http.Request) (*http.Response, error) {
return c.DoFunc(req)
}
func TestGetUrlContentErrorEOF(t *testing.T) {
var mockedClient = &ClientMock{}
mockedClient.DoFunc = func(req *http.Request) (*http.Response, error) {
return &http.Response{}, errors.New("unexpected EOF")
}
gotContent, gotErr := getUrlContent("", mockedClient)
wantContent := ""
wantErr := "unexpected EOF"
if gotContent != wantContent {
t.Errorf("got content %s; wanted %s", gotContent, wantContent)
}
if gotErr == nil || gotErr.Error() != wantErr {
t.Errorf("got err %v; wanted %s", gotErr, wantErr)
}
}
type errReader int
func (errReader) Read(p []byte) (n int, err error) {
return 0, errors.New("test read error")
}
func TestGetUrlContentErrorRead(t *testing.T) {
// a server which returns no response but content-length:1 to cause an error
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", "1")
}))
defer server.Close()
var myClient = &http.Client{Timeout: 10 * time.Second}
gotContent, gotErr := getUrlContent(server.URL, myClient)
wantContent := ""
wantErr := "unexpected EOF"
if gotContent != wantContent {
t.Errorf("got content %s; wanted %s", gotContent, wantContent)
}
if gotErr == nil || gotErr.Error() != wantErr {
t.Errorf("got err %v; wanted %s", gotErr, wantErr)
}
}