-
-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathfixture.ts
More file actions
274 lines (251 loc) · 7.6 KB
/
fixture.ts
File metadata and controls
274 lines (251 loc) · 7.6 KB
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
import test from '@playwright/test'
import assert from 'node:assert'
import { type SpawnOptions, spawn } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import { stripVTControlCharacters, styleText } from 'node:util'
import { x } from 'tinyexec'
function runCli(options: { command: string; label?: string } & SpawnOptions) {
const [name, ...args] = options.command.split(' ')
const child = x(name!, args, { nodeOptions: options }).process!
const label = `[${options.label ?? 'cli'}]`
let stdout = ''
let stderr = ''
child.stdout!.on('data', (data) => {
stdout += stripVTControlCharacters(String(data))
if (process.env.TEST_DEBUG) {
console.log(styleText('cyan', label), data.toString())
}
})
child.stderr!.on('data', (data) => {
stderr += stripVTControlCharacters(String(data))
console.log(styleText('magenta', label), data.toString())
})
const done = new Promise<void>((resolve) => {
child.on('exit', (code) => {
if (code !== 0 && code !== 143 && process.platform !== 'win32') {
console.log(styleText('magenta', `${label}`), `exit code ${code}`)
}
resolve()
})
})
async function findPort(): Promise<number> {
let stdout = ''
return new Promise((resolve) => {
child.stdout!.on('data', (data) => {
stdout += stripVTControlCharacters(String(data))
const match = stdout.match(/http:\/\/localhost:(\d+)/)
if (match) {
resolve(Number(match[1]))
}
})
})
}
function kill() {
if (process.platform === 'win32') {
spawn('taskkill', ['/pid', String(child.pid), '/t', '/f'])
} else {
child.kill()
}
}
return {
proc: child,
done,
findPort,
kill,
stdout: () => stdout,
stderr: () => stderr,
}
}
export type Fixture = ReturnType<typeof useFixture>
export function useFixture(options: {
root: string
mode?: 'dev' | 'build'
command?: string
buildCommand?: string
cliOptions?: SpawnOptions
}) {
let cleanup: (() => Promise<void>) | undefined
let baseURL!: string
const cwd = path.resolve(options.root)
let proc!: ReturnType<typeof runCli>
// TODO: `beforeAll` is called again on any test failure.
// https://playwright.dev/docs/test-retries
test.beforeAll(async () => {
if (options.mode === 'dev') {
proc = runCli({
command: options.command ?? `pnpm dev`,
label: `${options.root}:dev`,
cwd,
...options.cliOptions,
})
const port = await proc.findPort()
// TODO: use `test.extend` to set `baseURL`?
baseURL = `http://localhost:${port}`
cleanup = async () => {
proc.kill()
await proc.done
}
}
if (options.mode === 'build') {
if (!process.env.TEST_SKIP_BUILD) {
const proc = runCli({
command: options.buildCommand ?? `pnpm build`,
label: `${options.root}:build`,
cwd,
...options.cliOptions,
})
await proc.done
assert(proc.proc.exitCode === 0)
}
proc = runCli({
command: options.command ?? `pnpm preview`,
label: `${options.root}:preview`,
cwd,
...options.cliOptions,
})
const port = await proc.findPort()
baseURL = `http://localhost:${port}`
cleanup = async () => {
proc.kill()
await proc.done
}
}
})
test.afterAll(async () => {
await cleanup?.()
})
const createEditor = useCreateEditor(cwd)
return {
mode: options.mode,
root: cwd,
url: (url: string = './') => new URL(url, baseURL).href,
createEditor,
proc: () => proc,
}
}
export function useCreateEditor(cwd: string) {
const originalFiles: Record<string, string> = {}
test.afterAll(async () => {
for (const [filepath, content] of Object.entries(originalFiles)) {
fs.writeFileSync(filepath, content)
}
})
function createEditor(filepath: string) {
filepath = path.resolve(cwd, filepath)
const init = fs.readFileSync(filepath, 'utf-8')
originalFiles[filepath] ??= init
let current = init
return {
read: () => current,
edit(editFn: (data: string) => string): void {
const next = editFn(current)
assert(next !== current, 'Edit function did not change the content')
current = next
fs.writeFileSync(filepath, next)
},
reset(): void {
fs.writeFileSync(filepath, originalFiles[filepath]!)
},
resave(): void {
fs.writeFileSync(filepath, current)
},
}
}
return createEditor
}
export async function setupIsolatedFixture(options: {
src: string
dest: string
overrides?: Record<string, string>
}) {
// copy fixture
fs.rmSync(options.dest, { recursive: true, force: true })
fs.cpSync(options.src, options.dest, {
recursive: true,
filter: (src) => !src.includes('node_modules'),
})
// extract workspace overrides
const rootDir = path.join(import.meta.dirname, '..', '..', '..')
const workspaceYaml = fs.readFileSync(
path.join(rootDir, 'pnpm-workspace.yaml'),
'utf-8',
)
const overridesMatch = workspaceYaml.match(
/overrides:\s*([\s\S]*?)(?=\n\w|\n*$)/,
)
const overridesSection = overridesMatch ? overridesMatch[0] : 'overrides:'
const overrides = {
'@vitejs/plugin-rsc': `file:${path.join(rootDir, 'packages/plugin-rsc')}`,
'@vitejs/plugin-react': `file:${path.join(rootDir, 'packages/plugin-react')}`,
...options.overrides,
}
const tempWorkspaceYaml = `\
${overridesSection}
${Object.entries(overrides)
.map(([k, v]) => ` ${JSON.stringify(k)}: ${JSON.stringify(v)}`)
.join('\n')}
`
fs.writeFileSync(
path.join(options.dest, 'pnpm-workspace.yaml'),
tempWorkspaceYaml,
)
// install
await x('pnpm', ['i'], {
throwOnError: true,
nodeOptions: {
cwd: options.dest,
stdio: [
'ignore',
process.env.TEST_DEBUG ? 'inherit' : 'ignore',
'inherit',
],
},
})
}
// inspired by
// https://github.com/remix-run/react-router/blob/433872f6ab098eaf946cc6c9cf80abf137420ad2/integration/helpers/vite.ts#L239
// for syntax highlighting of /* js */, use this extension
// https://github.com/mjbvz/vscode-comment-tagged-templates
export async function setupInlineFixture(options: {
src: string
dest: string
files?: Record<
string,
string | { cp: string } | { edit: (s: string) => string }
>
}) {
fs.rmSync(options.dest, { recursive: true, force: true })
fs.mkdirSync(options.dest, { recursive: true })
// copy src
fs.cpSync(options.src, options.dest, {
recursive: true,
filter: (src) => !src.includes('node_modules') && !src.includes('dist'),
})
// write additional files
if (options.files) {
for (let [filename, contents] of Object.entries(options.files)) {
const destFile = path.join(options.dest, filename)
fs.mkdirSync(path.dirname(destFile), { recursive: true })
// custom command
if (typeof contents === 'object' && 'cp' in contents) {
const srcFile = path.join(options.dest, contents.cp)
fs.copyFileSync(srcFile, destFile)
continue
}
if (typeof contents === 'object' && 'edit' in contents) {
const editted = contents.edit(fs.readFileSync(destFile, 'utf-8'))
fs.writeFileSync(destFile, editted)
continue
}
// write a new file
contents = contents.replace(/^\n*/, '').replace(/\s*$/, '\n')
const indent = contents.match(/^\s*/)?.[0] ?? ''
const strippedContents = contents
.split('\n')
.map((line) => line.replace(new RegExp(`^${indent}`), ''))
.join('\n')
fs.writeFileSync(destFile, strippedContents)
}
}
}