-
-
Notifications
You must be signed in to change notification settings - Fork 349
/
Copy pathindex.ts
425 lines (359 loc) · 11 KB
/
index.ts
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/* eslint-disable */
import { ConsumerInteraction, ConsumerPact } from '@pact-foundation/pact-core';
import { JsonMap } from '../../common/jsonTypes';
import { forEachObjIndexed } from 'ramda';
import { Path, TemplateHeaders, TemplateQuery, V3MockServer } from '../../v3';
import { AnyTemplate, Matcher, matcherValueOrString } from '../../v3/matchers';
import {
PactV4Options,
PluginConfig,
V4InteractionWithCompleteRequest,
V4InteractionWithPlugin,
V4InteractionwithRequest,
V4InteractionWithResponse,
V4MockServer,
V4Request,
V4RequestBuilder,
V4RequestBuilderFunc,
V4ResponseBuilder,
V4ResponseBuilderFunc,
V4UnconfiguredInteraction,
V4Response,
V4InteractionWithPluginRequest,
V4PluginResponseBuilderFunc,
V4InteractionWithPluginResponse,
V4RequestWithPluginBuilder,
V4ResponseWithPluginBuilder,
V4PluginRequestBuilderFunc,
TestFunction,
} from './types';
import fs = require('fs');
import {
filterMissingFeatureFlag,
generateMockServerError,
} from '../../v3/display';
import logger from '../../common/logger';
type TemplateHeaderArrayValue = string[] | Matcher<string>[];
export class UnconfiguredInteraction implements V4UnconfiguredInteraction {
// tslint:disable:no-empty-function
constructor(
protected pact: ConsumerPact,
protected interaction: ConsumerInteraction,
protected opts: PactV4Options
) {}
uponReceiving(description: string): V4UnconfiguredInteraction {
this.interaction.uponReceiving(description);
return this;
}
given(state: string, parameters?: JsonMap): V4UnconfiguredInteraction {
if (parameters) {
forEachObjIndexed((v, k) => {
this.interaction.givenWithParam(state, `${k}`, JSON.stringify(v));
}, parameters);
} else {
this.interaction.given(state);
}
return this;
}
withCompleteRequest(request: V4Request): V4InteractionWithCompleteRequest {
return new InteractionWithCompleteRequest(
this.pact,
this.interaction,
this.opts
);
}
withRequest(
method: string,
path: Path,
builder?: V4RequestBuilderFunc
): V4InteractionwithRequest {
this.interaction.withRequest(method, matcherValueOrString(path));
if (builder) {
builder(new RequestBuilder(this.interaction));
}
return new InteractionwithRequest(this.pact, this.interaction, this.opts);
}
usingPlugin(config: PluginConfig): V4InteractionWithPlugin {
this.pact.addPlugin(config.plugin, config.version);
return new InteractionWithPlugin(this.pact, this.interaction, this.opts);
}
}
export class InteractionWithCompleteRequest
implements V4InteractionWithCompleteRequest
{
// tslint:disable:no-empty-function
constructor(
private pact: ConsumerPact,
private interaction: ConsumerInteraction,
private opts: PactV4Options
) {
throw Error('V4InteractionWithCompleteRequest is unimplemented');
}
withCompleteResponse(response: V4Response): V4InteractionWithResponse {
return new InteractionWithResponse(this.pact, this.interaction, this.opts);
}
}
export class InteractionwithRequest implements V4InteractionwithRequest {
// tslint:disable:no-empty-function
constructor(
private pact: ConsumerPact,
private interaction: ConsumerInteraction,
private opts: PactV4Options
) {}
willRespondWith(status: number, builder?: V4ResponseBuilderFunc) {
return new InteractionWithResponse(this.pact, this.interaction, this.opts);
}
}
export class RequestBuilder implements V4RequestBuilder {
// tslint:disable:no-empty-function
constructor(protected interaction: ConsumerInteraction) {}
query(query: TemplateQuery) {
forEachObjIndexed((v, k) => {
if (Array.isArray(v)) {
(v as unknown[]).forEach((vv, i) => {
this.interaction.withQuery(k, i, matcherValueOrString(vv));
});
} else {
this.interaction.withQuery(k, 0, matcherValueOrString(v));
}
}, query);
return this;
}
headers(headers: TemplateHeaders) {
forEachObjIndexed((v, k) => {
if (Array.isArray(v)) {
(v as TemplateHeaderArrayValue).forEach(
(header: string | Matcher<string>, index: number) => {
this.interaction.withRequestHeader(
`${k}`,
index,
matcherValueOrString(header)
);
}
);
} else {
this.interaction.withRequestHeader(`${k}`, 0, matcherValueOrString(v));
}
}, headers);
return this;
}
jsonBody(body: AnyTemplate) {
this.interaction.withRequestBody(
matcherValueOrString(body),
'application/json'
);
return this;
}
binaryFile(contentType: string, file: string) {
const body = readBinaryData(file);
this.interaction.withRequestBinaryBody(body, contentType);
return this;
}
multipartBody(contentType: string, file: string, mimePartName: string) {
this.interaction.withRequestMultipartBody(contentType, file, mimePartName);
return this;
}
body(contentType: string, body: Buffer) {
this.interaction.withRequestBinaryBody(body, contentType);
return this;
}
}
export class ResponseBuilder implements V4ResponseBuilder {
protected interaction: ConsumerInteraction;
// tslint:disable:no-empty-function
constructor(interaction: ConsumerInteraction) {
this.interaction = interaction;
}
headers(headers: TemplateHeaders) {
forEachObjIndexed((v, k) => {
this.interaction.withResponseHeader(`${k}`, 0, matcherValueOrString(v));
}, headers);
return this;
}
jsonBody(body: AnyTemplate) {
this.interaction.withResponseBody(
matcherValueOrString(body),
'application/json'
);
return this;
}
binaryFile(contentType: string, file: string) {
const body = readBinaryData(file);
this.interaction.withResponseBinaryBody(body, contentType);
return this;
}
multipartBody(contentType: string, file: string, mimePartName: string) {
this.interaction.withResponseMultipartBody(contentType, file, mimePartName);
return this;
}
body(contentType: string, body: Buffer) {
this.interaction.withResponseBinaryBody(body, contentType);
return this;
}
}
export class InteractionWithResponse implements V4InteractionWithResponse {
// tslint:disable:no-empty-function
constructor(
private pact: ConsumerPact,
private interaction: ConsumerInteraction,
private opts: PactV4Options
) {}
async executeTest<T>(testFn: TestFunction<T>) {
return executeTest(this.pact, this.opts, testFn);
}
}
export class InteractionWithPlugin implements V4InteractionWithPlugin {
// tslint:disable:no-empty-function
constructor(
private pact: ConsumerPact,
private interaction: ConsumerInteraction,
private opts: PactV4Options
) {}
// Multiple plugins are allowed
usingPlugin(config: PluginConfig): V4InteractionWithPlugin {
this.pact.addPlugin(config.plugin, config.version);
return this;
}
withRequest(
method: string,
path: Path,
builder?: V4PluginRequestBuilderFunc
): V4InteractionWithPluginRequest {
this.interaction.withRequest(method, matcherValueOrString(path));
if (typeof builder === 'function') {
builder(new RequestWithPluginBuilder(this.interaction));
}
return new InteractionWithPluginRequest(
this.pact,
this.interaction,
this.opts
);
}
}
export class InteractionWithPluginRequest
implements V4InteractionWithPluginRequest
{
// tslint:disable:no-empty-function
constructor(
private pact: ConsumerPact,
private interaction: ConsumerInteraction,
private opts: PactV4Options
) {}
willRespondWith(
status: number,
builder?: V4PluginResponseBuilderFunc
): V4InteractionWithPluginResponse {
if (typeof builder === 'function') {
builder(new ResponseWithPluginBuilder(this.interaction));
}
return new InteractionWithPluginResponse(
this.pact,
this.interaction,
this.opts
);
}
}
export class RequestWithPluginBuilder
extends RequestBuilder
implements V4RequestWithPluginBuilder
{
pluginContents(
contentType: string,
contents: string
): V4RequestWithPluginBuilder {
this.interaction.withPluginRequestInteractionContents(
contentType,
contents
);
return this;
}
}
export class ResponseWithPluginBuilder
extends ResponseBuilder
implements V4ResponseWithPluginBuilder
{
pluginContents(contentType: string, contents: string): V4ResponseBuilder {
this.interaction.withPluginResponseInteractionContents(
contentType,
contents
);
return this;
}
}
export class InteractionWithPluginResponse
implements V4InteractionWithPluginResponse
{
// tslint:disable:no-empty-function
constructor(
private pact: ConsumerPact,
private interaction: ConsumerInteraction,
private opts: PactV4Options
) {}
async executeTest<T>(testFn: (mockServer: V4MockServer) => Promise<T>) {
return executeTest(this.pact, this.opts, testFn);
}
}
const readBinaryData = (file: string): Buffer => {
try {
const body = fs.readFileSync(file);
return body;
} catch (e) {
throw new Error(`unable to read file for binary payload : ${e.message}`);
}
};
const cleanup = (
success: boolean,
pact: ConsumerPact,
opts: PactV4Options,
server: V3MockServer
) => {
if (success) {
pact.writePactFile(opts.dir || './pacts');
}
pact.cleanupMockServer(server.port);
pact.cleanupPlugins();
};
const executeTest = async <T>(
pact: ConsumerPact,
opts: PactV4Options,
testFn: TestFunction<T>
) => {
const scheme = opts.tls ? 'https' : 'http';
const host = opts.host || '127.0.0.1';
const port = pact.createMockServer(host, opts.port || 0, false);
const server = { port, url: `${scheme}://${host}:${port}`, id: 'unknown' };
let val: T | undefined;
let error: Error | undefined;
try {
val = await testFn(server);
} catch (e) {
error = e;
}
const matchingResults = pact.mockServerMismatches(port);
const errors = filterMissingFeatureFlag(matchingResults);
const success = pact.mockServerMatchedSuccessfully(port);
// Scenario: Pact validation failed
if (!success && errors.length > 0) {
let errorMessage = 'Test failed for the following reasons:';
errorMessage += `\n\n ${generateMockServerError(matchingResults, '\t')}`;
cleanup(false, pact, opts, server);
// If the tests throws an error, we need to rethrow the error, but print out
// any additional mock server errors to help the user understand what happened
// (The proximate cause here is often the HTTP 500 from the mock server,
// where the HTTP client then throws)
if (error) {
logger.error(errorMessage);
throw error;
}
// Test didn't throw, so we need to ensure the test fails
return Promise.reject(new Error(errorMessage));
}
// Scenario: test threw an error, but Pact validation was OK (error in client or test)
if (error) {
cleanup(false, pact, opts, server);
throw error;
}
// Scenario: Pact validation passed, test didn't throw - return the callback value
cleanup(true, pact, opts, server);
return val;
};