/
suite.ts
295 lines (244 loc) · 8.49 KB
/
suite.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
import util from 'util'
import { util as chaiUtil } from 'chai'
import type { BenchFunction, BenchOptions, Benchmark, BenchmarkAPI, File, RunMode, Suite, SuiteAPI, SuiteCollector, SuiteFactory, SuiteHooks, Task, Test, TestAPI, TestFunction, TestOptions } from '../types'
import { getWorkerState, isObject, isRunningInBenchmark, isRunningInTest, noop, objectAttr } from '../utils'
import { createChainable } from './chain'
import { collectTask, collectorContext, createTestContext, runWithSuite, withTimeout } from './context'
import { getHooks, setBenchOptions, setFn, setHooks } from './map'
// apis
export const suite = createSuite()
export const test = createTest(
function (name: string, fn?: TestFunction, options?: number | TestOptions) {
getCurrentSuite().test.fn.call(this, name, fn, options)
},
)
export const bench = createBenchmark(
function (name, fn: BenchFunction = noop, options: BenchOptions = {}) {
getCurrentSuite().benchmark.fn.call(this, name, fn, options)
},
)
// alias
export const describe = suite
export const it = test
const workerState = getWorkerState()
export const defaultSuite = workerState.config.sequence.shuffle
? suite.shuffle('')
: suite('')
export function clearCollectorContext() {
collectorContext.tasks.length = 0
defaultSuite.clear()
collectorContext.currentSuite = defaultSuite
}
export function getCurrentSuite<ExtraContext = {}>() {
return (collectorContext.currentSuite || defaultSuite) as SuiteCollector<ExtraContext>
}
export function createSuiteHooks() {
return {
beforeAll: [],
afterAll: [],
beforeEach: [],
afterEach: [],
}
}
// implementations
function createSuiteCollector(name: string, factory: SuiteFactory = () => { }, mode: RunMode, concurrent?: boolean, shuffle?: boolean, suiteOptions?: number | TestOptions) {
const tasks: (Benchmark | Test | Suite | SuiteCollector)[] = []
const factoryQueue: (Test | Suite | SuiteCollector)[] = []
let suite: Suite
initSuite()
const test = createTest(function (name: string, fn = noop, options = suiteOptions) {
if (!isRunningInTest())
throw new Error('`test()` and `it()` is only available in test mode.')
const mode = this.only ? 'only' : this.skip ? 'skip' : this.todo ? 'todo' : 'run'
if (typeof options === 'number')
options = { timeout: options }
const test: Test = {
id: '',
type: 'test',
name,
mode,
suite: undefined!,
fails: this.fails,
retry: options?.retry,
} as Omit<Test, 'context'> as Test
if (this.concurrent || concurrent)
test.concurrent = true
if (shuffle)
test.shuffle = true
const context = createTestContext(test)
// create test context
Object.defineProperty(test, 'context', {
value: context,
enumerable: false,
})
setFn(test, withTimeout(
() => fn(context),
options?.timeout,
))
tasks.push(test)
})
const benchmark = createBenchmark(function (name: string, fn = noop, options: BenchOptions = {}) {
const mode = this.only ? 'only' : this.skip ? 'skip' : this.todo ? 'todo' : 'run'
if (!isRunningInBenchmark())
throw new Error('`bench()` is only available in benchmark mode. Run with `vitest bench` instead.')
const benchmark: Benchmark = {
type: 'benchmark',
id: '',
name,
mode,
suite: undefined!,
}
setFn(benchmark, fn)
setBenchOptions(benchmark, options)
tasks.push(benchmark)
})
const collector: SuiteCollector = {
type: 'collector',
name,
mode,
test,
tasks,
benchmark,
collect,
clear,
on: addHook,
}
function addHook<T extends keyof SuiteHooks>(name: T, ...fn: SuiteHooks[T]) {
getHooks(suite)[name].push(...fn as any)
}
function initSuite() {
suite = {
id: '',
type: 'suite',
name,
mode,
shuffle,
tasks: [],
}
setHooks(suite, createSuiteHooks())
}
function clear() {
tasks.length = 0
factoryQueue.length = 0
initSuite()
}
async function collect(file?: File) {
factoryQueue.length = 0
if (factory)
await runWithSuite(collector, () => factory(test))
const allChildren: Task[] = []
for (const i of [...factoryQueue, ...tasks])
allChildren.push(i.type === 'collector' ? await i.collect(file) : i)
suite.file = file
suite.tasks = allChildren
allChildren.forEach((task) => {
task.suite = suite
if (file)
task.file = file
})
return suite
}
collectTask(collector)
return collector
}
function createSuite() {
function suiteFn(this: Record<string, boolean | undefined>, name: string, factory?: SuiteFactory, options?: number | TestOptions) {
const mode: RunMode = this.only ? 'only' : this.skip ? 'skip' : this.todo ? 'todo' : 'run'
return createSuiteCollector(name, factory, mode, this.concurrent, this.shuffle, options)
}
suiteFn.each = function<T>(this: { withContext: () => SuiteAPI }, cases: ReadonlyArray<T>, ...args: any[]) {
const suite = this.withContext()
if (Array.isArray(cases) && args.length)
cases = formatTemplateString(cases, args)
return (name: string, fn: (...args: T[]) => void, options?: number | TestOptions) => {
const arrayOnlyCases = cases.every(Array.isArray)
cases.forEach((i, idx) => {
const items = Array.isArray(i) ? i : [i]
arrayOnlyCases
? suite(formatTitle(name, items, idx), () => fn(...items), options)
: suite(formatTitle(name, items, idx), () => fn(i), options)
})
}
}
suiteFn.skipIf = (condition: any) => (condition ? suite.skip : suite) as SuiteAPI
suiteFn.runIf = (condition: any) => (condition ? suite : suite.skip) as SuiteAPI
return createChainable(
['concurrent', 'shuffle', 'skip', 'only', 'todo'],
suiteFn,
) as unknown as SuiteAPI
}
function createTest(fn: (
(
this: Record<'concurrent' | 'skip' | 'only' | 'todo' | 'fails', boolean | undefined>,
title: string,
fn?: TestFunction,
options?: number | TestOptions
) => void
)) {
const testFn = fn as any
testFn.each = function<T>(this: { withContext: () => TestAPI }, cases: ReadonlyArray<T>, ...args: any[]) {
const test = this.withContext()
if (Array.isArray(cases) && args.length)
cases = formatTemplateString(cases, args)
return (name: string, fn: (...args: T[]) => void, options?: number | TestOptions) => {
const arrayOnlyCases = cases.every(Array.isArray)
cases.forEach((i, idx) => {
const items = Array.isArray(i) ? i : [i]
arrayOnlyCases
? test(formatTitle(name, items, idx), () => fn(...items), options)
: test(formatTitle(name, items, idx), () => fn(i), options)
})
}
}
testFn.skipIf = (condition: any) => (condition ? test.skip : test) as TestAPI
testFn.runIf = (condition: any) => (condition ? test : test.skip) as TestAPI
return createChainable(
['concurrent', 'skip', 'only', 'todo', 'fails'],
testFn,
) as TestAPI
}
function createBenchmark(fn: (
(
this: Record<'skip' | 'only' | 'todo', boolean | undefined>,
name: string,
fn?: BenchFunction,
options?: BenchOptions
) => void
)) {
const benchmark = createChainable(
['skip', 'only', 'todo'],
fn,
) as BenchmarkAPI
benchmark.skipIf = (condition: any) => (condition ? benchmark.skip : benchmark) as BenchmarkAPI
benchmark.runIf = (condition: any) => (condition ? benchmark : benchmark.skip) as BenchmarkAPI
return benchmark as BenchmarkAPI
}
function formatTitle(template: string, items: any[], idx: number) {
if (template.includes('%#')) {
// '%#' match index of the test case
template = template
.replace(/%%/g, '__vitest_escaped_%__')
.replace(/%#/g, `${idx}`)
.replace(/__vitest_escaped_%__/g, '%%')
}
const count = template.split('%').length - 1
let formatted = util.format(template, ...items.slice(0, count))
if (isObject(items[0])) {
formatted = formatted.replace(/\$([$\w_.]+)/g,
(_, key) => chaiUtil.objDisplay(objectAttr(items[0], key)) as unknown as string,
// https://github.com/chaijs/chai/pull/1490
)
}
return formatted
}
function formatTemplateString(cases: any[], args: any[]): any[] {
const header = cases.join('').trim().replace(/ /g, '').split('\n').map(i => i.split('|'))[0]
const res: any[] = []
for (let i = 0; i < Math.floor((args.length) / header.length); i++) {
const oneCase: Record<string, any> = {}
for (let j = 0; j < header.length; j++)
oneCase[header[j]] = args[i * header.length + j] as any
res.push(oneCase)
}
return res
}