-
Notifications
You must be signed in to change notification settings - Fork 30.9k
/
Copy pathtest.js
1362 lines (1173 loc) Β· 36.9 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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const {
ArrayPrototypePush,
ArrayPrototypePushApply,
ArrayPrototypeReduce,
ArrayPrototypeShift,
ArrayPrototypeSlice,
ArrayPrototypeSome,
ArrayPrototypeSplice,
ArrayPrototypeUnshift,
ArrayPrototypeUnshiftApply,
FunctionPrototype,
MathMax,
Number,
NumberPrototypeToFixed,
ObjectDefineProperty,
ObjectSeal,
Promise,
PromisePrototypeThen,
PromiseResolve,
PromiseWithResolvers,
ReflectApply,
RegExpPrototypeExec,
SafeMap,
SafePromiseAll,
SafePromiseAllReturnVoid,
SafePromisePrototypeFinally,
SafePromiseRace,
SafeSet,
StringPrototypeStartsWith,
StringPrototypeTrim,
Symbol,
SymbolDispose,
} = primordials;
const { getCallerLocation } = internalBinding('util');
const { exitCodes: { kGenericUserError } } = internalBinding('errors');
const { addAbortListener } = require('internal/events/abort_listener');
const { queueMicrotask } = require('internal/process/task_queues');
const { AsyncResource } = require('async_hooks');
const { AbortController } = require('internal/abort_controller');
const {
AbortError,
codes: {
ERR_INVALID_ARG_TYPE,
ERR_TEST_FAILURE,
},
} = require('internal/errors');
const { MockTracker } = require('internal/test_runner/mock/mock');
const { TestsStream } = require('internal/test_runner/tests_stream');
const {
createDeferredCallback,
countCompletedTest,
isTestFailureError,
reporterScope,
} = require('internal/test_runner/utils');
const {
kEmptyObject,
once: runOnce,
} = require('internal/util');
const { isPromise } = require('internal/util/types');
const {
validateAbortSignal,
validateNumber,
validateOneOf,
validateUint32,
} = require('internal/validators');
const { setTimeout } = require('timers');
const { TIMEOUT_MAX } = require('internal/timers');
const { fileURLToPath } = require('internal/url');
const { availableParallelism } = require('os');
const { innerOk } = require('internal/assert/utils');
const { bigint: hrtime } = process.hrtime;
const kCallbackAndPromisePresent = 'callbackAndPromisePresent';
const kCancelledByParent = 'cancelledByParent';
const kAborted = 'testAborted';
const kParentAlreadyFinished = 'parentAlreadyFinished';
const kSubtestsFailed = 'subtestsFailed';
const kTestCodeFailure = 'testCodeFailure';
const kTestTimeoutFailure = 'testTimeoutFailure';
const kHookFailure = 'hookFailed';
const kDefaultTimeout = null;
const noop = FunctionPrototype;
const kShouldAbort = Symbol('kShouldAbort');
const kHookNames = ObjectSeal(['before', 'after', 'beforeEach', 'afterEach']);
const kUnwrapErrors = new SafeSet()
.add(kTestCodeFailure).add(kHookFailure)
.add('uncaughtException').add('unhandledRejection');
let kResistStopPropagation;
let assertObj;
let findSourceMap;
let noopTestStream;
const kRunOnceOptions = { __proto__: null, preserveReturnValue: true };
function lazyFindSourceMap(file) {
if (findSourceMap === undefined) {
({ findSourceMap } = require('internal/source_map/source_map_cache'));
}
return findSourceMap(file);
}
function lazyAssertObject(harness) {
if (assertObj === undefined) {
assertObj = new SafeMap();
const assert = require('assert');
const methodsToCopy = [
'atLeast',
'atMost',
'deepEqual',
'deepStrictEqual',
'doesNotMatch',
'doesNotReject',
'doesNotThrow',
'equal',
'fail',
'greaterThan',
'ifError',
'lessThan',
'match',
'notDeepEqual',
'notDeepStrictEqual',
'notEqual',
'notStrictEqual',
'rejects',
'strictEqual',
'throws',
];
for (let i = 0; i < methodsToCopy.length; i++) {
assertObj.set(methodsToCopy[i], assert[methodsToCopy[i]]);
}
const { getOptionValue } = require('internal/options');
if (getOptionValue('--experimental-test-snapshots')) {
const { SnapshotManager } = require('internal/test_runner/snapshot');
harness.snapshotManager = new SnapshotManager(harness.config.updateSnapshots);
assertObj.set('snapshot', harness.snapshotManager.createAssert());
}
}
return assertObj;
}
function stopTest(timeout, signal) {
const deferred = PromiseWithResolvers();
const abortListener = addAbortListener(signal, deferred.resolve);
let timer;
let disposeFunction;
if (timeout === kDefaultTimeout) {
disposeFunction = abortListener[SymbolDispose];
} else {
timer = setTimeout(() => deferred.resolve(), timeout);
timer.unref();
ObjectDefineProperty(deferred, 'promise', {
__proto__: null,
configurable: true,
writable: true,
value: PromisePrototypeThen(deferred.promise, () => {
throw new ERR_TEST_FAILURE(
`test timed out after ${timeout}ms`,
kTestTimeoutFailure,
);
}),
});
disposeFunction = () => {
abortListener[SymbolDispose]();
timer[SymbolDispose]();
};
}
ObjectDefineProperty(deferred.promise, SymbolDispose, {
__proto__: null,
configurable: true,
writable: true,
value: disposeFunction,
});
return deferred.promise;
}
function testMatchesPattern(test, patterns) {
const matchesByNameOrParent = ArrayPrototypeSome(patterns, (re) =>
RegExpPrototypeExec(re, test.name) !== null,
) || (test.parent && testMatchesPattern(test.parent, patterns));
if (matchesByNameOrParent) return true;
const testNameWithAncestors = StringPrototypeTrim(test.getTestNameWithAncestors());
return ArrayPrototypeSome(patterns, (re) =>
RegExpPrototypeExec(re, testNameWithAncestors) !== null,
);
}
class TestPlan {
constructor(count) {
validateUint32(count, 'count');
this.expected = count;
this.actual = 0;
}
check() {
if (this.actual !== this.expected) {
throw new ERR_TEST_FAILURE(
`plan expected ${this.expected} assertions but received ${this.actual}`,
kTestCodeFailure,
);
}
}
}
class TestContext {
#assert;
#test;
constructor(test) {
this.#test = test;
}
get signal() {
return this.#test.signal;
}
get name() {
return this.#test.name;
}
get filePath() {
return this.#test.entryFile;
}
get fullName() {
return getFullName(this.#test);
}
get error() {
return this.#test.error;
}
get passed() {
return this.#test.passed;
}
diagnostic(message) {
this.#test.diagnostic(message);
}
plan(count) {
if (this.#test.plan !== null) {
throw new ERR_TEST_FAILURE(
'cannot set plan more than once',
kTestCodeFailure,
);
}
this.#test.plan = new TestPlan(count);
}
get assert() {
if (this.#assert === undefined) {
const { plan } = this.#test;
const map = lazyAssertObject(this.#test.root.harness);
const assert = { __proto__: null };
this.#assert = assert;
map.forEach((method, name) => {
assert[name] = (...args) => {
if (plan !== null) {
plan.actual++;
}
return ReflectApply(method, this, args);
};
});
// This is a hack. It allows the innerOk function to collect the stacktrace from the correct starting point.
function ok(...args) {
if (plan !== null) {
plan.actual++;
}
innerOk(ok, args.length, ...args);
}
assert.ok = ok;
}
return this.#assert;
}
get mock() {
this.#test.mock ??= new MockTracker();
return this.#test.mock;
}
runOnly(value) {
this.#test.runOnlySubtests = !!value;
}
skip(message) {
this.#test.skip(message);
}
todo(message) {
this.#test.todo(message);
}
test(name, options, fn) {
const overrides = {
__proto__: null,
loc: getCallerLocation(),
};
const { plan } = this.#test;
if (plan !== null) {
plan.actual++;
}
const subtest = this.#test.createSubtest(
// eslint-disable-next-line no-use-before-define
Test, name, options, fn, overrides,
);
return subtest.start();
}
before(fn, options) {
this.#test.createHook('before', fn, {
__proto__: null,
...options,
parent: this.#test,
hookType: 'before',
loc: getCallerLocation(),
});
}
after(fn, options) {
this.#test.createHook('after', fn, {
__proto__: null,
...options,
parent: this.#test,
hookType: 'after',
loc: getCallerLocation(),
});
}
beforeEach(fn, options) {
this.#test.createHook('beforeEach', fn, {
__proto__: null,
...options,
parent: this.#test,
hookType: 'beforeEach',
loc: getCallerLocation(),
});
}
afterEach(fn, options) {
this.#test.createHook('afterEach', fn, {
__proto__: null,
...options,
parent: this.#test,
hookType: 'afterEach',
loc: getCallerLocation(),
});
}
}
class SuiteContext {
#suite;
constructor(suite) {
this.#suite = suite;
}
get signal() {
return this.#suite.signal;
}
get name() {
return this.#suite.name;
}
get filePath() {
return this.#suite.entryFile;
}
get fullName() {
return getFullName(this.#suite);
}
}
class Test extends AsyncResource {
abortController;
outerSignal;
#reportedSubtest;
constructor(options) {
super('Test');
let { fn, name, parent } = options;
const { concurrency, entryFile, loc, only, timeout, todo, skip, signal, plan } = options;
if (typeof fn !== 'function') {
fn = noop;
}
if (typeof name !== 'string' || name === '') {
name = fn.name || '<anonymous>';
}
if (!(parent instanceof Test)) {
parent = null;
}
this.name = name;
this.parent = parent;
this.testNumber = 0;
this.outputSubtestCount = 0;
this.diagnostics = [];
this.filtered = false;
this.filteredByName = false;
this.hasOnlyTests = false;
if (parent === null) {
this.root = this;
this.harness = options.harness;
this.config = this.harness.config;
this.concurrency = 1;
this.nesting = 0;
this.only = this.config.only;
this.reporter = new TestsStream();
this.runOnlySubtests = this.only;
this.childNumber = 0;
this.timeout = kDefaultTimeout;
this.entryFile = entryFile;
} else {
const nesting = parent.parent === null ? parent.nesting :
parent.nesting + 1;
const { config, isFilteringByName, isFilteringByOnly } = parent.root.harness;
this.root = parent.root;
this.harness = null;
this.config = config;
this.concurrency = parent.concurrency;
this.nesting = nesting;
this.only = only;
this.reporter = parent.reporter;
this.runOnlySubtests = false;
this.childNumber = parent.subtests.length + 1;
this.timeout = parent.timeout;
this.entryFile = parent.entryFile;
if (isFilteringByName) {
this.filteredByName = this.willBeFilteredByName();
if (!this.filteredByName) {
for (let t = this.parent; t !== null && t.filteredByName; t = t.parent) {
t.filteredByName = false;
}
}
}
if (isFilteringByOnly) {
if (this.only) {
// If filtering impacts the tests within a suite, then the suite only
// runs those tests. If filtering does not impact the tests within a
// suite, then all tests are run.
this.parent.runOnlySubtests = true;
if (this.parent === this.root || this.parent.startTime === null) {
for (let t = this.parent; t !== null && !t.hasOnlyTests; t = t.parent) {
t.hasOnlyTests = true;
}
}
} else if (this.only === false) {
fn = noop;
}
} else if (only || this.parent.runOnlySubtests) {
const warning =
"'only' and 'runOnly' require the --test-only command-line option.";
this.diagnostic(warning);
}
}
switch (typeof concurrency) {
case 'number':
validateUint32(concurrency, 'options.concurrency', true);
this.concurrency = concurrency;
break;
case 'boolean':
if (concurrency) {
this.concurrency = parent === null ?
MathMax(availableParallelism() - 1, 1) : Infinity;
} else {
this.concurrency = 1;
}
break;
default:
if (concurrency != null)
throw new ERR_INVALID_ARG_TYPE('options.concurrency', ['boolean', 'number'], concurrency);
}
if (timeout != null && timeout !== Infinity) {
validateNumber(timeout, 'options.timeout', 0, TIMEOUT_MAX);
this.timeout = timeout;
}
if (skip) {
fn = noop;
}
this.abortController = new AbortController();
this.outerSignal = signal;
this.signal = this.abortController.signal;
validateAbortSignal(signal, 'options.signal');
if (signal) {
kResistStopPropagation ??= require('internal/event_target').kResistStopPropagation;
}
this.outerSignal?.addEventListener(
'abort',
this.#abortHandler,
{ __proto__: null, [kResistStopPropagation]: true },
);
this.fn = fn;
this.mock = null;
this.plan = null;
this.expectedAssertions = plan;
this.cancelled = false;
this.skipped = skip !== undefined && skip !== false;
this.isTodo = todo !== undefined && todo !== false;
this.startTime = null;
this.endTime = null;
this.passed = false;
this.error = null;
this.message = typeof skip === 'string' ? skip :
typeof todo === 'string' ? todo : null;
this.activeSubtests = 0;
this.pendingSubtests = [];
this.readySubtests = new SafeMap();
this.subtests = [];
this.waitingOn = 0;
this.finished = false;
this.hooks = {
__proto__: null,
before: [],
after: [],
beforeEach: [],
afterEach: [],
ownAfterEachCount: 0,
};
if (loc === undefined) {
this.loc = undefined;
} else {
this.loc = {
__proto__: null,
line: loc[0],
column: loc[1],
file: loc[2],
};
if (this.config.sourceMaps === true) {
const map = lazyFindSourceMap(this.loc.file);
const entry = map?.findEntry(this.loc.line - 1, this.loc.column - 1);
if (entry?.originalSource !== undefined) {
this.loc.line = entry.originalLine + 1;
this.loc.column = entry.originalColumn + 1;
this.loc.file = entry.originalSource;
}
}
if (StringPrototypeStartsWith(this.loc.file, 'file://')) {
this.loc.file = fileURLToPath(this.loc.file);
}
}
}
applyFilters() {
if (this.error) {
// Never filter out errors.
return;
}
if (this.filteredByName) {
this.filtered = true;
return;
}
if (this.root.harness.isFilteringByOnly && !this.only && !this.hasOnlyTests) {
if (this.parent.runOnlySubtests ||
this.parent.hasOnlyTests ||
this.only === false) {
this.filtered = true;
}
}
}
willBeFilteredByName() {
const { testNamePatterns, testSkipPatterns } = this.config;
if (testNamePatterns && !testMatchesPattern(this, testNamePatterns)) {
return true;
}
if (testSkipPatterns && testMatchesPattern(this, testSkipPatterns)) {
return true;
}
return false;
}
/**
* Returns a name of the test prefixed by name of all its ancestors in ascending order, separated by a space
* Ex."grandparent parent test"
*
* It's needed to match a single test with non-unique name by pattern
*/
getTestNameWithAncestors() {
if (!this.parent) return '';
return `${this.parent.getTestNameWithAncestors()} ${this.name}`;
}
hasConcurrency() {
return this.concurrency > this.activeSubtests;
}
addPendingSubtest(deferred) {
ArrayPrototypePush(this.pendingSubtests, deferred);
}
async processPendingSubtests() {
while (this.pendingSubtests.length > 0 && this.hasConcurrency()) {
const deferred = ArrayPrototypeShift(this.pendingSubtests);
const test = deferred.test;
test.reporter.dequeue(test.nesting, test.loc, test.name);
await test.run();
deferred.resolve();
}
}
addReadySubtest(subtest) {
this.readySubtests.set(subtest.childNumber, subtest);
}
processReadySubtestRange(canSend) {
const start = this.waitingOn;
const end = start + this.readySubtests.size;
for (let i = start; i < end; i++) {
const subtest = this.readySubtests.get(i);
// Check if the specified subtest is in the map. If it is not, return
// early to avoid trying to process any more tests since they would be
// out of order.
if (subtest === undefined) {
return;
}
// Call isClearToSend() in the loop so that it is:
// - Only called if there are results to report in the correct order.
// - Guaranteed to only be called a maximum of once per call to
// processReadySubtestRange().
canSend ||= this.isClearToSend();
if (!canSend) {
return;
}
// Report the subtest's results and remove it from the ready map.
subtest.finalize();
this.readySubtests.delete(i);
}
}
createSubtest(Factory, name, options, fn, overrides) {
if (typeof name === 'function') {
fn = name;
} else if (name !== null && typeof name === 'object') {
fn = options;
options = name;
} else if (typeof options === 'function') {
fn = options;
}
if (options === null || typeof options !== 'object') {
options = kEmptyObject;
}
let parent = this;
// If this test has already ended, attach this test to the root test so
// that the error can be properly reported.
const preventAddingSubtests = this.finished || this.buildPhaseFinished;
if (preventAddingSubtests) {
while (parent.parent !== null) {
parent = parent.parent;
}
}
const test = new Factory({ __proto__: null, fn, name, parent, ...options, ...overrides });
if (parent.waitingOn === 0) {
parent.waitingOn = test.childNumber;
}
if (preventAddingSubtests) {
test.fail(
new ERR_TEST_FAILURE(
'test could not be started because its parent finished',
kParentAlreadyFinished,
),
);
}
ArrayPrototypePush(parent.subtests, test);
return test;
}
#abortHandler = () => {
const error = this.outerSignal?.reason || new AbortError('The test was aborted');
error.failureType = kAborted;
this.#cancel(error);
};
#cancel(error) {
if (this.endTime !== null || this.error !== null) {
return;
}
this.fail(error ||
new ERR_TEST_FAILURE(
'test did not finish before its parent and was cancelled',
kCancelledByParent,
),
);
this.cancelled = true;
this.abortController.abort();
}
computeInheritedHooks() {
if (this.parent.hooks.beforeEach.length > 0) {
ArrayPrototypeUnshiftApply(
this.hooks.beforeEach,
ArrayPrototypeSlice(this.parent.hooks.beforeEach),
);
}
if (this.parent.hooks.afterEach.length > 0) {
ArrayPrototypePushApply(
this.hooks.afterEach, ArrayPrototypeSlice(this.parent.hooks.afterEach),
);
}
}
createHook(name, fn, options) {
validateOneOf(name, 'hook name', kHookNames);
// eslint-disable-next-line no-use-before-define
const hook = new TestHook(fn, options);
if (name === 'before' || name === 'after') {
hook.run = runOnce(hook.run, kRunOnceOptions);
}
if (name === 'before' && this.startTime !== null) {
// Test has already started, run the hook immediately
PromisePrototypeThen(hook.run(this.getRunArgs()), () => {
if (hook.error != null) {
this.fail(hook.error);
}
});
}
if (name === 'afterEach') {
// afterEach hooks for the current test should run in the order that they
// are created. However, the current test's afterEach hooks should run
// prior to any ancestor afterEach hooks.
ArrayPrototypeSplice(this.hooks[name], this.hooks.ownAfterEachCount, 0, hook);
this.hooks.ownAfterEachCount++;
} else {
ArrayPrototypePush(this.hooks[name], hook);
}
}
fail(err) {
if (this.error !== null) {
return;
}
this.passed = false;
this.error = err;
}
pass() {
if (this.error !== null) {
return;
}
this.passed = true;
}
skip(message) {
this.skipped = true;
this.message = message;
}
todo(message) {
this.isTodo = true;
this.message = message;
}
diagnostic(message) {
ArrayPrototypePush(this.diagnostics, message);
}
start() {
this.applyFilters();
if (this.filtered) {
noopTestStream ??= new TestsStream();
this.reporter = noopTestStream;
this.run = this.filteredRun;
} else {
this.testNumber = ++this.parent.outputSubtestCount;
}
// If there is enough available concurrency to run the test now, then do
// it. Otherwise, return a Promise to the caller and mark the test as
// pending for later execution.
this.reporter.enqueue(this.nesting, this.loc, this.name);
if (this.root.harness.buildPromise || !this.parent.hasConcurrency()) {
const deferred = PromiseWithResolvers();
deferred.test = this;
this.parent.addPendingSubtest(deferred);
return deferred.promise;
}
this.reporter.dequeue(this.nesting, this.loc, this.name);
return this.run();
}
[kShouldAbort]() {
if (this.signal.aborted || this.outerSignal?.aborted) {
this.#abortHandler();
return true;
}
}
getRunArgs() {
const ctx = new TestContext(this);
return { __proto__: null, ctx, args: [ctx] };
}
async runHook(hook, args) {
validateOneOf(hook, 'hook name', kHookNames);
try {
await ArrayPrototypeReduce(this.hooks[hook], async (prev, hook) => {
await prev;
await hook.run(args);
if (hook.error) {
throw hook.error;
}
}, PromiseResolve());
} catch (err) {
const error = new ERR_TEST_FAILURE(`failed running ${hook} hook`, kHookFailure);
error.cause = isTestFailureError(err) ? err.cause : err;
throw error;
}
}
async filteredRun() {
this.pass();
this.subtests = [];
this.report = noop;
queueMicrotask(() => this.postRun());
}
async run() {
if (this.parent !== null) {
this.parent.activeSubtests++;
this.computeInheritedHooks();
}
this.startTime ??= hrtime();
if (this[kShouldAbort]()) {
this.postRun();
return;
}
const hookArgs = this.getRunArgs();
const { args, ctx } = hookArgs;
if (this.plan === null && this.expectedAssertions) {
ctx.plan(this.expectedAssertions);
}
const after = async () => {
if (this.hooks.after.length > 0) {
await this.runHook('after', hookArgs);
}
};
const afterEach = runOnce(async () => {
if (this.parent?.hooks.afterEach.length > 0 && !this.skipped) {
await this.parent.runHook('afterEach', hookArgs);
}
}, kRunOnceOptions);
let stopPromise;
try {
if (this.parent?.hooks.before.length > 0) {
// This hook usually runs immediately, we need to wait for it to finish
await this.parent.runHook('before', this.parent.getRunArgs());
}
if (this.parent?.hooks.beforeEach.length > 0 && !this.skipped) {
await this.parent.runHook('beforeEach', hookArgs);
}
stopPromise = stopTest(this.timeout, this.signal);
const runArgs = ArrayPrototypeSlice(args);
ArrayPrototypeUnshift(runArgs, this.fn, ctx);
if (this.fn.length === runArgs.length - 1) {
// This test is using legacy Node.js error first callbacks.
const { promise, cb } = createDeferredCallback();
ArrayPrototypePush(runArgs, cb);
const ret = ReflectApply(this.runInAsyncScope, this, runArgs);
if (isPromise(ret)) {
this.fail(new ERR_TEST_FAILURE(
'passed a callback but also returned a Promise',
kCallbackAndPromisePresent,
));
await SafePromiseRace([ret, stopPromise]);
} else {
await SafePromiseRace([PromiseResolve(promise), stopPromise]);
}
} else {
// This test is synchronous or using Promises.
const promise = ReflectApply(this.runInAsyncScope, this, runArgs);
await SafePromiseRace([PromiseResolve(promise), stopPromise]);
}
this[kShouldAbort]();
this.plan?.check();
this.pass();
await afterEach();
await after();
} catch (err) {
if (isTestFailureError(err)) {
if (err.failureType === kTestTimeoutFailure) {
this.#cancel(err);
} else {
this.fail(err);
}
} else {
this.fail(new ERR_TEST_FAILURE(err, kTestCodeFailure));
}
try { await afterEach(); } catch { /* test is already failing, let's ignore the error */ }
try { await after(); } catch { /* Ignore error. */ }
} finally {
stopPromise?.[SymbolDispose]();
// Do not abort hooks and the root test as hooks instance are shared between tests suite so aborting them will
// cause them to not run for further tests.
if (this.parent !== null) {
this.abortController.abort();
}
}
if (this.parent !== null || typeof this.hookType === 'string') {
// Clean up the test. Then, try to report the results and execute any
// tests that were pending due to available concurrency.
//
// The root test is skipped here because it is a special case. Its
// postRun() method is called when the process is getting ready to exit.
// This helps catch any asynchronous activity that occurs after the tests
// have finished executing.
this.postRun();
} else if (this.config.forceExit) {
// This is the root test, and all known tests and hooks have finished
// executing. If the user wants to force exit the process regardless of
// any remaining ref'ed handles, then do that now. It is theoretically
// possible that a ref'ed handle could asynchronously create more tests,
// but the user opted into this behavior.
const promises = [];
for (let i = 0; i < reporterScope.reporters.length; i++) {
const { destination } = reporterScope.reporters[i];
ArrayPrototypePush(promises, new Promise((resolve) => {
destination.on('unpipe', () => {
if (!destination.closed && typeof destination.close === 'function') {
destination.close(resolve);
} else {
resolve();
}
});
}));
}
this.harness.teardown();