-
Notifications
You must be signed in to change notification settings - Fork 73
/
mock_http_client.go
66 lines (54 loc) · 1.62 KB
/
mock_http_client.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 utils
import (
"bytes"
"context"
"io/ioutil"
"net/http"
log "github.com/sirupsen/logrus"
)
type MockHTTPClient struct {
GetCallCount int
MockDoFunc MockHTTPDoFunc
}
type MockHTTPDoFunc func(req *http.Request) (*http.Response, error)
func NewMockHTTPClient(mockDoFunc MockHTTPDoFunc) *MockHTTPClient {
c := MockHTTPClient{
MockDoFunc: mockDoFunc,
}
return &c
}
func (c *MockHTTPClient) Get(ctx context.Context, url string) ([]byte, error) {
c.GetCallCount++
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
resp, err := c.Do(req)
if err != nil {
log.Debug(err.Error())
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
func (c *MockHTTPClient) Do(req *http.Request) (*http.Response, error) {
return c.MockDoFunc(req)
}
// CreateMockHTTPDoFunc is a helper function to create mock responses for
// the MockHTTPClient. In short, it simulates the http.Client.Do() method.
func CreateMockHTTPDoFunc(mockResponse string, statusCode int, err error) MockHTTPDoFunc {
return func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: statusCode,
Body: ioutil.NopCloser(bytes.NewReader([]byte(mockResponse))),
}, err
}
}
func CreateMockGetResponse(response string, err error) func(ctx context.Context, url string) ([]byte, error) {
getFunc := func(ctx context.Context, url string) ([]byte, error) {
return ([]byte)(response), err
}
return getFunc
}
func CreateMockEmptyGetResponse() func(ctx context.Context, url string) ([]byte, error) {
return func(ctx context.Context, url string) ([]byte, error) {
return ([]byte)(""), nil
}
}