/
setup.ts
200 lines (181 loc) · 5.45 KB
/
setup.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
/* eslint-disable n/no-deprecated-api */
import { installSourcemapsSupport } from 'vite-node/source-map'
import { environments } from '../integrations/env'
import type { Environment, ResolvedConfig } from '../types'
import { clearTimeout, getWorkerState, isNode, setTimeout, toArray } from '../utils'
import * as VitestIndex from '../index'
import { resetRunOnceCounter } from '../integrations/run-once'
import { RealDate } from '../integrations/mock/date'
import { rpc } from './rpc'
let globalSetup = false
export async function setupGlobalEnv(config: ResolvedConfig) {
resetRunOnceCounter()
Object.defineProperty(globalThis, '__vitest_index__', {
value: VitestIndex,
enumerable: false,
})
// should be re-declared for each test
// if run with "threads: false"
setupDefines(config.defines)
if (globalSetup)
return
// always mock "required" `css` files, because we cannot process them
require.extensions['.css'] = () => ({})
require.extensions['.scss'] = () => ({})
require.extensions['.sass'] = () => ({})
globalSetup = true
if (isNode) {
const state = getWorkerState()
installSourcemapsSupport({
getSourceMap: source => state.moduleCache.getSourceMap(source),
})
await setupConsoleLogSpy()
}
if (config.globals)
(await import('../integrations/globals')).registerApiGlobally()
}
function setupDefines(defines: Record<string, any>) {
for (const key in defines)
(globalThis as any)[key] = defines[key]
}
export async function setupConsoleLogSpy() {
const stdoutBuffer = new Map<string, any[]>()
const stderrBuffer = new Map<string, any[]>()
const timers = new Map<string, { stdoutTime: number; stderrTime: number; timer: any }>()
const unknownTestId = '__vitest__unknown_test__'
const { Writable } = await import('node:stream')
const { Console } = await import('node:console')
// group sync console.log calls with macro task
function schedule(taskId: string) {
const timer = timers.get(taskId)!
const { stdoutTime, stderrTime } = timer
clearTimeout(timer.timer)
timer.timer = setTimeout(() => {
if (stderrTime < stdoutTime) {
sendStderr(taskId)
sendStdout(taskId)
}
else {
sendStdout(taskId)
sendStderr(taskId)
}
})
}
function sendStdout(taskId: string) {
const buffer = stdoutBuffer.get(taskId)
if (!buffer)
return
const content = buffer.map(i => String(i)).join('')
if (!content.trim())
return
const timer = timers.get(taskId)!
rpc().onUserConsoleLog({
type: 'stdout',
content,
taskId,
time: timer.stdoutTime || RealDate.now(),
size: buffer.length,
})
stdoutBuffer.set(taskId, [])
timer.stdoutTime = 0
}
function sendStderr(taskId: string) {
const buffer = stderrBuffer.get(taskId)
if (!buffer)
return
const content = buffer.map(i => String(i)).join('')
if (!content.trim())
return
const timer = timers.get(taskId)!
rpc().onUserConsoleLog({
type: 'stderr',
content,
taskId,
time: timer.stderrTime || RealDate.now(),
size: buffer.length,
})
stderrBuffer.set(taskId, [])
timer.stderrTime = 0
}
const stdout = new Writable({
write(data, encoding, callback) {
const id = getWorkerState()?.current?.id ?? unknownTestId
let timer = timers.get(id)
if (timer) {
timer.stdoutTime = timer.stdoutTime || RealDate.now()
}
else {
timer = { stdoutTime: RealDate.now(), stderrTime: RealDate.now(), timer: 0 }
timers.set(id, timer)
}
let buffer = stdoutBuffer.get(id)
if (!buffer) {
buffer = []
stdoutBuffer.set(id, buffer)
}
buffer.push(data)
schedule(id)
callback()
},
})
const stderr = new Writable({
write(data, encoding, callback) {
const id = getWorkerState()?.current?.id ?? unknownTestId
let timer = timers.get(id)
if (timer) {
timer.stderrTime = timer.stderrTime || RealDate.now()
}
else {
timer = { stderrTime: RealDate.now(), stdoutTime: RealDate.now(), timer: 0 }
timers.set(id, timer)
}
let buffer = stderrBuffer.get(id)
if (!buffer) {
buffer = []
stderrBuffer.set(id, buffer)
}
buffer.push(data)
schedule(id)
callback()
},
})
globalThis.console = new Console({
stdout,
stderr,
colorMode: true,
groupIndentation: 2,
})
}
async function loadEnvironment(name: string) {
const pkg = await import(`vitest-environment-${name}`)
if (!pkg || !pkg.default || typeof pkg.default !== 'object' || typeof pkg.default.setup !== 'function') {
throw new Error(
`Environment "${name}" is not a valid environment. `
+ `Package "vitest-environment-${name}" should have default export with "setup" method.`,
)
}
return pkg.default
}
export async function withEnv(
name: ResolvedConfig['environment'],
options: ResolvedConfig['environmentOptions'],
fn: () => Promise<void>,
) {
const config: Environment = (environments as any)[name] || await loadEnvironment(name)
const env = await config.setup(globalThis, options)
try {
await fn()
}
finally {
await env.teardown(globalThis)
}
}
export async function runSetupFiles(config: ResolvedConfig) {
const files = toArray(config.setupFiles)
await Promise.all(
files.map(async (fsPath) => {
getWorkerState().moduleCache.delete(fsPath)
await import(fsPath)
}),
)
}