-
Notifications
You must be signed in to change notification settings - Fork 323
/
Copy pathvitest.js
768 lines (671 loc) · 24.2 KB
/
vitest.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
const { addHook, channel, AsyncResource } = require('./helpers/instrument')
const shimmer = require('../../datadog-shimmer')
const log = require('../../dd-trace/src/log')
// test hooks
const testStartCh = channel('ci:vitest:test:start')
const testFinishTimeCh = channel('ci:vitest:test:finish-time')
const testPassCh = channel('ci:vitest:test:pass')
const testErrorCh = channel('ci:vitest:test:error')
const testSkipCh = channel('ci:vitest:test:skip')
const isNewTestCh = channel('ci:vitest:test:is-new')
const isDisabledCh = channel('ci:vitest:test:is-disabled')
const isQuarantinedCh = channel('ci:vitest:test:is-quarantined')
// test suite hooks
const testSuiteStartCh = channel('ci:vitest:test-suite:start')
const testSuiteFinishCh = channel('ci:vitest:test-suite:finish')
const testSuiteErrorCh = channel('ci:vitest:test-suite:error')
// test session hooks
const testSessionStartCh = channel('ci:vitest:session:start')
const testSessionFinishCh = channel('ci:vitest:session:finish')
const libraryConfigurationCh = channel('ci:vitest:library-configuration')
const knownTestsCh = channel('ci:vitest:known-tests')
const isEarlyFlakeDetectionFaultyCh = channel('ci:vitest:is-early-flake-detection-faulty')
const testManagementTestsCh = channel('ci:vitest:test-management-tests')
const taskToAsync = new WeakMap()
const taskToStatuses = new WeakMap()
const newTasks = new WeakSet()
const disabledTasks = new WeakSet()
const quarantinedTasks = new WeakSet()
let isRetryReasonEfd = false
const switchedStatuses = new WeakSet()
const sessionAsyncResource = new AsyncResource('bound-anonymous-fn')
const BREAKPOINT_HIT_GRACE_PERIOD_MS = 400
function waitForHitProbe () {
return new Promise(resolve => {
setTimeout(() => {
resolve()
}, BREAKPOINT_HIT_GRACE_PERIOD_MS)
})
}
function getProvidedContext () {
try {
const {
_ddIsEarlyFlakeDetectionEnabled,
_ddIsDiEnabled,
_ddKnownTests: knownTests,
_ddEarlyFlakeDetectionNumRetries: numRepeats,
_ddIsKnownTestsEnabled: isKnownTestsEnabled,
_ddIsTestManagementTestsEnabled: isTestManagementTestsEnabled,
_ddTestManagementTests: testManagementTests,
_ddIsFlakyTestRetriesEnabled: isFlakyTestRetriesEnabled
} = globalThis.__vitest_worker__.providedContext
return {
isDiEnabled: _ddIsDiEnabled,
isEarlyFlakeDetectionEnabled: _ddIsEarlyFlakeDetectionEnabled,
knownTests,
numRepeats,
isKnownTestsEnabled,
isTestManagementTestsEnabled,
testManagementTests,
isFlakyTestRetriesEnabled
}
} catch (e) {
log.error('Vitest workers could not parse provided context, so some features will not work.')
return {
isDiEnabled: false,
isEarlyFlakeDetectionEnabled: false,
knownTests: {},
numRepeats: 0,
isKnownTestsEnabled: false,
isTestManagementTestsEnabled: false,
testManagementTests: {}
}
}
}
function isReporterPackage (vitestPackage) {
return vitestPackage.B?.name === 'BaseSequencer'
}
// from 2.0.0
function isReporterPackageNew (vitestPackage) {
return vitestPackage.e?.name === 'BaseSequencer'
}
function isReporterPackageNewest (vitestPackage) {
return vitestPackage.h?.name === 'BaseSequencer'
}
function isBaseSequencer (vitestPackage) {
return vitestPackage.b?.name === 'BaseSequencer'
}
function getChannelPromise (channelToPublishTo) {
return new Promise(resolve => {
sessionAsyncResource.runInAsyncScope(() => {
channelToPublishTo.publish({ onDone: resolve })
})
})
}
function getSessionStatus (state) {
if (state.getCountOfFailedTests() > 0) {
return 'fail'
}
if (state.pathsSet.size === 0) {
return 'skip'
}
return 'pass'
}
// eslint-disable-next-line
// From https://github.com/vitest-dev/vitest/blob/51c04e2f44d91322b334f8ccbcdb368facc3f8ec/packages/runner/src/run.ts#L243-L250
function getVitestTestStatus (test, retryCount) {
if (test.result.state !== 'fail') {
if (!test.repeats) {
return 'pass'
} else if (test.repeats && (test.retry ?? 0) === retryCount) {
return 'pass'
}
}
return 'fail'
}
function getTypeTasks (fileTasks, type = 'test') {
const typeTasks = []
function getTasks (tasks) {
for (const task of tasks) {
if (task.type === type) {
typeTasks.push(task)
} else if (task.tasks) {
getTasks(task.tasks)
}
}
}
getTasks(fileTasks)
return typeTasks
}
function getTestName (task) {
let testName = task.name
let currentTask = task.suite
while (currentTask) {
if (currentTask.name) {
testName = `${currentTask.name} ${testName}`
}
currentTask = currentTask.suite
}
return testName
}
function getSortWrapper (sort) {
return async function () {
if (!testSessionFinishCh.hasSubscribers) {
return sort.apply(this, arguments)
}
// There isn't any other async function that we seem to be able to hook into
// So we will use the sort from BaseSequencer. This means that a custom sequencer
// will not work. This will be a known limitation.
let isFlakyTestRetriesEnabled = false
let flakyTestRetriesCount = 0
let isEarlyFlakeDetectionEnabled = false
let earlyFlakeDetectionNumRetries = 0
let isEarlyFlakeDetectionFaulty = false
let isKnownTestsEnabled = false
let isTestManagementTestsEnabled = false
let isDiEnabled = false
let knownTests = {}
let testManagementTests = {}
try {
const { err, libraryConfig } = await getChannelPromise(libraryConfigurationCh)
if (!err) {
isFlakyTestRetriesEnabled = libraryConfig.isFlakyTestRetriesEnabled
flakyTestRetriesCount = libraryConfig.flakyTestRetriesCount
isEarlyFlakeDetectionEnabled = libraryConfig.isEarlyFlakeDetectionEnabled
earlyFlakeDetectionNumRetries = libraryConfig.earlyFlakeDetectionNumRetries
isDiEnabled = libraryConfig.isDiEnabled
isKnownTestsEnabled = libraryConfig.isKnownTestsEnabled
isTestManagementTestsEnabled = libraryConfig.isTestManagementEnabled
}
} catch (e) {
isFlakyTestRetriesEnabled = false
isEarlyFlakeDetectionEnabled = false
isDiEnabled = false
isKnownTestsEnabled = false
}
if (isFlakyTestRetriesEnabled && !this.ctx.config.retry && flakyTestRetriesCount > 0) {
this.ctx.config.retry = flakyTestRetriesCount
try {
const workspaceProject = this.ctx.getCoreWorkspaceProject()
workspaceProject._provided._ddIsFlakyTestRetriesEnabled = isFlakyTestRetriesEnabled
} catch (e) {
log.warn('Could not send library configuration to workers.')
}
}
if (isKnownTestsEnabled) {
const knownTestsResponse = await getChannelPromise(knownTestsCh)
if (!knownTestsResponse.err) {
knownTests = knownTestsResponse.knownTests
const getFilePaths = this.ctx.getTestFilepaths || this.ctx._globTestFilepaths
const testFilepaths = await getFilePaths.call(this.ctx)
isEarlyFlakeDetectionFaultyCh.publish({
knownTests: knownTests.vitest || {},
testFilepaths,
onDone: (isFaulty) => {
isEarlyFlakeDetectionFaulty = isFaulty
}
})
if (isEarlyFlakeDetectionFaulty) {
isEarlyFlakeDetectionEnabled = false
isKnownTestsEnabled = false
log.warn('New test detection is disabled because the number of new tests is too high.')
} else {
// TODO: use this to pass session and module IDs to the worker, instead of polluting process.env
// Note: setting this.ctx.config.provide directly does not work because it's cached
try {
const workspaceProject = this.ctx.getCoreWorkspaceProject()
workspaceProject._provided._ddIsKnownTestsEnabled = isKnownTestsEnabled
workspaceProject._provided._ddKnownTests = knownTests.vitest || {}
workspaceProject._provided._ddIsEarlyFlakeDetectionEnabled = isEarlyFlakeDetectionEnabled
workspaceProject._provided._ddEarlyFlakeDetectionNumRetries = earlyFlakeDetectionNumRetries
} catch (e) {
log.warn('Could not send known tests to workers so Early Flake Detection will not work.')
}
}
} else {
isEarlyFlakeDetectionEnabled = false
isKnownTestsEnabled = false
}
}
if (isDiEnabled) {
try {
const workspaceProject = this.ctx.getCoreWorkspaceProject()
workspaceProject._provided._ddIsDiEnabled = isDiEnabled
} catch (e) {
log.warn('Could not send Dynamic Instrumentation configuration to workers.')
}
}
if (isTestManagementTestsEnabled) {
const { err, testManagementTests: receivedTestManagementTests } = await getChannelPromise(testManagementTestsCh)
if (!err) {
testManagementTests = receivedTestManagementTests
try {
const workspaceProject = this.ctx.getCoreWorkspaceProject()
workspaceProject._provided._ddIsTestManagementTestsEnabled = isTestManagementTestsEnabled
workspaceProject._provided._ddTestManagementTests = testManagementTests
} catch (e) {
log.warn('Could not send test management tests to workers so Test Management will not work.')
}
} else {
isTestManagementTestsEnabled = false
log.error('Could not get test management tests.')
}
}
let testCodeCoverageLinesTotal
if (this.ctx.coverageProvider?.generateCoverage) {
shimmer.wrap(this.ctx.coverageProvider, 'generateCoverage', generateCoverage => async function () {
const totalCodeCoverage = await generateCoverage.apply(this, arguments)
try {
testCodeCoverageLinesTotal = totalCodeCoverage.getCoverageSummary().lines.pct
} catch (e) {
// ignore errors
}
return totalCodeCoverage
})
}
shimmer.wrap(this.ctx, 'exit', exit => async function () {
let onFinish
const flushPromise = new Promise(resolve => {
onFinish = resolve
})
const failedSuites = this.state.getFailedFilepaths()
let error
if (failedSuites.length) {
error = new Error(`Test suites failed: ${failedSuites.length}.`)
}
sessionAsyncResource.runInAsyncScope(() => {
testSessionFinishCh.publish({
status: getSessionStatus(this.state),
testCodeCoverageLinesTotal,
error,
isEarlyFlakeDetectionEnabled,
isEarlyFlakeDetectionFaulty,
isTestManagementTestsEnabled,
onFinish
})
})
await flushPromise
return exit.apply(this, arguments)
})
return sort.apply(this, arguments)
}
}
function getCreateCliWrapper (vitestPackage, frameworkVersion) {
shimmer.wrap(vitestPackage, 'c', oldCreateCli => function () {
if (!testSessionStartCh.hasSubscribers) {
return oldCreateCli.apply(this, arguments)
}
sessionAsyncResource.runInAsyncScope(() => {
const processArgv = process.argv.slice(2).join(' ')
testSessionStartCh.publish({ command: `vitest ${processArgv}`, frameworkVersion })
})
return oldCreateCli.apply(this, arguments)
})
return vitestPackage
}
addHook({
name: 'vitest',
versions: ['>=1.6.0'],
file: 'dist/runners.js'
}, (vitestPackage) => {
const { VitestTestRunner } = vitestPackage
// `onBeforeRunTask` is run before any repetition or attempt is run
// `onBeforeRunTask` is an async function
shimmer.wrap(VitestTestRunner.prototype, 'onBeforeRunTask', onBeforeRunTask => function (task) {
const testName = getTestName(task)
const {
knownTests,
isEarlyFlakeDetectionEnabled,
isKnownTestsEnabled,
numRepeats,
isTestManagementTestsEnabled,
testManagementTests
} = getProvidedContext()
if (isTestManagementTestsEnabled) {
isDisabledCh.publish({
testManagementTests,
testSuiteAbsolutePath: task.file.filepath,
testName,
onDone: (isTestDisabled) => {
if (isTestDisabled) {
disabledTasks.add(task)
task.mode = 'skip'
}
}
})
}
if (isKnownTestsEnabled) {
isNewTestCh.publish({
knownTests,
testSuiteAbsolutePath: task.file.filepath,
testName,
onDone: (isNew) => {
if (isNew) {
if (isEarlyFlakeDetectionEnabled) {
isRetryReasonEfd = task.repeats !== numRepeats
task.repeats = numRepeats
}
newTasks.add(task)
taskToStatuses.set(task, [])
}
}
})
}
return onBeforeRunTask.apply(this, arguments)
})
// `onAfterRunTask` is run after all repetitions or attempts are run
// `onAfterRunTask` is an async function
shimmer.wrap(VitestTestRunner.prototype, 'onAfterRunTask', onAfterRunTask => function (task) {
const { isEarlyFlakeDetectionEnabled, isTestManagementTestsEnabled } = getProvidedContext()
if (isEarlyFlakeDetectionEnabled && taskToStatuses.has(task)) {
const statuses = taskToStatuses.get(task)
// If the test has passed at least once, we consider it passed
if (statuses.includes('pass')) {
if (task.result.state === 'fail') {
switchedStatuses.add(task)
}
task.result.state = 'pass'
}
}
if (isTestManagementTestsEnabled) {
if (quarantinedTasks.has(task)) {
task.result.state = 'pass'
}
}
return onAfterRunTask.apply(this, arguments)
})
// test start (only tests that are not marked as skip or todo)
// `onBeforeTryTask` is run for every repetition and attempt of the test
shimmer.wrap(VitestTestRunner.prototype, 'onBeforeTryTask', onBeforeTryTask => async function (task, retryInfo) {
if (!testStartCh.hasSubscribers) {
return onBeforeTryTask.apply(this, arguments)
}
const testName = getTestName(task)
let isNew = false
let isQuarantined = false
const {
isKnownTestsEnabled,
isEarlyFlakeDetectionEnabled,
isDiEnabled,
isTestManagementTestsEnabled,
testManagementTests
} = getProvidedContext()
if (isKnownTestsEnabled) {
isNew = newTasks.has(task)
}
if (isTestManagementTestsEnabled) {
isQuarantinedCh.publish({
testManagementTests,
testSuiteAbsolutePath: task.file.filepath,
testName,
onDone: (isTestQuarantined) => {
isQuarantined = isTestQuarantined
if (isTestQuarantined) {
quarantinedTasks.add(task)
}
}
})
}
const { retry: numAttempt, repeats: numRepetition } = retryInfo
// We finish the previous test here because we know it has failed already
if (numAttempt > 0) {
const shouldWaitForHitProbe = isDiEnabled && numAttempt > 1
if (shouldWaitForHitProbe) {
await waitForHitProbe()
}
const promises = {}
const shouldSetProbe = isDiEnabled && numAttempt === 1
const asyncResource = taskToAsync.get(task)
const testError = task.result?.errors?.[0]
if (asyncResource) {
asyncResource.runInAsyncScope(() => {
testErrorCh.publish({
error: testError,
shouldSetProbe,
promises
})
})
// We wait for the probe to be set
if (promises.setProbePromise) {
await promises.setProbePromise
}
}
}
const lastExecutionStatus = task.result.state
// These clauses handle task.repeats, whether EFD is enabled or not
// The only thing that EFD does is to forcefully pass the test if it has passed at least once
if (numRepetition > 0 && numRepetition < task.repeats) { // it may or may have not failed
// Here we finish the earlier iteration,
// as long as it's not the _last_ iteration (which will be finished normally)
// TODO: check test duration (not to repeat if it's too slow)
const asyncResource = taskToAsync.get(task)
if (asyncResource) {
if (lastExecutionStatus === 'fail') {
const testError = task.result?.errors?.[0]
asyncResource.runInAsyncScope(() => {
testErrorCh.publish({ error: testError })
})
} else {
asyncResource.runInAsyncScope(() => {
testPassCh.publish({ task })
})
}
if (isEarlyFlakeDetectionEnabled) {
const statuses = taskToStatuses.get(task)
statuses.push(lastExecutionStatus)
// If we don't "reset" the result.state to "pass", once a repetition fails,
// vitest will always consider the test as failed, so we can't read the actual status
task.result.state = 'pass'
}
}
} else if (numRepetition === task.repeats) {
const asyncResource = taskToAsync.get(task)
if (lastExecutionStatus === 'fail') {
const testError = task.result?.errors?.[0]
asyncResource.runInAsyncScope(() => {
testErrorCh.publish({ error: testError })
})
} else {
asyncResource.runInAsyncScope(() => {
testPassCh.publish({ task })
})
}
}
const asyncResource = new AsyncResource('bound-anonymous-fn')
taskToAsync.set(task, asyncResource)
asyncResource.runInAsyncScope(() => {
testStartCh.publish({
testName,
testSuiteAbsolutePath: task.file.filepath,
isRetry: numAttempt > 0 || numRepetition > 0,
isRetryReasonEfd,
isNew,
mightHitProbe: isDiEnabled && numAttempt > 0,
isQuarantined
})
})
return onBeforeTryTask.apply(this, arguments)
})
// test finish (only passed tests)
shimmer.wrap(VitestTestRunner.prototype, 'onAfterTryTask', onAfterTryTask =>
async function (task, { retry: retryCount }) {
if (!testFinishTimeCh.hasSubscribers) {
return onAfterTryTask.apply(this, arguments)
}
const result = await onAfterTryTask.apply(this, arguments)
const status = getVitestTestStatus(task, retryCount)
const asyncResource = taskToAsync.get(task)
const { isDiEnabled } = getProvidedContext()
if (isDiEnabled && retryCount > 1) {
await waitForHitProbe()
}
if (asyncResource) {
// We don't finish here because the test might fail in a later hook (afterEach)
asyncResource.runInAsyncScope(() => {
testFinishTimeCh.publish({ status, task })
})
}
return result
})
return vitestPackage
})
// There are multiple index* files across different versions of vitest,
// so we check for the existence of BaseSequencer to determine if we are in the right file
addHook({
name: 'vitest',
versions: ['>=1.6.0 <2.0.0'],
filePattern: 'dist/vendor/index.*'
}, (vitestPackage) => {
if (isReporterPackage(vitestPackage)) {
shimmer.wrap(vitestPackage.B.prototype, 'sort', getSortWrapper)
}
return vitestPackage
})
addHook({
name: 'vitest',
versions: ['>=2.0.0 <2.0.5'],
filePattern: 'dist/vendor/index.*'
}, (vitestPackage) => {
if (isReporterPackageNew(vitestPackage)) {
shimmer.wrap(vitestPackage.e.prototype, 'sort', getSortWrapper)
}
return vitestPackage
})
addHook({
name: 'vitest',
versions: ['>=2.0.5 <2.1.0'],
filePattern: 'dist/chunks/index.*'
}, (vitestPackage) => {
if (isReporterPackageNewest(vitestPackage)) {
shimmer.wrap(vitestPackage.h.prototype, 'sort', getSortWrapper)
}
return vitestPackage
})
addHook({
name: 'vitest',
versions: ['>=2.1.0 <3.0.0'],
filePattern: 'dist/chunks/RandomSequencer.*'
}, (randomSequencerPackage) => {
shimmer.wrap(randomSequencerPackage.B.prototype, 'sort', getSortWrapper)
return randomSequencerPackage
})
addHook({
name: 'vitest',
versions: ['>=3.0.9'],
filePattern: 'dist/chunks/coverage.*'
}, (coveragePackage) => {
if (isBaseSequencer(coveragePackage)) {
shimmer.wrap(coveragePackage.b.prototype, 'sort', getSortWrapper)
}
return coveragePackage
})
addHook({
name: 'vitest',
versions: ['>=3.0.0 <3.0.9'],
filePattern: 'dist/chunks/resolveConfig.*'
}, (resolveConfigPackage) => {
shimmer.wrap(resolveConfigPackage.B.prototype, 'sort', getSortWrapper)
return resolveConfigPackage
})
// Can't specify file because compiled vitest includes hashes in their files
addHook({
name: 'vitest',
versions: ['>=1.6.0 <2.0.5'],
filePattern: 'dist/vendor/cac.*'
}, getCreateCliWrapper)
addHook({
name: 'vitest',
versions: ['>=2.0.5'],
filePattern: 'dist/chunks/cac.*'
}, getCreateCliWrapper)
// test suite start and finish
// only relevant for workers
addHook({
name: '@vitest/runner',
versions: ['>=1.6.0'],
file: 'dist/index.js'
}, (vitestPackage, frameworkVersion) => {
shimmer.wrap(vitestPackage, 'startTests', startTests => async function (testPaths) {
let testSuiteError = null
if (!testSuiteStartCh.hasSubscribers) {
return startTests.apply(this, arguments)
}
// From >=3.0.1, the first arguments changes from a string to an object containing the filepath
const testSuiteAbsolutePath = testPaths[0]?.filepath || testPaths[0]
const { isEarlyFlakeDetectionEnabled, isFlakyTestRetriesEnabled } = getProvidedContext()
const testSuiteAsyncResource = new AsyncResource('bound-anonymous-fn')
testSuiteAsyncResource.runInAsyncScope(() => {
testSuiteStartCh.publish({
testSuiteAbsolutePath,
frameworkVersion,
isFlakyTestRetriesEnabled,
isEarlyFlakeDetectionEnabled
})
})
const startTestsResponse = await startTests.apply(this, arguments)
let onFinish = null
const onFinishPromise = new Promise(resolve => {
onFinish = resolve
})
const testTasks = getTypeTasks(startTestsResponse[0].tasks)
// Only one test task per test, even if there are retries
testTasks.forEach(task => {
const testAsyncResource = taskToAsync.get(task)
const { result } = task
// We have to trick vitest into thinking that the test has passed
// but we want to report it as failed if it did fail
const isSwitchedStatus = switchedStatuses.has(task)
if (result) {
const { state, duration, errors } = result
if (state === 'skip') { // programmatic skip
testSkipCh.publish({
testName: getTestName(task),
testSuiteAbsolutePath: task.file.filepath,
isNew: newTasks.has(task),
isDisabled: disabledTasks.has(task)
})
} else if (state === 'pass' && !isSwitchedStatus) {
if (testAsyncResource) {
testAsyncResource.runInAsyncScope(() => {
testPassCh.publish({ task })
})
}
} else if (state === 'fail' || isSwitchedStatus) {
let testError
if (errors?.length) {
testError = errors[0]
}
if (testAsyncResource) {
const isRetry = task.result?.retryCount > 0
// `duration` is the duration of all the retries, so it can't be used if there are retries
testAsyncResource.runInAsyncScope(() => {
testErrorCh.publish({ duration: !isRetry ? duration : undefined, error: testError })
})
}
if (errors?.length) {
testSuiteError = testError // we store the error to bubble it up to the suite
}
}
} else { // test.skip or test.todo
testSkipCh.publish({
testName: getTestName(task),
testSuiteAbsolutePath: task.file.filepath,
isNew: newTasks.has(task),
isDisabled: disabledTasks.has(task)
})
}
})
const testSuiteResult = startTestsResponse[0].result
if (testSuiteResult.errors?.length) { // Errors from root level hooks
testSuiteError = testSuiteResult.errors[0]
} else if (testSuiteResult.state === 'fail') { // Errors from `describe` level hooks
const suiteTasks = getTypeTasks(startTestsResponse[0].tasks, 'suite')
const failedSuites = suiteTasks.filter(task => task.result?.state === 'fail')
if (failedSuites.length && failedSuites[0].result?.errors?.length) {
testSuiteError = failedSuites[0].result.errors[0]
}
}
if (testSuiteError) {
testSuiteAsyncResource.runInAsyncScope(() => {
testSuiteErrorCh.publish({ error: testSuiteError })
})
}
testSuiteAsyncResource.runInAsyncScope(() => {
testSuiteFinishCh.publish({ status: testSuiteResult.state, onFinish })
})
// TODO: fix too frequent flushes
await onFinishPromise
return startTestsResponse
})
return vitestPackage
})