/
test.js
510 lines (422 loc) 路 12 KB
/
test.js
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
'use strict';
const concordance = require('concordance');
const observableToPromise = require('observable-to-promise');
const isPromise = require('is-promise');
const isObservable = require('is-observable');
const plur = require('plur');
const assert = require('./assert');
const nowAndTimers = require('./now-and-timers');
const concordanceOptions = require('./concordance-options').default;
function formatErrorValue(label, error) {
const formatted = concordance.format(error, concordanceOptions);
return {label, formatted};
}
const captureStack = start => {
const limitBefore = Error.stackTraceLimit;
Error.stackTraceLimit = 1;
const obj = {};
Error.captureStackTrace(obj, start);
Error.stackTraceLimit = limitBefore;
return obj.stack;
};
const assertions = assert.wrapAssertions({
pass(test) {
test.countPassedAssertion();
},
pending(test, promise) {
test.addPendingAssertion(promise);
},
fail(test, error) {
test.addFailedAssertion(error);
}
});
const assertionNames = Object.keys(assertions);
function log(...inputArgs) {
const args = inputArgs.map(value => {
return typeof value === 'string' ?
value :
concordance.format(value, concordanceOptions);
});
if (args.length > 0) {
this.addLog(args.join(' '));
}
}
function plan(count) {
this.plan(count, captureStack(this.plan));
}
function timeout(ms) {
this.timeout(ms);
}
const testMap = new WeakMap();
class ExecutionContext {
constructor(test) {
testMap.set(this, test);
const skip = () => {
test.countPassedAssertion();
};
const boundPlan = plan.bind(test);
boundPlan.skip = () => {};
Object.defineProperties(this, assertionNames.reduce((props, name) => {
props[name] = {value: assertions[name].bind(test)};
props[name].value.skip = skip;
return props;
}, {
log: {value: log.bind(test)},
plan: {value: boundPlan},
timeout: {value: timeout.bind(test)}
}));
this.snapshot.skip = () => {
test.skipSnapshot();
};
}
get end() {
const end = testMap.get(this).bindEndCallback();
const endFn = error => end(error, captureStack(endFn));
return endFn;
}
get title() {
return testMap.get(this).title;
}
get context() {
return testMap.get(this).contextRef.get();
}
set context(context) {
testMap.get(this).contextRef.set(context);
}
_throwsArgStart(assertion, file, line) {
testMap.get(this).trackThrows({assertion, file, line});
}
_throwsArgEnd() {
testMap.get(this).trackThrows(null);
}
}
class Test {
constructor(options) {
this.contextRef = options.contextRef;
this.failWithoutAssertions = options.failWithoutAssertions;
this.fn = options.fn;
this.metadata = options.metadata;
this.title = options.title;
this.logs = [];
this.snapshotInvocationCount = 0;
this.compareWithSnapshot = assertionOptions => {
const belongsTo = assertionOptions.id || this.title;
const {expected} = assertionOptions;
const index = assertionOptions.id ? 0 : this.snapshotInvocationCount++;
const label = assertionOptions.id ? '' : assertionOptions.message || `Snapshot ${this.snapshotInvocationCount}`;
return options.compareTestSnapshot({belongsTo, expected, index, label});
};
this.skipSnapshot = () => {
if (options.updateSnapshots) {
this.addFailedAssertion(new Error('Snapshot assertions cannot be skipped when updating snapshots'));
} else {
this.snapshotInvocationCount++;
this.countPassedAssertion();
}
};
this.assertCount = 0;
this.assertError = undefined;
this.calledEnd = false;
this.duration = null;
this.endCallbackFinisher = null;
this.finishDueToAttributedError = null;
this.finishDueToInactivity = null;
this.finishDueToTimeout = null;
this.finishing = false;
this.pendingAssertionCount = 0;
this.pendingThrowsAssertion = null;
this.planCount = null;
this.startedAt = 0;
this.timeoutTimer = null;
this.timeoutMs = 0;
}
bindEndCallback() {
if (this.metadata.callback) {
return (error, stack) => {
this.endCallback(error, stack);
};
}
throw new Error('`t.end()`` is not supported in this context. To use `t.end()` as a callback, you must use "callback mode" via `test.cb(testName, fn)`');
}
endCallback(error, stack) {
if (this.calledEnd) {
this.saveFirstError(new Error('`t.end()` called more than once'));
return;
}
this.calledEnd = true;
if (error) {
this.saveFirstError(new assert.AssertionError({
actual: error,
message: 'Callback called with an error',
stack,
values: [formatErrorValue('Callback called with an error:', error)]
}));
}
if (this.endCallbackFinisher) {
this.endCallbackFinisher();
}
}
createExecutionContext() {
return new ExecutionContext(this);
}
countPassedAssertion() {
if (this.finishing) {
this.saveFirstError(new Error('Assertion passed, but test has already finished'));
}
this.assertCount++;
this.refreshTimeout();
}
addLog(text) {
this.logs.push(text);
}
addPendingAssertion(promise) {
if (this.finishing) {
this.saveFirstError(new Error('Assertion passed, but test has already finished'));
}
this.assertCount++;
this.pendingAssertionCount++;
this.refreshTimeout();
promise
.catch(error => this.saveFirstError(error))
.then(() => {
this.pendingAssertionCount--;
this.refreshTimeout();
});
}
addFailedAssertion(error) {
if (this.finishing) {
this.saveFirstError(new Error('Assertion failed, but test has already finished'));
}
this.assertCount++;
this.refreshTimeout();
this.saveFirstError(error);
}
saveFirstError(error) {
if (!this.assertError) {
this.assertError = error;
}
}
plan(count, planStack) {
if (typeof count !== 'number') {
throw new TypeError('Expected a number');
}
this.planCount = count;
// In case the `planCount` doesn't match `assertCount, we need the stack of
// this function to throw with a useful stack.
this.planStack = planStack;
}
timeout(ms) {
if (this.finishing) {
return;
}
this.clearTimeout();
this.timeoutMs = ms;
this.timeoutTimer = nowAndTimers.setTimeout(() => {
this.saveFirstError(new Error('Test timeout exceeded'));
if (this.finishDueToTimeout) {
this.finishDueToTimeout();
}
}, ms);
}
refreshTimeout() {
if (!this.timeoutTimer) {
return;
}
if (this.timeoutTimer.refresh) {
this.timeoutTimer.refresh();
} else {
this.timeout(this.timeoutMs);
}
}
clearTimeout() {
nowAndTimers.clearTimeout(this.timeoutTimer);
this.timeoutTimer = null;
}
verifyPlan() {
if (!this.assertError && this.planCount !== null && this.planCount !== this.assertCount) {
this.saveFirstError(new assert.AssertionError({
assertion: 'plan',
message: `Planned for ${this.planCount} ${plur('assertion', this.planCount)}, but got ${this.assertCount}.`,
operator: '===',
stack: this.planStack
}));
}
}
verifyAssertions() {
if (!this.assertError) {
if (this.failWithoutAssertions && !this.calledEnd && this.planCount === null && this.assertCount === 0) {
this.saveFirstError(new Error('Test finished without running any assertions'));
} else if (this.pendingAssertionCount > 0) {
this.saveFirstError(new Error('Test finished, but an assertion is still pending'));
}
}
}
trackThrows(pending) {
this.pendingThrowsAssertion = pending;
}
detectImproperThrows(error) {
if (!this.pendingThrowsAssertion) {
return false;
}
const pending = this.pendingThrowsAssertion;
this.pendingThrowsAssertion = null;
const values = [];
if (error) {
values.push(formatErrorValue(`The following error was thrown, possibly before \`t.${pending.assertion}()\` could be called:`, error));
}
this.saveFirstError(new assert.AssertionError({
assertion: pending.assertion,
fixedSource: {file: pending.file, line: pending.line},
improperUsage: true,
message: `Improper usage of \`t.${pending.assertion}()\` detected`,
stack: error instanceof Error && error.stack,
values
}));
return true;
}
waitForPendingThrowsAssertion() {
return new Promise(resolve => {
this.finishDueToAttributedError = () => {
resolve(this.finishPromised());
};
this.finishDueToInactivity = () => {
this.detectImproperThrows();
resolve(this.finishPromised());
};
// Wait up to a second to see if an error can be attributed to the
// pending assertion.
nowAndTimers.setTimeout(() => this.finishDueToInactivity(), 1000).unref();
});
}
attributeLeakedError(error) {
if (!this.detectImproperThrows(error)) {
return false;
}
this.finishDueToAttributedError();
return true;
}
callFn() {
try {
return {
ok: true,
retval: this.fn.call(null, this.createExecutionContext())
};
} catch (error) {
return {
ok: false,
error
};
}
}
run() {
this.startedAt = nowAndTimers.now();
const result = this.callFn();
if (!result.ok) {
if (!this.detectImproperThrows(result.error)) {
this.saveFirstError(new assert.AssertionError({
message: 'Error thrown in test',
stack: result.error instanceof Error && result.error.stack,
values: [formatErrorValue('Error thrown in test:', result.error)]
}));
}
return this.finishPromised();
}
const returnedObservable = isObservable(result.retval);
const returnedPromise = isPromise(result.retval);
let promise;
if (returnedObservable) {
promise = observableToPromise(result.retval);
} else if (returnedPromise) {
// `retval` can be any thenable, so convert to a proper promise.
promise = Promise.resolve(result.retval);
}
if (this.metadata.callback) {
if (returnedObservable || returnedPromise) {
const asyncType = returnedObservable ? 'observables' : 'promises';
this.saveFirstError(new Error(`Do not return ${asyncType} from tests declared via \`test.cb(...)\`, if you want to return a promise simply declare the test via \`test(...)\``));
return this.finishPromised();
}
if (this.calledEnd) {
return this.finishPromised();
}
return new Promise(resolve => {
this.endCallbackFinisher = () => {
resolve(this.finishPromised());
};
this.finishDueToAttributedError = () => {
resolve(this.finishPromised());
};
this.finishDueToTimeout = () => {
resolve(this.finishPromised());
};
this.finishDueToInactivity = () => {
this.saveFirstError(new Error('`t.end()` was never called'));
resolve(this.finishPromised());
};
});
}
if (promise) {
return new Promise(resolve => {
this.finishDueToAttributedError = () => {
resolve(this.finishPromised());
};
this.finishDueToTimeout = () => {
resolve(this.finishPromised());
};
this.finishDueToInactivity = () => {
const error = returnedObservable ?
new Error('Observable returned by test never completed') :
new Error('Promise returned by test never resolved');
this.saveFirstError(error);
resolve(this.finishPromised());
};
promise
.catch(error => {
if (!this.detectImproperThrows(error)) {
this.saveFirstError(new assert.AssertionError({
message: 'Rejected promise returned by test',
stack: error instanceof Error && error.stack,
values: [formatErrorValue('Rejected promise returned by test. Reason:', error)]
}));
}
})
.then(() => resolve(this.finishPromised()));
});
}
return this.finishPromised();
}
finish() {
this.finishing = true;
if (!this.assertError && this.pendingThrowsAssertion) {
return this.waitForPendingThrowsAssertion();
}
this.clearTimeout();
this.verifyPlan();
this.verifyAssertions();
this.duration = nowAndTimers.now() - this.startedAt;
let error = this.assertError;
let passed = !error;
if (this.metadata.failing) {
passed = !passed;
if (passed) {
error = null;
} else {
error = new Error('Test was expected to fail, but succeeded, you should stop marking the test as failing');
}
}
return {
duration: this.duration,
error,
logs: this.logs,
metadata: this.metadata,
passed,
title: this.title
};
}
finishPromised() {
return new Promise(resolve => {
resolve(this.finish());
});
}
}
module.exports = Test;