/
core.ts
699 lines (575 loc) · 20.1 KB
/
core.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
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
import { existsSync, promises as fs } from 'node:fs'
import type { ViteDevServer } from 'vite'
import { normalize, relative, toNamespacedPath } from 'pathe'
import fg from 'fast-glob'
import mm from 'micromatch'
import c from 'picocolors'
import { ViteNodeRunner } from 'vite-node/client'
import { ViteNodeServer } from 'vite-node/server'
import type { ArgumentsType, CoverageProvider, OnServerRestartHandler, Reporter, ResolvedConfig, UserConfig, VitestRunMode } from '../types'
import { SnapshotManager } from '../integrations/snapshot/manager'
import { deepMerge, hasFailed, noop, slash, toArray } from '../utils'
import { getCoverageProvider } from '../integrations/coverage'
import { Typechecker } from '../typecheck/typechecker'
import { createPool } from './pool'
import type { ProcessPool } from './pool'
import { createBenchmarkReporters, createReporters } from './reporters/utils'
import { StateManager } from './state'
import { resolveConfig } from './config'
import { Logger } from './logger'
import { VitestCache } from './cache'
const WATCHER_DEBOUNCE = 100
export class Vitest {
config: ResolvedConfig = undefined!
configOverride: Partial<ResolvedConfig> | undefined
server: ViteDevServer = undefined!
state: StateManager = undefined!
snapshot: SnapshotManager = undefined!
cache: VitestCache = undefined!
reporters: Reporter[] = undefined!
coverageProvider: CoverageProvider | null | undefined
logger: Logger
pool: ProcessPool | undefined
typechecker: Typechecker | undefined
vitenode: ViteNodeServer = undefined!
invalidates: Set<string> = new Set()
changedTests: Set<string> = new Set()
filenamePattern?: string
runningPromise?: Promise<void>
closingPromise?: Promise<void>
isFirstRun = true
restartsCount = 0
runner: ViteNodeRunner = undefined!
constructor(
public readonly mode: VitestRunMode,
) {
this.logger = new Logger(this)
}
private _onRestartListeners: OnServerRestartHandler[] = []
private _onSetServer: OnServerRestartHandler[] = []
async setServer(options: UserConfig, server: ViteDevServer) {
this.unregisterWatcher?.()
clearTimeout(this._rerunTimer)
this.restartsCount += 1
this.pool?.close()
this.pool = undefined
this.coverageProvider = undefined
this.runningPromise = undefined
const resolved = resolveConfig(this.mode, options, server.config)
this.server = server
this.config = resolved
this.state = new StateManager()
this.cache = new VitestCache()
this.snapshot = new SnapshotManager({ ...resolved.snapshotOptions })
if (this.config.watch && this.mode !== 'typecheck')
this.registerWatcher()
this.vitenode = new ViteNodeServer(server, this.config)
const node = this.vitenode
this.runner = new ViteNodeRunner({
root: server.config.root,
base: server.config.base,
fetchModule(id: string) {
return node.fetchModule(id)
},
resolveId(id: string, importer?: string) {
return node.resolveId(id, importer)
},
})
if (this.config.watch) {
// hijack server restart
const serverRestart = server.restart
server.restart = async (...args) => {
await Promise.all(this._onRestartListeners.map(fn => fn()))
return await serverRestart(...args)
}
// since we set `server.hmr: false`, Vite does not auto restart itself
server.watcher.on('change', async (file) => {
file = normalize(file)
const isConfig = file === server.config.configFile
if (isConfig) {
await Promise.all(this._onRestartListeners.map(fn => fn('config')))
await serverRestart()
}
})
}
this.reporters = resolved.mode === 'benchmark'
? await createBenchmarkReporters(toArray(resolved.benchmark?.reporters), this.runner)
: await createReporters(resolved.reporters, this.runner)
this.cache.results.setConfig(resolved.root, resolved.cache)
try {
await this.cache.results.readFromCache()
}
catch {}
await Promise.all(this._onSetServer.map(fn => fn()))
}
async initCoverageProvider() {
if (this.coverageProvider !== undefined)
return
this.coverageProvider = await getCoverageProvider(this.config.coverage, this.runner)
if (this.coverageProvider) {
await this.coverageProvider.initialize(this)
this.config.coverage = this.coverageProvider.resolveOptions()
}
return this.coverageProvider
}
getSerializableConfig() {
return deepMerge({
...this.config,
reporters: [],
deps: {
...this.config.deps,
experimentalOptimizer: {
enabled: this.config.deps?.experimentalOptimizer?.enabled ?? false,
},
},
snapshotOptions: {
...this.config.snapshotOptions,
resolveSnapshotPath: undefined,
},
onConsoleLog: undefined!,
sequence: {
...this.config.sequence,
sequencer: undefined!,
},
benchmark: {
...this.config.benchmark,
reporters: [],
},
},
this.configOverride || {} as any,
) as ResolvedConfig
}
async typecheck(filters: string[] = []) {
const { dir, root } = this.config
const { include, exclude } = this.config.typecheck
const testsFilesList = this.filterFiles(await this.globFiles(include, exclude, dir || root), filters)
const checker = new Typechecker(this, testsFilesList)
this.typechecker = checker
checker.onParseEnd(async ({ files, sourceErrors }) => {
this.state.collectFiles(checker.getTestFiles())
await this.report('onTaskUpdate', checker.getTestPacks())
await this.report('onCollected')
if (!files.length) {
this.logger.printNoTestFound()
}
else {
if (hasFailed(files))
process.exitCode = 1
await this.report('onFinished', files)
}
if (sourceErrors.length && !this.config.typecheck.ignoreSourceErrors) {
process.exitCode = 1
await this.logger.printSourceTypeErrors(sourceErrors)
}
// if there are source errors, we are showing it, and then terminating process
if (!files.length) {
const exitCode = this.config.passWithNoTests ? (process.exitCode ?? 0) : 1
process.exit(exitCode)
}
if (this.config.watch) {
await this.report('onWatcherStart', files, [
...(this.config.typecheck.ignoreSourceErrors ? [] : sourceErrors),
...this.state.getUnhandledErrors(),
])
}
})
checker.onParseStart(async () => {
await this.report('onInit', this)
this.state.collectFiles(checker.getTestFiles())
await this.report('onCollected')
})
checker.onWatcherRerun(async () => {
await this.report('onWatcherRerun', testsFilesList, 'File change detected. Triggering rerun.')
await checker.collectTests()
this.state.collectFiles(checker.getTestFiles())
await this.report('onTaskUpdate', checker.getTestPacks())
await this.report('onCollected')
})
await checker.prepare()
await checker.collectTests()
await checker.start()
}
async start(filters?: string[]) {
if (this.mode === 'typecheck') {
await this.typecheck(filters)
return
}
try {
await this.initCoverageProvider()
await this.coverageProvider?.clean(this.config.coverage.clean)
}
catch (e) {
this.logger.error(e)
process.exit(1)
}
await this.report('onInit', this)
const files = await this.filterTestsBySource(
await this.globTestFiles(filters),
)
if (!files.length) {
const exitCode = this.config.passWithNoTests ? 0 : 1
this.logger.printNoTestFound(filters)
process.exit(exitCode)
}
// populate once, update cache on watch
await Promise.all(files.map(file => this.cache.stats.updateStats(file)))
await this.runFiles(files)
await this.reportCoverage(true)
if (this.config.watch && !this.config.browser)
await this.report('onWatcherStart')
}
private async getTestDependencies(filepath: string) {
const deps = new Set<string>()
const addImports = async (filepath: string) => {
const transformed = await this.vitenode.transformRequest(filepath)
if (!transformed)
return
const dependencies = [...transformed.deps || [], ...transformed.dynamicDeps || []]
for (const dep of dependencies) {
const path = await this.server.pluginContainer.resolveId(dep, filepath, { ssr: true })
const fsPath = path && !path.external && path.id.split('?')[0]
if (fsPath && !fsPath.includes('node_modules') && !deps.has(fsPath) && existsSync(fsPath)) {
deps.add(fsPath)
await addImports(fsPath)
}
}
}
await addImports(filepath)
return deps
}
async filterTestsBySource(tests: string[]) {
if (this.config.changed && !this.config.related) {
const { VitestGit } = await import('./git')
const vitestGit = new VitestGit(this.config.root)
const related = await vitestGit.findChangedFiles({
changedSince: this.config.changed,
})
if (!related) {
this.logger.error(c.red('Could not find Git root. Have you initialized git with `git init`?\n'))
process.exit(1)
}
this.config.related = Array.from(new Set(related))
}
const related = this.config.related
if (!related)
return tests
const forceRerunTriggers = this.config.forceRerunTriggers
if (forceRerunTriggers.length && mm(related, forceRerunTriggers).length)
return tests
// don't run anything if no related sources are found
if (!related.length)
return []
const testGraphs = await Promise.all(
tests.map(async (filepath) => {
const deps = await this.getTestDependencies(filepath)
return [filepath, deps] as const
}),
)
const runningTests = []
for (const [filepath, deps] of testGraphs) {
// if deps or the test itself were changed
if (related.some(path => path === filepath || deps.has(path)))
runningTests.push(filepath)
}
return runningTests
}
async runFiles(paths: string[]) {
paths = Array.from(new Set(paths))
this.state.collectPaths(paths)
await this.report('onPathsCollected', paths)
if (this.config.browser)
return
// previous run
await this.runningPromise
// schedule the new run
this.runningPromise = (async () => {
if (!this.pool)
this.pool = createPool(this)
const invalidates = Array.from(this.invalidates)
this.invalidates.clear()
this.snapshot.clear()
this.state.clearErrors()
try {
await this.pool.runTests(paths, invalidates)
}
catch (err) {
this.state.catchError(err, 'Unhandled Error')
}
const files = this.state.getFiles()
if (hasFailed(files))
process.exitCode = 1
this.cache.results.updateResults(files)
await this.cache.results.writeToCache()
})()
.finally(async () => {
if (!this.config.browser)
await this.report('onFinished', this.state.getFiles(paths), this.state.getUnhandledErrors())
this.runningPromise = undefined
})
return await this.runningPromise
}
async rerunFiles(files: string[] = this.state.getFilepaths(), trigger?: string) {
if (this.filenamePattern) {
const filteredFiles = await this.globTestFiles([this.filenamePattern])
files = files.filter(file => filteredFiles.includes(file))
}
if (this.coverageProvider && this.config.coverage.cleanOnRerun)
await this.coverageProvider.clean()
await this.report('onWatcherRerun', files, trigger)
await this.runFiles(files)
await this.reportCoverage(!trigger)
if (!this.config.browser)
await this.report('onWatcherStart', this.state.getFiles(files))
}
async changeNamePattern(pattern: string, files: string[] = this.state.getFilepaths(), trigger?: string) {
// Empty test name pattern should reset filename pattern as well
if (pattern === '')
this.filenamePattern = undefined
this.config.testNamePattern = pattern ? new RegExp(pattern) : undefined
await this.rerunFiles(files, trigger)
}
async changeFilenamePattern(pattern: string) {
this.filenamePattern = pattern
const files = this.state.getFilepaths()
const trigger = this.filenamePattern ? 'change filename pattern' : 'reset filename pattern'
await this.rerunFiles(files, trigger)
}
async rerunFailed() {
await this.rerunFiles(this.state.getFailedFilepaths(), 'rerun failed')
}
async updateSnapshot(files?: string[]) {
// default to failed files
files = files || [
...this.state.getFailedFilepaths(),
...this.snapshot.summary.uncheckedKeysByFile.map(s => s.filePath),
]
this.configOverride = {
snapshotOptions: {
updateSnapshot: 'all',
},
}
try {
await this.rerunFiles(files, 'update snapshot')
}
finally {
this.configOverride = undefined
}
}
private _rerunTimer: any
private async scheduleRerun(triggerId: string) {
const currentCount = this.restartsCount
clearTimeout(this._rerunTimer)
await this.runningPromise
clearTimeout(this._rerunTimer)
// server restarted
if (this.restartsCount !== currentCount)
return
this._rerunTimer = setTimeout(async () => {
if (this.changedTests.size === 0) {
this.invalidates.clear()
return
}
// server restarted
if (this.restartsCount !== currentCount)
return
this.isFirstRun = false
this.snapshot.clear()
let files = Array.from(this.changedTests)
if (this.filenamePattern) {
const filteredFiles = await this.globTestFiles([this.filenamePattern])
files = files.filter(file => filteredFiles.includes(file))
// A file that does not match the current filename pattern was changed
if (files.length === 0)
return
}
this.changedTests.clear()
if (this.coverageProvider && this.config.coverage.cleanOnRerun)
await this.coverageProvider.clean()
await this.report('onWatcherRerun', files, triggerId)
await this.runFiles(files)
await this.reportCoverage(false)
if (!this.config.browser)
await this.report('onWatcherStart', this.state.getFiles(files))
}, WATCHER_DEBOUNCE)
}
private unregisterWatcher = noop
private registerWatcher() {
const updateLastChanged = (id: string) => {
const mod = this.server.moduleGraph.getModuleById(id)
if (mod)
mod.lastHMRTimestamp = Date.now()
}
const onChange = (id: string) => {
id = slash(id)
updateLastChanged(id)
const needsRerun = this.handleFileChanged(id)
if (needsRerun)
this.scheduleRerun(id)
}
const onUnlink = (id: string) => {
id = slash(id)
this.invalidates.add(id)
if (this.state.filesMap.has(id)) {
this.state.filesMap.delete(id)
this.cache.results.removeFromCache(id)
this.cache.stats.removeStats(id)
this.changedTests.delete(id)
this.report('onTestRemoved', id)
}
}
const onAdd = async (id: string) => {
id = slash(id)
updateLastChanged(id)
if (await this.isTargetFile(id)) {
this.changedTests.add(id)
await this.cache.stats.updateStats(id)
this.scheduleRerun(id)
}
}
const watcher = this.server.watcher
if (this.config.forceRerunTriggers.length)
watcher.add(this.config.forceRerunTriggers)
watcher.unwatch(this.config.watchExclude)
watcher.on('change', onChange)
watcher.on('unlink', onUnlink)
watcher.on('add', onAdd)
this.unregisterWatcher = () => {
watcher.off('change', onChange)
watcher.off('unlink', onUnlink)
watcher.off('add', onAdd)
this.unregisterWatcher = noop
}
}
/**
* @returns A value indicating whether rerun is needed (changedTests was mutated)
*/
private handleFileChanged(id: string): boolean {
if (this.changedTests.has(id) || this.invalidates.has(id))
return false
if (mm.isMatch(id, this.config.forceRerunTriggers)) {
this.state.getFilepaths().forEach(file => this.changedTests.add(file))
return true
}
const mod = this.server.moduleGraph.getModuleById(id)
if (!mod)
return false
this.invalidates.add(id)
if (this.state.filesMap.has(id)) {
this.changedTests.add(id)
return true
}
let rerun = false
mod.importers.forEach((i) => {
if (!i.id)
return
const heedsRerun = this.handleFileChanged(i.id)
if (heedsRerun)
rerun = true
})
return rerun
}
private async reportCoverage(allTestsRun: boolean) {
if (this.coverageProvider) {
this.logger.log(c.blue(' % ') + c.dim('Coverage report from ') + c.yellow(this.coverageProvider.name))
await this.coverageProvider.reportCoverage({ allTestsRun })
}
}
async close() {
if (!this.closingPromise) {
this.closingPromise = Promise.allSettled([
this.pool?.close(),
this.server.close(),
this.typechecker?.stop(),
].filter(Boolean)).then((results) => {
results.filter(r => r.status === 'rejected').forEach((err) => {
this.logger.error('error during close', (err as PromiseRejectedResult).reason)
})
})
}
return this.closingPromise
}
/**
* Close the thread pool and exit the process
*/
async exit(force = false) {
setTimeout(() => {
this.report('onProcessTimeout').then(() => {
console.warn(`close timed out after ${this.config.teardownTimeout}ms`)
this.state.getProcessTimeoutCauses().forEach(cause => console.warn(cause))
process.exit()
})
}, this.config.teardownTimeout).unref()
await this.close()
if (force)
process.exit()
}
async report<T extends keyof Reporter>(name: T, ...args: ArgumentsType<Reporter[T]>) {
await Promise.all(this.reporters.map(r => r[name]?.(
// @ts-expect-error let me go
...args,
)))
}
async globFiles(include: string[], exclude: string[], cwd: string) {
const globOptions: fg.Options = {
absolute: true,
dot: true,
cwd,
ignore: exclude,
}
return fg(include, globOptions)
}
private _allTestsCache: string[] | null = null
async globAllTestFiles(config: ResolvedConfig, cwd: string) {
const { include, exclude, includeSource } = config
const testFiles = await this.globFiles(include, exclude, cwd)
if (includeSource) {
const files = await this.globFiles(includeSource, exclude, cwd)
await Promise.all(files.map(async (file) => {
try {
const code = await fs.readFile(file, 'utf-8')
if (this.isInSourceTestFile(code))
testFiles.push(file)
}
catch {
return null
}
}))
}
this._allTestsCache = testFiles
return testFiles
}
filterFiles(testFiles: string[], filters: string[] = []) {
if (filters.length && process.platform === 'win32')
filters = filters.map(f => toNamespacedPath(f))
if (filters.length)
return testFiles.filter(i => filters.some(f => i.includes(f)))
return testFiles
}
async globTestFiles(filters: string[] = []) {
const { dir, root } = this.config
const testFiles = this._allTestsCache ?? await this.globAllTestFiles(this.config, dir || root)
this._allTestsCache = null
return this.filterFiles(testFiles, filters)
}
async isTargetFile(id: string, source?: string): Promise<boolean> {
const relativeId = relative(this.config.dir || this.config.root, id)
if (mm.isMatch(relativeId, this.config.exclude))
return false
if (mm.isMatch(relativeId, this.config.include))
return true
if (this.config.includeSource?.length && mm.isMatch(relativeId, this.config.includeSource)) {
source = source || await fs.readFile(id, 'utf-8')
return this.isInSourceTestFile(source)
}
return false
}
isInSourceTestFile(code: string) {
return code.includes('import.meta.vitest')
}
onServerRestart(fn: OnServerRestartHandler) {
this._onRestartListeners.push(fn)
}
onAfterSetServer(fn: OnServerRestartHandler) {
this._onSetServer.push(fn)
}
}