This repository was archived by the owner on Feb 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathyesno.ts
433 lines (370 loc) · 12.3 KB
/
yesno.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
426
427
428
429
430
431
432
433
import { IDebugger } from 'debug';
import * as _ from 'lodash';
import { EOL } from 'os';
import { YESNO_RECORDING_MODE_ENV_VAR } from './consts';
import Context, { IInFlightRequest } from './context';
import { YesNoError } from './errors';
import * as file from './file';
import FilteredHttpCollection, {
IFiltered,
PartialResponseForRequest,
} from './filtering/collection';
import { ComparatorFn } from './filtering/comparator';
import { HttpFilter, ISerializedHttpPartialDeepMatch, match, MatchFn } from './filtering/matcher';
import { redact as redactRecord, Redactor } from './filtering/redact';
import {
createRecord,
formatUrl,
ISerializedHttp,
ISerializedRequest,
ISerializedResponse,
RequestSerializer,
validateSerializedHttpArray,
} from './http-serializer';
import Interceptor, { IInterceptEvent, IInterceptOptions, IProxiedEvent } from './interceptor';
import MockResponse from './mock-response';
import Recording, { RecordMode as Mode } from './recording';
import Rule, { RuleType } from './rule';
const debug: IDebugger = require('debug')('yesno');
export type GenericTest = (...args: any) => Promise<any> | void;
export type GenericTestFunction = (title: string, fn: GenericTest) => any;
export interface IRecordableTest {
test?: GenericTestFunction;
it?: GenericTestFunction;
prefix?: string;
dir: string;
}
/**
* Options to configure intercept of HTTP requests
*/
export interface IYesNoInterceptingOptions extends IInterceptOptions {
/**
* Comparator function used to determine whether an intercepted request
* matches a loaded mock.
*/
comparatorFn?: ComparatorFn;
}
/**
* Client API for YesNo
*/
export class YesNo implements IFiltered {
private readonly interceptor: Interceptor;
private readonly ctx: Context;
constructor(ctx: Context) {
this.ctx = ctx;
this.interceptor = this.createInterceptor();
}
/**
* Restore HTTP functionality
*/
public restore(): void {
debug('Disabling intercept');
this.clear();
this.interceptor.disable();
}
/**
* Spy on intercepted requests
*/
public spy(options?: IYesNoInterceptingOptions): void {
this.enable(options);
this.setMode(Mode.Spy);
}
/**
* Set rule for mock/record
*
* @param filter to match requests
* @return new rule index
*/
public mockRule(filter: HttpFilter): Rule {
const matcher = _.isString(filter) || _.isRegExp(filter) ? { url: filter } : filter;
const rule = new Rule({ context: this.ctx, matcher });
this.ctx.rules.push(rule);
return rule;
}
/**
* Mock responses for intercepted requests
* @todo Reset the request counter?
*/
public mock(mocks: file.IHttpMock[], options?: IYesNoInterceptingOptions): void {
this.enable(options);
this.setMode(Mode.Mock);
this.setMocks(mocks.map(file.hydrateHttpMock));
}
/**
* Start a new recording.
*
* Depending on the configured mode, will either spy on all outbound HTTP requests
* or return mocks loaded from disc.
*
* When done, call the `complete()` on the returned recording
* to save all intercepted requests to disc if applicable.
* @param options Where to load/save mocks
* @returns A new recording.
*/
public async recording(options: file.IFileOptions): Promise<Recording> {
const mode = this.getModeByEnv();
if (mode !== Mode.Mock) {
this.spy();
} else {
this.mock(await this.load(options));
}
return new Recording({
...options,
getRecordsToSave: this.getRecordsToSave.bind(this),
mode,
});
}
/**
* Create a test function that will wrap its provided test in a recording.
*/
public test({ it, test, dir, prefix }: IRecordableTest): GenericTestFunction {
const runTest = test || it;
if (!runTest) {
throw new YesNoError('Missing "test" or "it" test function');
}
return (title: string, fn: GenericTest): GenericTestFunction => {
const filename = file.getMockFilename(prefix ? `${prefix}-${title}` : title, dir);
return runTest(title, async () => {
debug('Running test "%s"', title);
this.restore();
try {
const recording = await this.recording({ filename });
await fn();
debug('Saving test "%s"', filename);
await recording.complete();
} finally {
this.restore();
}
});
};
}
/**
* Load request/response mocks from disk
*/
public async load(options: file.IFileOptions): Promise<ISerializedHttp[]> {
debug('Loading mocks');
const records = await file.load(options as file.IFileOptions);
validateSerializedHttpArray(records);
return records;
}
/**
* Save intercepted requests
*
* Normally save is called by the complete method and will only succeed if there are
* no in-flight requests (i.e. all open requests have completed). However, if for some
* reason a request will not complete and you need to save the successful requests up to
* that point, you can set 'force' option to true and call this save method.
*
* @returns Full filename of saved JSON if generated
*/
public async save(options: file.ISaveOptions & file.IFileOptions): Promise<string | void> {
options.records = options.records || this.getRecordsToSave(options.force);
return file.save(options);
}
/**
* Clear all stateful information about requests.
*
* If used in a test suite, this should be called after each test.
*/
public clear() {
this.ctx.clear();
(this.interceptor as Interceptor).requestNumber = 0;
}
/**
* Create a filter collection
* @todo Convert everything to a match fn
* @param query
*/
public matching(filter?: HttpFilter): FilteredHttpCollection {
const normalizedFilter: ISerializedHttpPartialDeepMatch | MatchFn | undefined =
_.isString(filter) || _.isRegExp(filter) ? { url: filter } : filter;
return this.getCollection(normalizedFilter);
}
/**
* Get all intercepted requests
*/
public intercepted(): ISerializedHttp[] {
return this.getCollection().intercepted();
}
/**
* Get all loaded mocks
*/
public mocks(): ISerializedHttp[] {
return this.getCollection().mocks();
}
/**
* Redact property on all records
*/
public redact(property: string | string[], redactor?: Redactor): void {
if (this.getCollection().intercepted().length) {
return this.getCollection().redact(property, redactor);
}
this.ctx.autoRedact = { property, redactor };
}
private getModeByEnv(): Mode {
const env = (process.env[YESNO_RECORDING_MODE_ENV_VAR] || Mode.Mock).toLowerCase();
if (!Object.values(Mode).includes(env)) {
throw new YesNoError(
// tslint:disable-next-line:max-line-length
`Invalid mode "${env}" set for ${YESNO_RECORDING_MODE_ENV_VAR}. Must be one of ${Object.values(
Mode,
).join(', ')}`,
);
}
return env as Mode;
}
private getRecordsToSave(force: boolean = false): ISerializedHttp[] {
const inFlightRequests = this.ctx.inFlightRequests.filter((x) => x) as IInFlightRequest[];
if (inFlightRequests.length && !force) {
const urls = inFlightRequests
.map(
({ requestSerializer }) => `${requestSerializer.method}${formatUrl(requestSerializer)}`,
)
.join(EOL);
throw new YesNoError(
`Cannot save. Still have ${inFlightRequests.length} in flight requests: ${EOL}${urls}`,
);
}
return this.ctx.interceptedRequestsCompleted;
}
/**
* Enable intercepting requests
*/
private enable(options?: IYesNoInterceptingOptions): YesNo {
const { comparatorFn, ignorePorts = [] }: IYesNoInterceptingOptions = options || {};
debug('Enabling intercept. Ignoring ports', ignorePorts);
this.interceptor.enable({ ignorePorts });
this.ctx.comparatorFn = comparatorFn || this.ctx.comparatorFn;
return this;
}
private setMocks(mocks: ISerializedHttp[]): void {
validateSerializedHttpArray(mocks);
this.ctx.loadedMocks = mocks;
}
/**
* Determine the current mode
*/
private isMode(mode: Mode): boolean {
return this.ctx.mode === mode;
}
private createInterceptor() {
const interceptor = new Interceptor();
interceptor.on('intercept', this.onIntercept.bind(this));
interceptor.on('proxied', this.onProxied.bind(this));
return interceptor;
}
private async onIntercept(event: IInterceptEvent): Promise<void> {
this.recordRequest(event.requestSerializer, event.requestNumber);
const sendMockResponse = async (response?: ISerializedResponse) => {
try {
const mockResponse = new MockResponse(event, this.ctx);
const sent = await mockResponse.send(response);
if (sent) {
// redact properties if needed
if (this.ctx.autoRedact !== null) {
const properties = _.isArray(this.ctx.autoRedact.property)
? this.ctx.autoRedact.property
: [this.ctx.autoRedact.property];
const record = createRecord({
duration: 0,
request: sent.request,
response: sent.response,
});
sent.request = redactRecord(record, properties, this.ctx.autoRedact.redactor).request;
}
this.recordResponse(sent.request, sent.response, event.requestNumber);
} else if (this.isMode(Mode.Mock)) {
throw new Error('Unexpectedly failed to send mock respond');
}
} catch (e) {
if (!(e instanceof YesNoError)) {
debug(`[#${event.requestNumber}] Mock response failed unexpectedly`, e);
e.message = `YesNo: Mock response failed: ${e.message}`;
} else {
debug(`[#${event.requestNumber}] Mock response failed`, e.message);
}
event.clientRequest.emit('error', e);
}
};
// process the set of defined rules
for (const rule of this.ctx.rules) {
// see if the rule matches
const matchFound = match(rule.matcher)({ request: event.requestSerializer });
if (matchFound) {
switch (rule.ruleType) {
case RuleType.Live:
return event.proxy();
case RuleType.Respond:
if (!rule.mock) {
throw new YesNoError('Missing "response" for "mockRule.respond"');
}
const base = { body: {}, headers: {}, statusCode: 200 };
const response: ISerializedResponse =
typeof rule.mock === 'function'
? {
...base,
...rule.mock(event.requestSerializer),
}
: {
...base,
...rule.mock,
};
return sendMockResponse(response);
default:
// check for a matching mock
return sendMockResponse();
}
}
}
if (!this.ctx.hasResponsesDefinedForMatchers() && !this.isMode(Mode.Mock)) {
// No need to mock, send event to its original destination
return event.proxy();
}
// proxy requst if ignore is set
if (this.ctx.hasMatchingIgnore(event.requestSerializer)) {
return event.proxy();
}
sendMockResponse();
}
private onProxied({ requestSerializer, responseSerializer, requestNumber }: IProxiedEvent): void {
this.recordResponse(
requestSerializer.serialize(),
responseSerializer.serialize(),
requestNumber,
);
}
private setMode(mode: Mode) {
this.ctx.mode = mode;
}
private getCollection(
matcher?: ISerializedHttpPartialDeepMatch | MatchFn,
): FilteredHttpCollection {
return new FilteredHttpCollection({
context: this.ctx,
matcher,
});
}
private recordRequest(requestSerializer: RequestSerializer, requestNumber: number): void {
this.ctx.inFlightRequests[requestNumber] = {
requestSerializer,
startTime: Date.now(),
};
}
private recordResponse(
request: ISerializedRequest,
response: ISerializedResponse,
requestNumber: number,
): void {
const duration =
Date.now() - (this.ctx.inFlightRequests[requestNumber] as IInFlightRequest).startTime;
const record = createRecord({ request, response, duration });
this.ctx.interceptedRequestsCompleted[requestNumber] = record;
this.ctx.inFlightRequests[requestNumber] = null;
debug(
'Added request-response for %s %s (duration: %d)',
request.method,
record.request.host,
duration,
);
}
}