-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathlistRenderer.ts
311 lines (275 loc) · 8.07 KB
/
listRenderer.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
import type { SuiteHooks, Task } from '@vitest/runner'
import type { Benchmark, BenchmarkResult } from '../../../runtime/types/benchmark'
import type { Logger } from '../../logger'
import type { VitestRunMode } from '../../types/config'
import { stripVTControlCharacters } from 'node:util'
import { getTests } from '@vitest/runner/utils'
import { notNullish } from '@vitest/utils'
import cliTruncate from 'cli-truncate'
import c from 'tinyrainbow'
import { F_RIGHT } from './figures'
import {
formatProjectName,
getCols,
getHookStateSymbol,
getStateSymbol,
} from './utils'
export interface ListRendererOptions {
renderSucceed?: boolean
logger: Logger
showHeap: boolean
slowTestThreshold: number
mode: VitestRunMode
}
const outputMap = new WeakMap<Task, string>()
function formatFilepath(path: string) {
const lastSlash = Math.max(path.lastIndexOf('/') + 1, 0)
const basename = path.slice(lastSlash)
let firstDot = basename.indexOf('.')
if (firstDot < 0) {
firstDot = basename.length
}
firstDot += lastSlash
return (
c.dim(path.slice(0, lastSlash))
+ path.slice(lastSlash, firstDot)
+ c.dim(path.slice(firstDot))
)
}
function formatNumber(number: number) {
const res = String(number.toFixed(number < 100 ? 4 : 2)).split('.')
return (
res[0].replace(/(?=(?:\d{3})+$)\B/g, ',') + (res[1] ? `.${res[1]}` : '')
)
}
function renderHookState(
task: Task,
hookName: keyof SuiteHooks,
level = 0,
): string {
const state = task.result?.hooks?.[hookName]
if (state && state === 'run') {
return `${' '.repeat(level)} ${getHookStateSymbol(task, hookName)} ${c.dim(
`[ ${hookName} ]`,
)}`
}
return ''
}
function renderBenchmarkItems(result: BenchmarkResult) {
return [
result.name,
formatNumber(result.hz || 0),
formatNumber(result.p99 || 0),
`±${result.rme.toFixed(2)}%`,
result.samples.length.toString(),
]
}
function renderBenchmark(task: Benchmark, tasks: Task[]): string {
const result = task.result?.benchmark
if (!result) {
return task.name
}
const benches = tasks
.map(i => (i.meta?.benchmark ? i.result?.benchmark : undefined))
.filter(notNullish)
const allItems = benches.map(renderBenchmarkItems)
const items = renderBenchmarkItems(result)
const padded = items.map((i, idx) => {
const width = Math.max(...allItems.map(i => i[idx].length))
return idx ? i.padStart(width, ' ') : i.padEnd(width, ' ') // name
})
return [
padded[0], // name
c.dim(' '),
c.blue(padded[1]),
c.dim(' ops/sec '),
c.cyan(padded[3]),
c.dim(` (${padded[4]} samples)`),
result.rank === 1
? c.bold(c.green(' fastest'))
: result.rank === benches.length && benches.length > 2
? c.bold(c.gray(' slowest'))
: '',
].join('')
}
function renderTree(
tasks: Task[],
options: ListRendererOptions,
level = 0,
maxRows?: number,
): string {
const output: string[] = []
let currentRowCount = 0
// Go through tasks in reverse order since maxRows is used to bail out early when limit is reached
for (const task of [...tasks].reverse()) {
const taskOutput = []
let suffix = ''
let prefix = ` ${getStateSymbol(task)} `
if (level === 0 && task.type === 'suite' && 'projectName' in task) {
prefix += formatProjectName(task.projectName)
}
if (level === 0 && task.type === 'suite' && task.meta.typecheck) {
prefix += c.bgBlue(c.bold(' TS '))
prefix += ' '
}
if (
task.type === 'test'
&& task.result?.retryCount
&& task.result.retryCount > 0
) {
suffix += c.yellow(` (retry x${task.result.retryCount})`)
}
if (task.type === 'suite') {
const tests = getTests(task)
suffix += c.dim(` (${tests.length})`)
}
if (task.mode === 'skip' || task.mode === 'todo') {
const note = task.result?.note || 'skipped'
suffix += ` ${c.dim(c.gray(`[${note}]`))}`
}
if (
task.type === 'test'
&& task.result?.repeatCount
&& task.result.repeatCount > 0
) {
suffix += c.yellow(` (repeat x${task.result.repeatCount})`)
}
if (task.result?.duration != null) {
if (task.result.duration > options.slowTestThreshold) {
suffix += c.yellow(
` ${Math.round(task.result.duration)}${c.dim('ms')}`,
)
}
}
if (options.showHeap && task.result?.heap != null) {
suffix += c.magenta(
` ${Math.floor(task.result.heap / 1024 / 1024)} MB heap used`,
)
}
let name = task.name
if (level === 0) {
name = formatFilepath(name)
}
const padding = ' '.repeat(level)
const body = task.meta?.benchmark
? renderBenchmark(task as Benchmark, tasks)
: name
taskOutput.push(padding + prefix + body + suffix)
if (task.result?.state !== 'pass' && outputMap.get(task) != null) {
let data: string | undefined = outputMap.get(task)
if (typeof data === 'string') {
data = stripVTControlCharacters(data.trim().split('\n').filter(Boolean).pop()!)
if (data === '') {
data = undefined
}
}
if (data != null) {
const out = `${' '.repeat(level)}${F_RIGHT} ${data}`
taskOutput.push(` ${c.gray(cliTruncate(out, getCols(-3)))}`)
}
}
taskOutput.push(renderHookState(task, 'beforeAll', level + 1))
taskOutput.push(renderHookState(task, 'beforeEach', level + 1))
if (task.type === 'suite' && task.tasks.length > 0) {
if (
task.result?.state === 'fail'
|| task.result?.state === 'run'
|| options.renderSucceed
) {
if (options.logger.ctx.config.hideSkippedTests) {
const filteredTasks = task.tasks.filter(
t => t.mode !== 'skip' && t.mode !== 'todo',
)
taskOutput.push(
renderTree(filteredTasks, options, level + 1, maxRows),
)
}
else {
taskOutput.push(renderTree(task.tasks, options, level + 1, maxRows))
}
}
}
taskOutput.push(renderHookState(task, 'afterAll', level + 1))
taskOutput.push(renderHookState(task, 'afterEach', level + 1))
const rows = taskOutput.filter(Boolean)
output.push(rows.join('\n'))
currentRowCount += rows.length
if (maxRows && currentRowCount >= maxRows) {
break
}
}
// TODO: moving windows
return output.reverse().join('\n')
}
export function createListRenderer(
_tasks: Task[],
options: ListRendererOptions,
) {
let tasks = _tasks
let timer: any
const log = options.logger.logUpdate
function update() {
if (options.logger.ctx.config.hideSkippedTests) {
const filteredTasks = tasks.filter(
t => t.mode !== 'skip' && t.mode !== 'todo',
)
log(
renderTree(
filteredTasks,
options,
0,
// log-update already limits the amount of printed rows to fit the current terminal
// but we can optimize performance by doing it ourselves
process.stdout.rows,
),
)
}
else {
log(
renderTree(
tasks,
options,
0,
// log-update already limits the amount of printed rows to fit the current terminal
// but we can optimize performance by doing it ourselves
process.stdout.rows,
),
)
}
}
return {
start() {
if (timer) {
return this
}
timer = setInterval(update, 16)
return this
},
update(_tasks: Task[]) {
tasks = _tasks
return this
},
stop() {
if (timer) {
clearInterval(timer)
timer = undefined
}
log.clear()
if (options.logger.ctx.config.hideSkippedTests) {
const filteredTasks = tasks.filter(
t => t.mode !== 'skip' && t.mode !== 'todo',
)
// Note that at this point the renderTree should output all tasks
options.logger.log(renderTree(filteredTasks, options))
}
else {
// Note that at this point the renderTree should output all tasks
options.logger.log(renderTree(tasks, options))
}
return this
},
clear() {
log.clear()
},
}
}