-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathindex.ts
310 lines (279 loc) · 8.85 KB
/
index.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
import type { Options } from 'tinyexec'
import type { UserConfig as ViteUserConfig } from 'vite'
import type { WorkspaceProjectConfiguration } from 'vitest/config'
import type { TestModule, UserConfig, Vitest, VitestRunMode } from 'vitest/node'
import { webcrypto as crypto } from 'node:crypto'
import fs from 'node:fs'
import { Readable, Writable } from 'node:stream'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'pathe'
import { x } from 'tinyexec'
import * as tinyrainbow from 'tinyrainbow'
import { afterEach, onTestFinished, type WorkerGlobalState } from 'vitest'
import { startVitest } from 'vitest/node'
import { getCurrentTest } from 'vitest/suite'
import { Cli } from './cli'
// override default colors to disable them in tests
Object.assign(tinyrainbow.default, tinyrainbow.getDefaultColors())
interface VitestRunnerCLIOptions {
std?: 'inherit'
fails?: boolean
}
export async function runVitest(
config: UserConfig,
cliFilters: string[] = [],
mode: VitestRunMode = 'test',
viteOverrides: ViteUserConfig = {},
runnerOptions: VitestRunnerCLIOptions = {},
) {
// Reset possible previous runs
process.exitCode = 0
let exitCode = process.exitCode
// Prevent possible process.exit() calls, e.g. from --browser
const exit = process.exit
process.exit = (() => { }) as never
const stdout = new Writable({
write(chunk, __, callback) {
if (runnerOptions.std === 'inherit') {
process.stdout.write(chunk.toString())
}
callback()
},
})
const stderr = new Writable({
write(chunk, __, callback) {
if (runnerOptions.std === 'inherit') {
process.stderr.write(chunk.toString())
}
callback()
},
})
// "node:tty".ReadStream doesn't work on Github Windows CI, let's simulate it
const stdin = new Readable({ read: () => '' }) as NodeJS.ReadStream
stdin.isTTY = true
stdin.setRawMode = () => stdin
const cli = new Cli({ stdin, stdout, stderr })
let ctx: Vitest | undefined
let thrown = false
try {
const { reporters, ...rest } = config
ctx = await startVitest(mode, cliFilters, {
watch: false,
// "none" can be used to disable passing "reporter" option so that default value is used (it's not same as reporters: ["default"])
...(reporters === 'none' ? {} : reporters ? { reporters } : { reporters: ['verbose'] }),
...rest,
env: {
NO_COLOR: 'true',
...rest.env,
},
}, {
...viteOverrides,
server: {
// we never need a websocket connection for the root config because it doesn't connect to the browser
// browser mode uses a separate config that doesn't inherit CLI overrides
ws: false,
watch: {
// During tests we edit the files too fast and sometimes chokidar
// misses change events, so enforce polling for consistency
// https://github.com/vitejs/vite/blob/b723a753ced0667470e72b4853ecda27b17f546a/playground/vitestSetup.ts#L211
usePolling: true,
interval: 100,
},
...viteOverrides?.server,
},
}, {
stdin,
stdout,
stderr,
})
}
catch (e: any) {
if (runnerOptions.fails !== true) {
console.error(e)
}
thrown = true
cli.stderr += e.stack
}
finally {
exitCode = process.exitCode
process.exitCode = 0
if (getCurrentTest()) {
onTestFinished(async () => {
await ctx?.close()
await ctx?.closingPromise
process.exit = exit
})
}
else {
afterEach(async () => {
await ctx?.close()
await ctx?.closingPromise
process.exit = exit
})
}
}
return {
thrown,
ctx,
exitCode,
vitest: cli,
stdout: cli.stdout,
stderr: cli.stderr,
waitForClose: async () => {
await new Promise<void>(resolve => ctx!.onClose(resolve))
return ctx?.closingPromise
},
}
}
export async function runCli(command: string, _options?: Partial<Options> | string, ...args: string[]) {
let options = _options
if (typeof _options === 'string') {
args.unshift(_options)
options = undefined
}
const subprocess = x(command, args, options as Options).process!
const cli = new Cli({
stdin: subprocess.stdin!,
stdout: subprocess.stdout!,
stderr: subprocess.stderr!,
})
let setDone: (value?: unknown) => void
const isDone = new Promise(resolve => (setDone = resolve))
subprocess.on('exit', () => setDone())
function output() {
return {
vitest: cli,
exitCode: subprocess.exitCode,
stdout: cli.stdout || '',
stderr: cli.stderr || '',
waitForClose: () => isDone,
}
}
// Manually stop the processes so that each test don't have to do this themselves
afterEach(async () => {
if (subprocess.exitCode === null) {
subprocess.kill()
}
await isDone
})
if (args.includes('--inspect') || args.includes('--inspect-brk')) {
return output()
}
if (args[0] !== 'list' && args.includes('--watch')) {
if (command === 'vitest') {
// Wait for initial test run to complete
await cli.waitForStdout('Waiting for file changes')
}
// make sure watcher is ready
await cli.waitForStdout('[debug] watcher is ready')
cli.stdout = cli.stdout.replace('[debug] watcher is ready\n', '')
}
else {
await isDone
}
return output()
}
export async function runVitestCli(_options?: Partial<Options> | string, ...args: string[]) {
process.env.VITE_TEST_WATCHER_DEBUG = 'true'
return runCli('vitest', _options, ...args)
}
export async function runViteNodeCli(_options?: Partial<Options> | string, ...args: string[]) {
process.env.VITE_TEST_WATCHER_DEBUG = 'true'
const { vitest, ...rest } = await runCli('vite-node', _options, ...args)
return { viteNode: vitest, ...rest }
}
export function getInternalState(): WorkerGlobalState {
// @ts-expect-error untyped global
return globalThis.__vitest_worker__
}
const originalFiles = new Map<string, string>()
const createdFiles = new Set<string>()
afterEach(() => {
originalFiles.forEach((content, file) => {
fs.writeFileSync(file, content, 'utf-8')
})
createdFiles.forEach((file) => {
if (fs.existsSync(file)) {
fs.unlinkSync(file)
}
})
originalFiles.clear()
createdFiles.clear()
})
export function createFile(file: string, content: string) {
createdFiles.add(file)
fs.mkdirSync(dirname(file), { recursive: true })
fs.writeFileSync(file, content, 'utf-8')
}
export function editFile(file: string, callback: (content: string) => string) {
const content = fs.readFileSync(file, 'utf-8')
if (!originalFiles.has(file)) {
originalFiles.set(file, content)
}
fs.writeFileSync(file, callback(content), 'utf-8')
}
export function resolvePath(baseUrl: string, path: string) {
const filename = fileURLToPath(baseUrl)
return resolve(dirname(filename), path)
}
export function useFS(root: string, structure: Record<string, string | ViteUserConfig | WorkspaceProjectConfiguration[]>) {
const files = new Set<string>()
const hasConfig = Object.keys(structure).some(file => file.includes('.config.'))
if (!hasConfig) {
structure['./vitest.config.js'] = {}
}
for (const file in structure) {
const filepath = resolve(root, file)
files.add(filepath)
const content = typeof structure[file] === 'string'
? structure[file]
: `export default ${JSON.stringify(structure[file])}`
fs.mkdirSync(dirname(filepath), { recursive: true })
fs.writeFileSync(filepath, String(content), 'utf-8')
}
onTestFinished(() => {
if (process.env.VITEST_FS_CLEANUP !== 'false') {
fs.rmSync(root, { recursive: true, force: true })
}
})
return {
editFile: (file: string, callback: (content: string) => string) => {
const filepath = resolve(root, file)
if (!files.has(filepath)) {
throw new Error(`file ${file} is outside of the test file system`)
}
const content = fs.readFileSync(filepath, 'utf-8')
fs.writeFileSync(filepath, callback(content))
},
createFile: (file: string, content: string) => {
if (file.startsWith('..')) {
throw new Error(`file ${file} is outside of the test file system`)
}
const filepath = resolve(root, file)
if (!files.has(filepath)) {
throw new Error(`file ${file} already exists in the test file system`)
}
createFile(filepath, content)
},
}
}
export async function runInlineTests(
structure: Record<string, string | ViteUserConfig | WorkspaceProjectConfiguration[]>,
config?: UserConfig,
) {
const root = resolve(process.cwd(), `vitest-test-${crypto.randomUUID()}`)
const fs = useFS(root, structure)
const vitest = await runVitest({
root,
...config,
})
return {
fs,
root,
...vitest,
get results() {
return (vitest.ctx?.state.getFiles() || []).map(file => vitest.ctx?.state.getReportedEntity(file) as TestModule)
},
}
}
export const ts = String.raw