/
logger.ts
234 lines (201 loc) · 7.83 KB
/
logger.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
import { createLogUpdate } from 'log-update'
import c from 'picocolors'
import { version } from '../../../../package.json'
import type { ErrorWithDiff } from '../types'
import type { TypeCheckError } from '../typecheck/typechecker'
import { getFullName, toArray } from '../utils'
import { highlightCode } from '../utils/colors'
import type { HangingOps } from '../runtime/runners/with-async-leaks-detecter'
import { divider } from './reporters/renderers/utils'
import { RandomSequencer } from './sequencers/RandomSequencer'
import type { Vitest } from './core'
import { printError } from './error'
import type { WorkspaceProject } from './workspace'
interface ErrorOptions {
type?: string
fullStack?: boolean
project?: WorkspaceProject
}
const ESC = '\x1B['
const ERASE_DOWN = `${ESC}J`
const ERASE_SCROLLBACK = `${ESC}3J`
const CURSOR_TO_START = `${ESC}1;1H`
const CLEAR_SCREEN = '\x1Bc'
export class Logger {
outputStream = process.stdout
errorStream = process.stderr
logUpdate = createLogUpdate(process.stdout)
private _clearScreenPending: string | undefined
private _highlights = new Map<string, string>()
constructor(
public ctx: Vitest,
public console = globalThis.console,
) {
this._highlights.clear()
}
log(...args: any[]) {
this._clearScreen()
this.console.log(...args)
}
error(...args: any[]) {
this._clearScreen()
this.console.error(...args)
}
warn(...args: any[]) {
this._clearScreen()
this.console.warn(...args)
}
clearFullScreen(message: string) {
if (!this.ctx.config.clearScreen) {
this.console.log(message)
return
}
this.console.log(`${ERASE_SCROLLBACK}${CLEAR_SCREEN}${message}`)
}
clearScreen(message: string, force = false) {
if (!this.ctx.config.clearScreen) {
this.console.log(message)
return
}
this._clearScreenPending = message
if (force)
this._clearScreen()
}
private _clearScreen() {
if (this._clearScreenPending == null)
return
const log = this._clearScreenPending
this._clearScreenPending = undefined
this.console.log(`${CURSOR_TO_START}${ERASE_DOWN}${log}`)
}
async printError(err: unknown, options: ErrorOptions = {}) {
const { fullStack = false, type } = options
const project = options.project ?? this.ctx.getCoreWorkspaceProject() ?? this.ctx.projects[0]
await printError(err, project, {
fullStack,
type,
showCodeFrame: true,
logger: this,
})
}
clearHighlightCache(filename?: string) {
if (filename)
this._highlights.delete(filename)
else
this._highlights.clear()
}
highlight(filename: string, source: string) {
if (this._highlights.has(filename))
return this._highlights.get(filename)!
const code = highlightCode(filename, source)
this._highlights.set(filename, code)
return code
}
printNoTestFound(filters?: string[]) {
const config = this.ctx.config
const comma = c.dim(', ')
if (filters?.length)
this.console.error(c.dim('filter: ') + c.yellow(filters.join(comma)))
const projectsFilter = toArray(config.project)
if (projectsFilter.length)
this.console.error(c.dim('projects: ') + c.yellow(projectsFilter.join(comma)))
this.ctx.projects.forEach((project) => {
const config = project.config
const name = project.getName()
const output = project.isCore() || !name ? '' : `[${name}]`
if (output)
this.console.error(c.bgCyan(`${output} Config`))
if (config.include)
this.console.error(c.dim('include: ') + c.yellow(config.include.join(comma)))
if (config.exclude)
this.console.error(c.dim('exclude: ') + c.yellow(config.exclude.join(comma)))
if (config.typecheck.enabled) {
this.console.error(c.dim('typecheck include: ') + c.yellow(config.typecheck.include.join(comma)))
this.console.error(c.dim('typecheck exclude: ') + c.yellow(config.typecheck.exclude.join(comma)))
}
})
if (config.watchExclude)
this.console.error(c.dim('watch exclude: ') + c.yellow(config.watchExclude.join(comma)))
if (config.watch && (config.changed || config.related?.length)) {
this.log(`No affected ${config.mode} files found\n`)
}
else {
if (config.passWithNoTests)
this.log(`No ${config.mode} files found, exiting with code 0\n`)
else
this.error(c.red(`\nNo ${config.mode} files found, exiting with code 1`))
}
}
printBanner() {
this.log()
const versionTest = this.ctx.config.watch
? c.blue(`v${version}`)
: c.cyan(`v${version}`)
const mode = this.ctx.config.watch
? c.blue(' DEV ')
: c.cyan(' RUN ')
this.log(`${c.inverse(c.bold(mode))} ${versionTest} ${c.gray(this.ctx.config.root)}`)
if (this.ctx.config.sequence.sequencer === RandomSequencer)
this.log(c.gray(` Running tests with seed "${this.ctx.config.sequence.seed}"`))
this.ctx.projects.forEach((project) => {
if (!project.browser)
return
const name = project.getName()
const output = project.isCore() ? '' : ` [${name}]`
const resolvedUrls = project.browser.resolvedUrls
const origin = resolvedUrls?.local[0] ?? resolvedUrls?.network[0]
this.log(c.dim(c.green(` ${output} Browser runner started at ${new URL('/', origin)}`)))
})
if (this.ctx.config.ui) {
this.log(c.dim(c.green(` UI started at http://${this.ctx.config.api?.host || 'localhost'}:${c.bold(`${this.ctx.server.config.server.port}`)}${this.ctx.config.uiBase}`)))
}
else if (this.ctx.config.api?.port) {
const resolvedUrls = this.ctx.server.resolvedUrls
// workaround for https://github.com/vitejs/vite/issues/15438, it was fixed in vite 5.1
const fallbackUrl = `http://${this.ctx.config.api.host || 'localhost'}:${this.ctx.config.api.port}`
const origin = resolvedUrls?.local[0] ?? resolvedUrls?.network[0] ?? fallbackUrl
this.log(c.dim(c.green(` API started at ${new URL('/', origin)}`)))
}
if (this.ctx.coverageProvider)
this.log(c.dim(' Coverage enabled with ') + c.yellow(this.ctx.coverageProvider.name))
this.log()
}
async printUnhandledErrors(errors: unknown[]) {
const errorMessage = c.red(c.bold(
`\nVitest caught ${errors.length} unhandled error${errors.length > 1 ? 's' : ''} during the test run.`
+ '\nThis might cause false positive tests. Resolve unhandled errors to make sure your tests are not affected.',
))
this.log(c.red(divider(c.bold(c.inverse(' Unhandled Errors ')))))
this.log(errorMessage)
await Promise.all(errors.map(async (err) => {
await this.printError(err, { fullStack: true, type: (err as ErrorWithDiff).type || 'Unhandled Error' })
}))
this.log(c.red(divider()))
}
async printSourceTypeErrors(errors: TypeCheckError[]) {
const errorMessage = c.red(c.bold(
`\nVitest found ${errors.length} error${errors.length > 1 ? 's' : ''} not related to your test files.`,
))
this.log(c.red(divider(c.bold(c.inverse(' Source Errors ')))))
this.log(errorMessage)
await Promise.all(errors.map(async (err) => {
await this.printError(err, { fullStack: true })
}))
this.log(c.red(divider()))
}
async printAsyncLeaksWarning(hangingOps: HangingOps[]) {
if (hangingOps.length === 0)
return
const errorMessage = c.yellow(c.bold(
`\nVitest has detected the following ${hangingOps.length} hanging operation${hangingOps.length > 1 ? 's' : ''} potentially keeping Vitest from exiting: \n`,
))
this.log(c.yellow(divider(c.bold(c.inverse(' Hanging Operations ')))))
this.log(errorMessage)
hangingOps.forEach(({ type, taskId, stack }) => {
const task = taskId && this.ctx.state.idMap.get(taskId)
this.log(type + c.dim(` | ${task ? getFullName(task) : taskId}`))
this.log(`${c.gray(c.dim(`${stack}`))}\n`)
})
this.log(c.yellow(divider()))
}
}