/
collect.ts
110 lines (94 loc) · 2.93 KB
/
collect.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
import type { File, ResolvedConfig, Suite } from '../types'
import { getWorkerState, isBrowser, relativePath } from '../utils'
import { interpretTaskModes, someTasksAreOnly } from '../utils/collect'
import { clearCollectorContext, defaultSuite } from './suite'
import { getHooks, setHooks } from './map'
import { processError } from './error'
import { collectorContext } from './context'
import { runSetupFiles } from './setup'
const now = Date.now
function hash(str: string): string {
let hash = 0
if (str.length === 0)
return `${hash}`
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i)
hash = (hash << 5) - hash + char
hash = hash & hash // Convert to 32bit integer
}
return `${hash}`
}
export async function collectTests(paths: string[], config: ResolvedConfig): Promise<File[]> {
const files: File[] = []
const browserHashMap = getWorkerState().browserHashMap!
async function importFromBrowser(filepath: string) {
const match = filepath.match(/^(\w:\/)/)
const hash = browserHashMap.get(filepath)
if (match)
return await import(`/@fs/${filepath.slice(match[1].length)}?v=${hash}`)
else
return await import(`${filepath}?v=${hash}`)
}
for (const filepath of paths) {
const path = relativePath(config.root, filepath)
const file: File = {
id: hash(path),
name: path,
type: 'suite',
mode: 'run',
filepath,
tasks: [],
projectName: config.name,
}
clearCollectorContext()
try {
const setupStart = now()
await runSetupFiles(config)
const collectStart = now()
file.setupDuration = collectStart - setupStart
if (config.browser && isBrowser)
await importFromBrowser(filepath)
else
await import(filepath)
const defaultTasks = await defaultSuite.collect(file)
setHooks(file, getHooks(defaultTasks))
for (const c of [...defaultTasks.tasks, ...collectorContext.tasks]) {
if (c.type === 'test') {
file.tasks.push(c)
}
else if (c.type === 'benchmark') {
file.tasks.push(c)
}
else if (c.type === 'suite') {
file.tasks.push(c)
}
else if (c.type === 'collector') {
const suite = await c.collect(file)
if (suite.name || suite.tasks.length)
file.tasks.push(suite)
}
}
file.collectDuration = now() - collectStart
}
catch (e) {
file.result = {
state: 'fail',
error: processError(e),
}
if (config.browser)
console.error(e)
}
calculateHash(file)
const hasOnlyTasks = someTasksAreOnly(file)
interpretTaskModes(file, config.testNamePattern, hasOnlyTasks, false, config.allowOnly)
files.push(file)
}
return files
}
function calculateHash(parent: Suite) {
parent.tasks.forEach((t, idx) => {
t.id = `${parent.id}_${idx}`
if (t.type === 'suite')
calculateHash(t)
})
}