/
runtime.ts
314 lines (276 loc) · 9.44 KB
/
runtime.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
312
313
314
import { Config } from '@jest/types'
import { sync as spawnSync } from 'cross-spawn'
import { createHash } from 'crypto'
import stringifyJson = require('fast-json-stable-stringify')
import {
copySync,
ensureSymlinkSync,
existsSync,
mkdirpSync,
outputFileSync,
outputJsonSync,
readFileSync,
readJsonSync,
readdirSync,
realpathSync,
removeSync,
renameSync,
statSync,
symlinkSync,
writeFileSync,
} from 'fs-extra'
import { stringify as stringifyJson5 } from 'json5'
import merge = require('lodash.merge')
import { join, relative, resolve, sep } from 'path'
import * as Paths from '../../../scripts/lib/paths'
import RunResult from './run-result'
import { PreparedTest, RunTestOptions } from './types'
import { enableOptimizations, templateNameForPath } from './utils'
const TEMPLATE_EXCLUDED_ITEMS = ['node_modules', 'package-lock.json']
const EVAL_SOURCE = `
describe.skip('__eval', () => {
test.skip('__test', () => {
expect(true).toBe(true);
});
it.skip('__test', () => {
expect(true).toBe(true);
});
});
eval(process.env.__TS_JEST_EVAL);
`
// tslint:disable-next-line:variable-name
let __hooksSource: string
function hooksSourceWith(vars: Record<string, any>): string {
if (!__hooksSource) {
__hooksSource = readFileSync(join(__dirname, '__hooks-source__.js.hbs'), 'utf8')
}
return __hooksSource.replace(/\{\{([^\}]+)\}\}/g, (_, key) => JSON.stringify(vars[key]))
}
export function run(name: string, options: RunTestOptions = {}): RunResult {
const { env = {}, template, inject, writeIo, noCache, jestConfigPath: configFile = 'jest.config.js' } = options
const { workdir: dir, sourceDir } = prepareTest(
name,
template || templateNameForPath(join(Paths.e2eSourceDir, name)),
options,
)
const pkg = readJsonSync(join(dir, 'package.json'))
const jestConfigPath = (path: string = dir) => resolve(path, configFile)
// grab base configuration
let baseConfig: Config.InitialOptions = require(jestConfigPath())
if (configFile === 'package.json') baseConfig = (baseConfig as any).jest
const extraConfig = {} as Config.InitialOptions
let shortCmd: string
let cmdArgs: string[] = []
if (inject) {
extraConfig.testMatch = undefined
extraConfig.testRegex = '/__eval\\.ts$'
}
if (process.argv.find(v => ['--updateSnapshot', '-u'].includes(v))) {
cmdArgs.push('-u')
}
if (!inject && pkg.scripts && pkg.scripts.test) {
cmdArgs = ['npm', '-s', 'run', 'test', '--', ...cmdArgs]
shortCmd = 'npm'
} else {
cmdArgs.unshift(join('node_modules', '.bin', 'jest'))
shortCmd = 'jest'
}
// extends config
if (options.jestConfig) {
merge(extraConfig, options.jestConfig)
}
if (options.tsJestConfig) {
const globalConfig: any = extraConfig.globals || (extraConfig.globals = {})
const tsJestConfig = globalConfig['ts-jest'] || (globalConfig['ts-jest'] = {})
merge(tsJestConfig, options.tsJestConfig)
}
// cache dir
if (noCache || writeIo) {
cmdArgs.push('--no-cache')
extraConfig.cacheDirectory = undefined
} else if (!(baseConfig.cacheDirectory || extraConfig.cacheDirectory)) {
// force the cache directory if not set
extraConfig.cacheDirectory = join(Paths.cacheDir, `e2e-${template}`)
}
// build final config and create dir suffix based on it
const finalConfig = merge({}, baseConfig, extraConfig)
const digest = createHash('sha1')
.update(stringifyJson(finalConfig))
.digest('hex')
// this must be in the same path hierarchy as dir
const nextDirPrefix = `${dir}-${digest.substr(0, 7)}.`
let index = 1
while (existsSync(`${nextDirPrefix}${index}`)) index++
const nextDir = `${nextDirPrefix}${index}`
// move the directory related to config digest
renameSync(dir, nextDir)
// write final config
// FIXME: sounds like the json fail to be encoded as an arg
if (false /* enableOptimizations() */) {
cmdArgs.push('--config', JSON.stringify(finalConfig))
} else if (Object.keys(extraConfig).length !== 0) {
if (configFile === 'package.json') {
pkg.jest = finalConfig
outputJsonSync(jestConfigPath(nextDir), pkg)
} else {
outputFileSync(jestConfigPath(nextDir), `module.exports = ${JSON.stringify(finalConfig, null, 2)}`, 'utf8')
}
}
// ensure we run in band
if (!cmdArgs.includes('--runInBand')) {
cmdArgs.push('--runInBand')
}
const cmd = cmdArgs.shift() as string
if (cmdArgs[cmdArgs.length - 1] === '--') cmdArgs.pop()
// extend env
const localEnv: any = { ...env }
if (inject) {
const injected = typeof inject === 'function' ? `(${inject.toString()}).apply(this);` : inject
localEnv.__TS_JEST_EVAL = injected
}
if (writeIo) {
localEnv.TS_JEST_HOOKS = defaultHooksFile('.')
}
// arguments to give to spawn
const spawnOptions: { env: Record<string, string>; cwd: string } = { env: localEnv } as any
// create started script for debugging
if (!enableOptimizations()) {
outputFileSync(
join(nextDir, '__launch.js'),
`
const { execFile } = require('child_process')
const cmd = ${stringifyJson5(cmd, null, 2)}
const args = ${stringifyJson5(cmdArgs, null, 2)}
const options = ${stringifyJson5(spawnOptions, null, 2)}
options.env = Object.assign({}, process.env, options.env)
execFile(cmd, args, options)
`,
'utf8',
)
}
// extend env with our env
spawnOptions.env = { ...process.env, ...localEnv }
spawnOptions.cwd = nextDir
// run jest
const result = spawnSync(cmd, cmdArgs, spawnOptions)
// we need to copy each snapshot which does NOT exists in the source dir
if (!enableOptimizations()) {
readdirSync(nextDir).forEach(item => {
if (item === 'node_modules' || !statSync(join(nextDir, item)).isDirectory()) {
return
}
const srcDir = join(sourceDir, item)
const wrkDir = join(nextDir, item)
// do not try to copy a linked root snapshots
if (item === '__snapshots__' && existsSync(srcDir)) return
copySync(wrkDir, srcDir, {
overwrite: false,
filter: from => {
return relative(sourceDir, from)
.split(sep)
.includes('__snapshots__')
},
})
})
}
return new RunResult(realpathSync(nextDir), result, {
cmd: shortCmd,
args: cmdArgs,
env: localEnv,
ioDir: writeIo ? ioDirForPath(nextDir) : undefined,
config: finalConfig,
digest,
})
}
export function prepareTest(name: string, template: string, options: RunTestOptions = {}): PreparedTest {
const sourceDir = join(Paths.e2eSourceDir, name)
// working directory is in the temp directory, different for each template name
const caseWorkdir = join(Paths.e2eWorkDir, template, name)
const templateDir = join(Paths.e2eWorkTemplatesDir, template)
// config utils
const configUtils = {
merge: (...objects: any[]) => merge({}, ...objects),
}
// recreate the directory
removeSync(caseWorkdir)
mkdirpSync(caseWorkdir)
const tmplModulesDir = join(templateDir, 'node_modules')
const caseModulesDir = join(caseWorkdir, 'node_modules')
// link the node_modules dir if the template has one
if (existsSync(tmplModulesDir)) {
// It's important to mark this symlink as 'dir' or tests fail
// with permission issues on windows.
symlinkSync(tmplModulesDir, caseModulesDir, 'dir')
}
// copy files from the template to the case dir
readdirSync(templateDir).forEach(item => {
if (TEMPLATE_EXCLUDED_ITEMS.includes(item)) {
return
}
copySync(join(templateDir, item), join(caseWorkdir, item))
})
// copy source and test files
const snapshotDirs: Record<string, 0> = Object.create(null)
copySync(sourceDir, caseWorkdir, {
filter: (src, dest) => {
const relPath = relative(sourceDir, src)
const segments = relPath.split(sep)
if (segments.includes('__snapshots__')) {
// link snapshots
while (segments[segments.length - 1] !== '__snapshots__') {
segments.pop()
}
snapshotDirs[segments.join(sep)] = 0
return false
} else if (relPath === 'jest.config.js') {
// extend base if it's a function
let baseConfig = {}
if (existsSync(dest)) {
baseConfig = require(dest)
}
const mod = require(src)
if (typeof mod === 'function') {
writeFileSync(dest, `module.exports = ${JSON.stringify(mod(baseConfig, configUtils))}`)
return false
}
return true
} else {
return true
}
},
})
// create symbolic links for the existing snapshots
Object.keys(snapshotDirs).forEach(dir => {
ensureSymlinkSync(join(sourceDir, dir), join(caseWorkdir, dir))
})
// create the special files
outputFileSync(join(caseWorkdir, '__eval.ts'), EVAL_SOURCE, 'utf8')
let ioDir!: string
// hooks
if (options.writeIo) {
ioDir = ioDirForPath(caseWorkdir)
mkdirpSync(ioDir)
const hooksFile = defaultHooksFile(caseWorkdir)
outputFileSync(
hooksFile,
hooksSourceWith({
writeProcessIoTo: ioDirForPath('.') || false,
}),
'utf8',
)
}
// create a package.json if it does not exists, and/or enforce the package name
const pkgFile = join(caseWorkdir, 'package.json')
const pkg: any = existsSync(pkgFile) ? readJsonSync(pkgFile) : {}
pkg.name = name
pkg.private = true
pkg.version = `0.0.0-mock0`
outputJsonSync(pkgFile, pkg, { spaces: 2 })
return { workdir: caseWorkdir, templateDir, sourceDir }
}
function ioDirForPath(path: string) {
return join(path, '__io__')
}
function defaultHooksFile(path: string) {
return join(path, '__hooks.js')
}