-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
base.ts
364 lines (314 loc) · 13.7 KB
/
base.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
import { performance } from 'node:perf_hooks'
import c from 'picocolors'
import type { ErrorWithDiff, File, Reporter, Task, TaskResultPack, UserConsoleLog } from '../../types'
import { getFullName, getSafeTimers, getSuites, getTests, hasFailed, hasFailedSnapshot, isCI, isNode, relativePath } from '../../utils'
import type { Vitest } from '../../node'
import { F_RIGHT } from '../../utils/figures'
import { countTestErrors, divider, formatProjectName, formatTimeString, getStateString, getStateSymbol, pointer, renderSnapshotSummary } from './renderers/utils'
const BADGE_PADDING = ' '
const HELP_HINT = `${c.dim('press ')}${c.bold('h')}${c.dim(' to show help')}`
const HELP_UPDATE_SNAP = c.dim('press ') + c.bold(c.yellow('u')) + c.dim(' to update snapshot')
const HELP_QUITE = `${c.dim('press ')}${c.bold('q')}${c.dim(' to quit')}`
const WAIT_FOR_CHANGE_PASS = `\n${c.bold(c.inverse(c.green(' PASS ')))}${c.green(' Waiting for file changes...')}`
const WAIT_FOR_CHANGE_FAIL = `\n${c.bold(c.inverse(c.red(' FAIL ')))}${c.red(' Tests failed. Watching for file changes...')}`
const WAIT_FOR_CHANGE_CANCELLED = `\n${c.bold(c.inverse(c.red(' CANCELLED ')))}${c.red(' Test run cancelled. Watching for file changes...')}`
const LAST_RUN_LOG_TIMEOUT = 1_500
export abstract class BaseReporter implements Reporter {
start = 0
end = 0
watchFilters?: string[]
isTTY = isNode && process.stdout?.isTTY && !isCI
ctx: Vitest = undefined!
private _filesInWatchMode = new Map<string, number>()
private _lastRunTimeout = 0
private _lastRunTimer: NodeJS.Timer | undefined
private _lastRunCount = 0
private _timeStart = new Date()
constructor() {
this.registerUnhandledRejection()
}
get mode() {
return this.ctx.config.mode
}
onInit(ctx: Vitest) {
this.ctx = ctx
ctx.logger.printBanner()
this.start = performance.now()
}
relative(path: string) {
return relativePath(this.ctx.config.root, path)
}
async onFinished(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) {
this.end = performance.now()
await this.reportSummary(files)
if (errors.length) {
if (!this.ctx.config.dangerouslyIgnoreUnhandledErrors)
process.exitCode = 1
await this.ctx.logger.printUnhandledErrors(errors)
}
}
onTaskUpdate(packs: TaskResultPack[]) {
if (this.isTTY)
return
const logger = this.ctx.logger
for (const pack of packs) {
const task = this.ctx.state.idMap.get(pack[0])
if (task && 'filepath' in task && task.result?.state && task.result?.state !== 'run') {
const tests = getTests(task)
const failed = tests.filter(t => t.result?.state === 'fail')
const skipped = tests.filter(t => t.mode === 'skip' || t.mode === 'todo')
let state = c.dim(`${tests.length} test${tests.length > 1 ? 's' : ''}`)
if (failed.length)
state += ` ${c.dim('|')} ${c.red(`${failed.length} failed`)}`
if (skipped.length)
state += ` ${c.dim('|')} ${c.yellow(`${skipped.length} skipped`)}`
let suffix = c.dim(' (') + state + c.dim(')')
if (task.result.duration) {
const color = task.result.duration > this.ctx.config.slowTestThreshold ? c.yellow : c.gray
suffix += color(` ${Math.round(task.result.duration)}${c.dim('ms')}`)
}
if (this.ctx.config.logHeapUsage && task.result.heap != null)
suffix += c.magenta(` ${Math.floor(task.result.heap / 1024 / 1024)} MB heap used`)
let title = ` ${getStateSymbol(task)} `
if (task.projectName)
title += formatProjectName(task.projectName)
title += `${task.name} ${suffix}`
logger.log(title)
// print short errors, full errors will be at the end in summary
for (const test of failed) {
logger.log(c.red(` ${pointer} ${getFullName(test, c.dim(' > '))}`))
test.result?.errors?.forEach((e) => {
logger.log(c.red(` ${F_RIGHT} ${(e as any)?.message}`))
})
}
}
}
}
async onWatcherStart(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) {
this.resetLastRunLog()
const failed = errors.length > 0 || hasFailed(files)
const failedSnap = hasFailedSnapshot(files)
const cancelled = this.ctx.isCancelling
if (failed)
this.ctx.logger.log(WAIT_FOR_CHANGE_FAIL)
else if (cancelled)
this.ctx.logger.log(WAIT_FOR_CHANGE_CANCELLED)
else
this.ctx.logger.log(WAIT_FOR_CHANGE_PASS)
const hints: string[] = []
// TODO typecheck doesn't support these for now
if (this.mode !== 'typecheck')
hints.push(HELP_HINT)
if (failedSnap)
hints.unshift(HELP_UPDATE_SNAP)
else
hints.push(HELP_QUITE)
this.ctx.logger.log(BADGE_PADDING + hints.join(c.dim(', ')))
if (this._lastRunCount) {
const LAST_RUN_TEXT = `rerun x${this._lastRunCount}`
const LAST_RUN_TEXTS = [
c.blue(LAST_RUN_TEXT),
c.gray(LAST_RUN_TEXT),
c.dim(c.gray(LAST_RUN_TEXT)),
]
this.ctx.logger.logUpdate(BADGE_PADDING + LAST_RUN_TEXTS[0])
this._lastRunTimeout = 0
const { setInterval } = getSafeTimers()
this._lastRunTimer = setInterval(
() => {
this._lastRunTimeout += 1
if (this._lastRunTimeout >= LAST_RUN_TEXTS.length)
this.resetLastRunLog()
else
this.ctx.logger.logUpdate(BADGE_PADDING + LAST_RUN_TEXTS[this._lastRunTimeout])
},
LAST_RUN_LOG_TIMEOUT / LAST_RUN_TEXTS.length,
)
}
}
private resetLastRunLog() {
const { clearInterval } = getSafeTimers()
clearInterval(this._lastRunTimer)
this._lastRunTimer = undefined
this.ctx.logger.logUpdate.clear()
}
async onWatcherRerun(files: string[], trigger?: string) {
this.resetLastRunLog()
this.watchFilters = files
files.forEach((filepath) => {
let reruns = this._filesInWatchMode.get(filepath) ?? 0
this._filesInWatchMode.set(filepath, ++reruns)
})
const BADGE = c.inverse(c.bold(c.blue(' RERUN ')))
const TRIGGER = trigger ? c.dim(` ${this.relative(trigger)}`) : ''
const FILENAME_PATTERN = this.ctx.filenamePattern ? `${BADGE_PADDING} ${c.dim('Filename pattern: ')}${c.blue(this.ctx.filenamePattern)}\n` : ''
const TESTNAME_PATTERN = this.ctx.configOverride.testNamePattern ? `${BADGE_PADDING} ${c.dim('Test name pattern: ')}${c.blue(String(this.ctx.configOverride.testNamePattern))}\n` : ''
if (files.length > 1) {
// we need to figure out how to handle rerun all from stdin
this.ctx.logger.clearFullScreen(`\n${BADGE}${TRIGGER}\n${FILENAME_PATTERN}${TESTNAME_PATTERN}`)
this._lastRunCount = 0
}
else if (files.length === 1) {
const rerun = this._filesInWatchMode.get(files[0]) ?? 1
this._lastRunCount = rerun
this.ctx.logger.clearFullScreen(`\n${BADGE}${TRIGGER} ${c.blue(`x${rerun}`)}\n${FILENAME_PATTERN}${TESTNAME_PATTERN}`)
}
this._timeStart = new Date()
this.start = performance.now()
}
onUserConsoleLog(log: UserConsoleLog) {
if (!this.shouldLog(log))
return
const task = log.taskId ? this.ctx.state.idMap.get(log.taskId) : undefined
const header = c.gray(log.type + c.dim(` | ${task ? getFullName(task, c.dim(' > ')) : 'unknown test'}`))
process[log.type].write(`${header}\n${log.content}\n`)
}
shouldLog(log: UserConsoleLog) {
if (this.ctx.config.silent)
return false
const shouldLog = this.ctx.config.onConsoleLog?.(log.content, log.type)
if (shouldLog === false)
return shouldLog
return true
}
onServerRestart(reason?: string) {
this.ctx.logger.log(c.bold(c.magenta(
reason === 'config'
? '\nRestarting due to config changes...'
: '\nRestarting Vitest...',
)))
}
async reportSummary(files: File[]) {
await this.printErrorsSummary(files)
if (this.mode === 'benchmark')
await this.reportBenchmarkSummary(files)
else
await this.reportTestSummary(files)
}
async reportTestSummary(files: File[]) {
const tests = getTests(files)
const logger = this.ctx.logger
const executionTime = this.end - this.start
const collectTime = files.reduce((acc, test) => acc + Math.max(0, test.collectDuration || 0), 0)
const setupTime = files.reduce((acc, test) => acc + Math.max(0, test.setupDuration || 0), 0)
const testsTime = files.reduce((acc, test) => acc + Math.max(0, test.result?.duration || 0), 0)
const transformTime = this.ctx.projects
.flatMap(w => Array.from(w.vitenode.fetchCache.values()).map(i => i.duration || 0))
.reduce((a, b) => a + b, 0)
const environmentTime = files.reduce((acc, file) => acc + Math.max(0, file.environmentLoad || 0), 0)
const prepareTime = files.reduce((acc, file) => acc + Math.max(0, file.prepareDuration || 0), 0)
const threadTime = collectTime + testsTime + setupTime
const padTitle = (str: string) => c.dim(`${str.padStart(11)} `)
const time = (time: number) => {
if (time > 1000)
return `${(time / 1000).toFixed(2)}s`
return `${Math.round(time)}ms`
}
// show top 10 costly transform module
// console.log(Array.from(this.ctx.vitenode.fetchCache.entries()).filter(i => i[1].duration)
// .sort((a, b) => b[1].duration! - a[1].duration!)
// .map(i => `${time(i[1].duration!)} ${i[0]}`)
// .slice(0, 10)
// .join('\n'),
// )
const snapshotOutput = renderSnapshotSummary(this.ctx.config.root, this.ctx.snapshot.summary)
if (snapshotOutput.length) {
logger.log(snapshotOutput.map((t, i) => i === 0
? `${padTitle('Snapshots')} ${t}`
: `${padTitle('')} ${t}`,
).join('\n'))
if (snapshotOutput.length > 1)
logger.log()
}
logger.log(padTitle('Test Files'), getStateString(files))
logger.log(padTitle('Tests'), getStateString(tests))
if (this.mode === 'typecheck') {
const failed = tests.filter(t => t.meta?.typecheck && t.result?.errors?.length)
logger.log(padTitle('Type Errors'), failed.length ? c.bold(c.red(`${failed.length} failed`)) : c.dim('no errors'))
}
logger.log(padTitle('Start at'), formatTimeString(this._timeStart))
if (this.watchFilters)
logger.log(padTitle('Duration'), time(threadTime))
else if (this.mode === 'typecheck')
logger.log(padTitle('Duration'), time(executionTime))
else
logger.log(padTitle('Duration'), time(executionTime) + c.dim(` (transform ${time(transformTime)}, setup ${time(setupTime)}, collect ${time(collectTime)}, tests ${time(testsTime)}, environment ${time(environmentTime)}, prepare ${time(prepareTime)})`))
logger.log()
}
private async printErrorsSummary(files: File[]) {
const logger = this.ctx.logger
const suites = getSuites(files)
const tests = getTests(files)
const failedSuites = suites.filter(i => i.result?.errors)
const failedTests = tests.filter(i => i.result?.state === 'fail')
const failedTotal = countTestErrors(failedSuites) + countTestErrors(failedTests)
let current = 1
const errorDivider = () => logger.error(`${c.red(c.dim(divider(`[${current++}/${failedTotal}]`, undefined, 1)))}\n`)
if (failedSuites.length) {
logger.error(c.red(divider(c.bold(c.inverse(` Failed Suites ${failedSuites.length} `)))))
logger.error()
await this.printTaskErrors(failedSuites, errorDivider)
}
if (failedTests.length) {
logger.error(c.red(divider(c.bold(c.inverse(` Failed Tests ${failedTests.length} `)))))
logger.error()
await this.printTaskErrors(failedTests, errorDivider)
}
return tests
}
async reportBenchmarkSummary(files: File[]) {
const logger = this.ctx.logger
const benches = getTests(files)
const topBenches = benches.filter(i => i.result?.benchmark?.rank === 1)
logger.log(`\n${c.cyan(c.inverse(c.bold(' BENCH ')))} ${c.cyan('Summary')}\n`)
for (const bench of topBenches) {
const group = bench.suite
if (!group)
continue
const groupName = getFullName(group, c.dim(' > '))
logger.log(` ${bench.name}${c.dim(` - ${groupName}`)}`)
const siblings = group.tasks
.filter(i => i.result?.benchmark && i !== bench)
.sort((a, b) => a.result!.benchmark!.rank - b.result!.benchmark!.rank)
for (const sibling of siblings) {
const number = `${(sibling.result!.benchmark!.mean / bench.result!.benchmark!.mean).toFixed(2)}x`
logger.log(` ${c.green(number)} ${c.gray('faster than')} ${sibling.name}`)
}
logger.log('')
}
}
private async printTaskErrors(tasks: Task[], errorDivider: () => void) {
const errorsQueue: [error: ErrorWithDiff | undefined, tests: Task[]][] = []
for (const task of tasks) {
// merge identical errors
task.result?.errors?.forEach((error) => {
const errorItem = error?.stackStr && errorsQueue.find(i => i[0]?.stackStr === error.stackStr)
if (errorItem)
errorItem[1].push(task)
else
errorsQueue.push([error, [task]])
})
}
for (const [error, tasks] of errorsQueue) {
for (const task of tasks) {
const filepath = (task as File)?.filepath || ''
const projectName = (task as File)?.projectName || task.file?.projectName
let name = getFullName(task, c.dim(' > '))
if (filepath)
name = `${name} ${c.dim(`[ ${this.relative(filepath)} ]`)}`
this.ctx.logger.error(`${c.red(c.bold(c.inverse(' FAIL ')))} ${formatProjectName(projectName)}${name}`)
}
await this.ctx.logger.printError(error)
errorDivider()
await Promise.resolve()
}
}
registerUnhandledRejection() {
process.on('unhandledRejection', async (err) => {
process.exitCode = 1
await this.ctx.logger.printError(err, true, 'Unhandled Rejection')
this.ctx.logger.error('\n\n')
process.exit(1)
})
}
}