-
Notifications
You must be signed in to change notification settings - Fork 1
/
mocker.go
210 lines (166 loc) · 4.5 KB
/
mocker.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package mocker
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
// Request is a request that can be expected by the mock server.
type Request struct {
Headers map[string][]string `json:"headers,omitempty"`
Body interface{} `json:"body,omitempty"`
Method string `json:"method"`
Path string `json:"path"`
Times int `json:"times,omitempty"`
Query map[string][]string `json:"query,omitempty"`
Response *Response `json:"response"`
Anytime bool `json:"anytime,omitempty"`
}
// Response is a response that can be expected as a response to a mock request.
type Response struct {
Headers map[string][]string `json:"headers,omitempty"`
Body interface{} `json:"body,omitempty"`
Status int `json:"status"`
}
// Results represents the results from the mock server.
type Results struct {
Expected []*Request `json:"expected"`
Unexpected []*Request `json:"unexpected"`
}
// Mocker allows to communicate with a mock server.
type Mocker struct {
BasePath string
Client *http.Client
}
// Option allows setting config.
type Option func(m *Mocker)
// WithHTTPClient sets the http client.
func WithHTTPClient(cli *http.Client) Option {
return func(m *Mocker) {
m.Client = cli
}
}
// New returns a new Mocker.
func New(basePath string, opts ...Option) *Mocker {
m := &Mocker{
basePath,
&http.Client{},
}
for _, opt := range opts {
opt(m)
}
return m
}
// Results returns both the expected and the unexpected results.
func (ms *Mocker) Results() (*Results, error) {
results := &Results{}
req, err := http.NewRequest("GET", fmt.Sprintf("%s/mocks", ms.BasePath), nil)
if err != nil {
return nil, err
}
rsp, err := ms.Client.Do(req)
if err != nil {
return nil, err
}
if rsp.StatusCode != 200 {
return nil, errors.New("failed to get mocks")
}
if err := DecodeResponse(rsp, &results); err != nil {
return nil, err
}
return results, nil
}
// Ensure ensures that no expected requests were not matched, and that there were no unexpected requests.
func (ms *Mocker) Ensure() error {
results, err := ms.Results()
if err != nil {
return err
}
var errs []string
if len(results.Expected) > 0 {
expected, err := JSONString(results.Expected)
if err != nil {
return err
}
errs = append(errs, fmt.Sprintf("missing %d expected calls: %v", len(results.Expected), expected))
}
if len(results.Unexpected) > 0 {
unexpected, err := JSONString(results.Unexpected)
if err != nil {
return err
}
errs = append(errs, fmt.Sprintf("%d unexpected calls: %v", len(results.Unexpected), unexpected))
}
if len(errs) == 0 {
return nil
}
return fmt.Errorf(strings.Join(errs, "\n"))
}
// Expect tells the actual mock server to expect the given request.
func (ms *Mocker) Expect(mock *Request) error {
body, err := json.Marshal(mock)
if err != nil {
return err
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/mocks", ms.BasePath), bytes.NewBuffer(body))
if err != nil {
return err
}
req.Header.Set("content-type", "application/json")
rsp, err := ms.Client.Do(req)
if err != nil {
return err
}
if rsp.StatusCode == 201 {
return nil
}
errs, err := JSONResponse(rsp)
if err != nil {
return err
}
return fmt.Errorf("failed to create mock %s", errs)
}
// Clear tells the actual mock server to clear all expected and unexpected requests.
func (ms *Mocker) Clear() error {
req, err := http.NewRequest("DELETE", fmt.Sprintf("%s/mocks", ms.BasePath), nil)
if err != nil {
return err
}
rsp, err := ms.Client.Do(req)
if err != nil {
return err
}
if rsp.StatusCode != 204 {
return errors.New("failed to clear mocks")
}
return nil
}
// DecodeResponse decodes the response body into the given data.
func DecodeResponse(rsp *http.Response, data interface{}) error {
defer rsp.Body.Close()
return json.NewDecoder(rsp.Body).Decode(&data)
}
// JSONResponse returns the response body as a JSON string.
func JSONResponse(rsp *http.Response) (string, error) {
defer rsp.Body.Close()
raw, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return "", err
}
var buf bytes.Buffer
json.Indent(&buf, raw, "", "\t") // nolint: errcheck
return buf.String(), nil
}
// JSONString returns the given data as a JSON string.
func JSONString(data interface{}) (string, error) {
raw, err := json.Marshal(data)
if err != nil {
return "", err
}
var buf bytes.Buffer
json.Indent(&buf, raw, "", "\t") // nolint: errcheck
return buf.String(), nil
}