-
Notifications
You must be signed in to change notification settings - Fork 5
/
mock_http_client.go
59 lines (49 loc) · 1.48 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
package mpesa
import (
"bytes"
"io"
"net/http"
)
type mockResponseFunc func() (status int, body string)
type (
mockResponse struct {
fn mockResponseFunc
}
mockHttpClient struct {
responses map[string]mockResponse
requests []*http.Request
}
)
// mockHttpResponse returns a http.Response with the given status and body.
func mockHttpResponse(status int, body string) *http.Response {
return &http.Response{
Status: http.StatusText(status),
StatusCode: status,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Body: io.NopCloser(bytes.NewBuffer([]byte(body))),
}
}
// newMockHttpClient creates a new instance of mockHttpClient
func newMockHttpClient() *mockHttpClient {
return &mockHttpClient{
responses: make(map[string]mockResponse),
}
}
// MockRequest appends the given response for the provided url.
func (m *mockHttpClient) MockRequest(url string, fn mockResponseFunc) {
m.responses[url] = mockResponse{fn: fn}
}
// Do checks if the given req.URL exists in the available responses lists and returns the stored response.
// If none exists, it returns status http.StatusNotFound
func (m *mockHttpClient) Do(req *http.Request) (*http.Response, error) {
m.requests = append(m.requests, req.Clone(req.Context()))
if mock, ok := m.responses[req.URL.String()]; ok {
if mock.fn != nil {
status, body := mock.fn()
return mockHttpResponse(status, body), nil
}
}
return mockHttpResponse(http.StatusNotFound, http.StatusText(http.StatusNotFound)), nil
}