-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock.go
74 lines (63 loc) · 1.76 KB
/
mock.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
package httpmock
import (
"bytes"
"io/ioutil"
"net/http"
"strings"
)
// Response is to mock the HTTP response
// to use with the MockClient
type MultiResponse []*Response
type Response struct {
URI string
Body string
StatusCode int
}
type RoundTripFunc func(req *http.Request) *http.Response
func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}
// Client create the mock http.client type
// to mock HTTP response with a given MockResponse type
func Client(response *Response) *http.Client {
fn := func(req *http.Request) *http.Response {
if strings.Contains(req.URL.String(), response.URI) {
return &http.Response{
StatusCode: response.StatusCode,
Body: ioutil.NopCloser(strings.NewReader(response.Body)),
Header: make(http.Header),
}
}
return &http.Response{
StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(bytes.NewBufferString("Resource not found")),
Header: make(http.Header),
}
}
return &http.Client{
Transport: RoundTripFunc(fn),
}
}
// MultiResponseClient create the mock http.client type
// to mock HTTP response with a given MockResponse type
func MultiResponseClient(response MultiResponse) *http.Client {
fn := func(req *http.Request) *http.Response {
for _, r := range response {
if strings.HasSuffix(req.URL.String(), r.URI) {
return &http.Response{
StatusCode: r.StatusCode,
Body: ioutil.NopCloser(strings.NewReader(r.Body)),
Header: make(http.Header),
}
}
}
return &http.Response{
StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(bytes.NewBufferString("Resource not found")),
Header: make(http.Header),
}
}
return &http.Client{
Transport: RoundTripFunc(fn),
}
}