This repository has been archived by the owner on Feb 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexternal.go
377 lines (301 loc) · 9.39 KB
/
external.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package httpdog
import (
"context"
"errors"
"fmt"
"strings"
"github.com/bool64/shared"
"github.com/cucumber/godog"
"github.com/swaggest/rest/resttest"
)
type exp struct {
resttest.Expectation
async bool
}
// External is a collection of step-driven HTTP servers to serve requests of application with mocked data.
type External struct {
pending map[string]exp
mocks map[string]*resttest.ServerMock
Vars *shared.Vars
}
// RegisterSteps adds steps to godog scenario context to serve outgoing requests with mocked data.
//
// In simple case you can define expected URL and response.
//
// Given "some-service" receives "GET" request "/get-something?foo=bar"
//
// And "some-service" responds with status "OK" and body
// """
// {"key":"value"}
// """
//
// Or request with body.
//
// And "another-service" receives "POST" request "/post-something" with body
// """
// // Could be a JSON5 too.
// {"foo":"bar"}
// """
//
// Request with body from a file.
//
// And "another-service" receives "POST" request "/post-something" with body from file
// """
// _testdata/sample.json
// """
//
// Request can expect to have a header.
//
// And "some-service" request includes header "X-Foo: bar"
//
// By default, each configured request is expected to be received 1 time. This can be changed to a different number.
//
// And "some-service" request is received 1234 times
//
// Or to be unlimited.
//
// And "some-service" request is received several times
//
// By default, requests are expected in same sequential order as they are defined.
// If there is no stable order you can have an async expectation.
// Async requests are expected in any order.
//
// And "some-service" request is async
//
// Response may have a header.
//
// And "some-service" response includes header "X-Bar: foo"
//
// Response must have a status.
//
// And "some-service" responds with status "OK"
//
// Response may also have a body.
//
// And "some-service" responds with status "OK" and body
// """
// {"key":"value"}
// """
//
// Response body can also be defined in file.
//
// And "another-service" responds with status "200" and body from file
// """
// _testdata/sample.json5
// """
func (e *External) RegisterSteps(s *godog.ScenarioContext) {
e.pending = make(map[string]exp, len(e.mocks))
e.steps(s)
s.Before(func(ctx context.Context, sc *godog.Scenario) (context.Context, error) {
for _, mock := range e.mocks {
mock.ResetExpectations()
}
if e.Vars != nil {
e.Vars.Reset()
}
return ctx, nil
})
s.After(func(ctx context.Context, sc *godog.Scenario, err error) (context.Context, error) {
var errs []string
if len(e.pending) > 0 {
for service, req := range e.pending {
errs = append(errs, fmt.Sprintf("%s in %s for %s %s",
errUndefinedResponse, service, req.Method, req.RequestURI))
}
}
for service, mock := range e.mocks {
if err := mock.ExpectationsWereMet(); err != nil {
errs = append(errs, fmt.Sprintf("expectations were not met for %s: %s", service, err))
}
}
if len(errs) > 0 {
return ctx, errors.New("check failed for external services:\n" + strings.Join(errs, ",\n"))
}
return ctx, nil
})
}
func (e *External) steps(s *godog.ScenarioContext) {
// Init request expectation.
s.Step(`^"([^"]*)" receives "([^"]*)" request "([^"]*)"$`,
e.serviceReceivesRequest)
s.Step(`^"([^"]*)" receives "([^"]*)" request "([^"]*)" with body$`,
e.serviceReceivesRequestWithBody)
s.Step(`^"([^"]*)" receives "([^"]*)" request "([^"]*)" with body from file$`,
e.serviceReceivesRequestWithBodyFromFile)
// Configure request expectation.
s.Step(`^"([^"]*)" request includes header "([^"]*): ([^"]*)"$`,
e.serviceRequestIncludesHeader)
s.Step(`^"([^"]*)" request is async$`,
e.serviceRequestIsAsync)
s.Step(`^"([^"]*)" request is received several times$`,
e.serviceReceivesRequestMultipleTimes)
s.Step(`^"([^"]*)" request is received (\d+) times$`,
e.serviceReceivesRequestNTimes)
// Configure response.
s.Step(`^"([^"]*)" response includes header "([^"]*): ([^"]*)"$`,
e.serviceResponseIncludesHeader)
// Finalize request expectation.
s.Step(`^"([^"]*)" responds with status "([^"]*)"$`,
func(service, statusOrCode string) error {
return e.serviceRespondsWithStatusAndPreparedBody(service, statusOrCode, nil)
})
s.Step(`^"([^"]*)" responds with status "([^"]*)" and body$`,
e.serviceRespondsWithStatusAndBody)
s.Step(`^"([^"]*)" responds with status "([^"]*)" and body from file$`,
e.serviceRespondsWithStatusAndBodyFromFile)
}
// GetMock exposes mock of external service.
func (e *External) GetMock(service string) *resttest.ServerMock {
return e.mocks[service]
}
// Add starts a mocked server for a named service and returns url.
func (e *External) Add(service string, options ...func(mock *resttest.ServerMock)) string {
mock, url := resttest.NewServerMock()
mock.JSONComparer.Vars = e.Vars
for _, option := range options {
option(mock)
}
if e.mocks == nil {
e.mocks = make(map[string]*resttest.ServerMock, 1)
}
e.mocks[service] = mock
return url
}
func (e *External) serviceReceivesRequestWithPreparedBody(service, method, requestURI string, body []byte) error {
err := e.serviceReceivesRequest(service, method, requestURI)
if err != nil {
return err
}
pending := e.pending[service]
pending.RequestBody = body
e.pending[service] = pending
return nil
}
func (e *External) serviceRequestIncludesHeader(service, header, value string) error {
pending := e.pending[service]
if pending.Method == "" {
return fmt.Errorf("%w: %q", errUndefinedRequest, service)
}
if pending.RequestHeader == nil {
pending.RequestHeader = make(map[string]string, 1)
}
pending.RequestHeader[header] = value
e.pending[service] = pending
return nil
}
func (e *External) serviceReceivesRequestWithBody(service, method, requestURI string, bodyDoc *godog.DocString) error {
body, err := loadBody([]byte(bodyDoc.Content), e.Vars)
if err != nil {
return err
}
return e.serviceReceivesRequestWithPreparedBody(service, method, requestURI, body)
}
func (e *External) serviceReceivesRequestWithBodyFromFile(service, method, requestURI string, filePath *godog.DocString) error {
body, err := loadBodyFromFile(filePath.Content, e.Vars)
if err != nil {
return err
}
return e.serviceReceivesRequestWithPreparedBody(service, method, requestURI, body)
}
func (e *External) serviceReceivesRequest(service, method, requestURI string) error {
if _, ok := e.mocks[service]; !ok {
return fmt.Errorf("%w: %q", errNoMockForService, service)
}
pending := e.pending[service]
pending.Method = method
pending.RequestURI = requestURI
e.pending[service] = pending
return nil
}
func (e *External) serviceReceivesRequestNTimes(service string, n int) error {
if _, ok := e.mocks[service]; !ok {
return fmt.Errorf("%w: %q", errNoMockForService, service)
}
pending := e.pending[service]
if pending.Method == "" {
return fmt.Errorf("%w: %q", errUndefinedRequest, service)
}
pending.Repeated = n
e.pending[service] = pending
return nil
}
func (e *External) serviceRequestIsAsync(service string) error {
if _, ok := e.mocks[service]; !ok {
return fmt.Errorf("%w: %q", errNoMockForService, service)
}
pending := e.pending[service]
if pending.Method == "" {
return fmt.Errorf("%w: %q", errUndefinedRequest, service)
}
pending.async = true
e.pending[service] = pending
return nil
}
func (e *External) serviceReceivesRequestMultipleTimes(service string) error {
if _, ok := e.mocks[service]; !ok {
return fmt.Errorf("%w: %q", errNoMockForService, service)
}
pending := e.pending[service]
if pending.Method == "" {
return fmt.Errorf("%w: %q", errUndefinedRequest, service)
}
pending.Unlimited = true
e.pending[service] = pending
return nil
}
func (e *External) serviceRespondsWithStatusAndPreparedBody(service, statusOrCode string, body []byte) error {
m, ok := e.mocks[service]
if !ok {
return fmt.Errorf("%w: %q", errNoMockForService, service)
}
code, err := statusCode(statusOrCode)
if err != nil {
return err
}
pending := e.pending[service]
if pending.Method == "" {
return fmt.Errorf("%w: %q", errUndefinedRequest, service)
}
delete(e.pending, service)
pending.Status = code
pending.ResponseBody = body
if pending.ResponseHeader == nil {
pending.ResponseHeader = map[string]string{}
}
if pending.async {
m.ExpectAsync(pending.Expectation)
} else {
m.Expect(pending.Expectation)
}
return nil
}
func (e *External) serviceResponseIncludesHeader(service, header, value string) error {
_, ok := e.mocks[service]
if !ok {
return fmt.Errorf("%w: %q", errNoMockForService, service)
}
pending := e.pending[service]
if pending.Method == "" {
return fmt.Errorf("%w: %q", errUndefinedRequest, service)
}
if pending.ResponseHeader == nil {
pending.ResponseHeader = make(map[string]string, 1)
}
pending.ResponseHeader[header] = value
e.pending[service] = pending
return nil
}
func (e *External) serviceRespondsWithStatusAndBody(service, statusOrCode string, bodyDoc *godog.DocString) error {
body, err := loadBody([]byte(bodyDoc.Content), e.Vars)
if err != nil {
return err
}
return e.serviceRespondsWithStatusAndPreparedBody(service, statusOrCode, body)
}
func (e *External) serviceRespondsWithStatusAndBodyFromFile(service, statusOrCode string, filePath *godog.DocString) error {
body, err := loadBodyFromFile(filePath.Content, e.Vars)
if err != nil {
return err
}
return e.serviceRespondsWithStatusAndPreparedBody(service, statusOrCode, body)
}