-
-
Notifications
You must be signed in to change notification settings - Fork 343
/
pact.ts
286 lines (246 loc) · 7.71 KB
/
pact.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
/* eslint-disable import/first */
import { forEachObjIndexed, equals } from 'ramda';
import { makeConsumerPact } from '@pact-foundation/pact-core';
import {
ConsumerPact,
ConsumerInteraction,
} from '@pact-foundation/pact-core/src/consumer/index';
import { isArray } from 'util';
import fs = require('fs');
import { version as pactPackageVersion } from '../../package.json';
import { JsonMap } from '../common/jsonTypes';
import {
PactV3Options,
SpecificationVersion,
TemplateHeaders,
V3Interaction,
V3MockServer,
V3ProviderState,
V3Request,
V3Response,
} from './types';
import { matcherValueOrString } from './matchers';
import { MatchersV3 } from '../v3';
import { filterMissingFeatureFlag, generateMockServerError } from './display';
const readBinaryData = (file: string): Buffer => {
try {
const body = fs.readFileSync(file);
return body;
} catch (e) {
throw new Error(`unable to read file for binary request: ${e.message}`);
}
};
export class PactV3 {
private opts: PactV3Options;
private states: V3ProviderState[] = [];
private pact: ConsumerPact;
private interaction: ConsumerInteraction;
constructor(opts: PactV3Options) {
this.opts = opts;
this.setup();
}
// JSON object interface for V3, to aid with migration from the previous major version
public addInteraction(interaction: V3Interaction): PactV3 {
if (interaction.uponReceiving === '') {
throw new Error(
"must provide a valid interaction description via 'uponReceiving'"
);
}
(interaction.states || []).forEach((s) => {
this.given(s.description, s.parameters);
});
this.uponReceiving(interaction.uponReceiving);
this.withRequest(interaction.withRequest);
this.willRespondWith(interaction.willRespondWith);
return this;
}
// TODO: this currently must be called before other methods, else it won't work
public given(providerState: string, parameters?: JsonMap): PactV3 {
if (parameters) {
const json = JSON.stringify(parameters);
// undefined arguments not supported (invalid JSON)
if (json === undefined) {
throw new Error(
`Invalid provider state parameter received. Parameters must not be undefined. Received: ${parameters}`
);
}
// Check nested objects
const jsonParsed = JSON.parse(json);
if (!equals(parameters, jsonParsed)) {
throw new Error(
`Invalid provider state parameter received. Parameters must not contain undefined values. Received: ${parameters}`
);
}
}
this.states.push({ description: providerState, parameters });
return this;
}
public uponReceiving(description: string): PactV3 {
this.interaction = this.pact.newInteraction(description);
this.states.forEach((s) => {
if (s.parameters) {
forEachObjIndexed((v, k) => {
this.interaction.givenWithParam(
s.description,
`${k}`,
JSON.stringify(v)
);
}, s.parameters);
} else {
this.interaction.given(s.description);
}
});
return this;
}
public withRequest(req: V3Request): PactV3 {
if (req.body) {
this.interaction.withRequestBody(
matcherValueOrString(req.body),
req.contentType ||
contentTypeFromHeaders(req.headers, 'application/json')
);
}
setRequestDetails(this.interaction, req);
return this;
}
public withRequestBinaryFile(
req: V3Request,
contentType: string,
file: string
): PactV3 {
const body = readBinaryData(file);
this.interaction.withRequestBinaryBody(body, contentType);
setRequestDetails(this.interaction, req);
return this;
}
public withRequestMultipartFileUpload(
req: V3Request,
contentType: string,
file: string,
mimePartName: string
): PactV3 {
this.interaction.withRequestMultipartBody(contentType, file, mimePartName);
setRequestDetails(this.interaction, req);
return this;
}
public willRespondWith(res: V3Response): PactV3 {
setResponseDetails(this.interaction, res);
if (res.body) {
this.interaction.withResponseBody(
matcherValueOrString(res.body),
res.contentType ||
contentTypeFromHeaders(res.headers, 'application/json') // TODO: extract // force correct content-type header?
);
}
this.states = [];
return this;
}
public withResponseBinaryFile(
res: V3Response,
contentType: string,
file: string
): PactV3 {
const body = readBinaryData(file);
this.interaction.withResponseBinaryBody(body, contentType);
setResponseDetails(this.interaction, res);
return this;
}
public withResponseMultipartFileUpload(
res: V3Response,
contentType: string,
file: string,
mimePartName: string
): PactV3 {
this.interaction.withResponseMultipartBody(contentType, file, mimePartName);
setResponseDetails(this.interaction, res);
return this;
}
public async executeTest<T>(
testFn: (mockServer: V3MockServer) => Promise<T>
): Promise<T | undefined> {
const scheme = this.opts.tls ? 'https' : 'http';
const host = this.opts.host || '127.0.0.1';
const port = this.pact.createMockServer(
host,
this.opts.port,
this.opts.tls
);
const server = { port, url: `${scheme}://${host}:${port}`, id: 'unknown' };
let val: T | undefined;
try {
val = await testFn(server);
} catch (e) {
this.cleanup(false, server);
throw e;
}
const matchingResults = this.pact.mockServerMismatches(port);
const success = this.pact.mockServerMatchedSuccessfully(port);
// Feature flag: allow missing requests on the mock service
if (!success && filterMissingFeatureFlag(matchingResults).length > 0) {
let error = 'Test failed for the following reasons:';
error += `\n\n ${generateMockServerError(matchingResults, '\t')}`;
this.cleanup(false, server);
return Promise.reject(new Error(error));
}
this.cleanup(true, server);
return val;
}
private cleanup(success: boolean, server: V3MockServer) {
if (success) {
this.pact.writePactFile(this.opts.dir || './pacts');
}
this.pact.cleanupMockServer(server.port);
this.setup();
}
// reset the internal state
// (this.pact cannot be re-used between tests)
private setup() {
this.states = [];
this.pact = makeConsumerPact(
this.opts.consumer,
this.opts.provider,
this.opts.spec ?? SpecificationVersion.SPECIFICATION_VERSION_V3,
this.opts.logLevel ?? 'info'
);
this.pact.addMetadata('pact-js', 'version', pactPackageVersion);
}
}
const setRequestDetails = (
interaction: ConsumerInteraction,
req: V3Request
) => {
interaction.withRequest(req.method, matcherValueOrString(req.path));
forEachObjIndexed((v, k) => {
interaction.withRequestHeader(k, 0, matcherValueOrString(v));
}, req.headers);
forEachObjIndexed((v, k) => {
if (isArray(v)) {
(v as unknown[]).forEach((vv, i) => {
interaction.withQuery(k, i, matcherValueOrString(vv));
});
} else {
interaction.withQuery(k, 0, matcherValueOrString(v));
}
}, req.query);
};
const setResponseDetails = (
interaction: ConsumerInteraction,
res: V3Response
) => {
interaction.withStatus(res.status);
forEachObjIndexed((v, k) => {
interaction.withResponseHeader(k, 0, matcherValueOrString(v));
}, res.headers);
};
const contentTypeFromHeaders = (
headers: TemplateHeaders | undefined,
defaultContentType: string
) => {
let contentType: string | MatchersV3.Matcher<string> = defaultContentType;
forEachObjIndexed((v, k) => {
if (`${k}`.toLowerCase() === 'content-type') {
contentType = matcherValueOrString(v);
}
}, headers || {});
return contentType;
};