-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
suite.ts
447 lines (374 loc) · 14.2 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
import { format, isObject, objDisplay, objectAttr } from '@vitest/utils'
import { parseSingleStack } from '@vitest/utils/source-map'
import type { Custom, CustomAPI, File, Fixtures, RunMode, Suite, SuiteAPI, SuiteCollector, SuiteFactory, SuiteHooks, Task, TaskCustomOptions, Test, TestAPI, TestFunction, TestOptions } from './types'
import type { VitestRunner } from './types/runner'
import { createChainable } from './utils/chain'
import { collectTask, collectorContext, createTestContext, runWithSuite, withTimeout } from './context'
import { getHooks, setFixture, setFn, setHooks } from './map'
import type { FixtureItem } from './fixture'
import { mergeContextFixtures, withFixtures } from './fixture'
import { getCurrentTest } from './test-state'
// apis
export const suite = createSuite()
export const test = createTest(
function (name: string | Function, optionsOrFn?: TestOptions | TestFunction, optionsOrTest?: number | TestOptions | TestFunction) {
if (getCurrentTest())
throw new Error('Calling the test function inside another test function is not allowed. Please put it inside "describe" or "suite" so it can be properly collected.')
getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn as TestOptions, optionsOrTest as TestFunction)
},
)
// alias
export const describe = suite
export const it = test
let runner: VitestRunner
let defaultSuite: SuiteCollector
let currentTestFilepath: string
export function getDefaultSuite() {
return defaultSuite
}
export function getTestFilepath() {
return currentTestFilepath
}
export function getRunner() {
return runner
}
export function clearCollectorContext(filepath: string, currentRunner: VitestRunner) {
if (!defaultSuite)
defaultSuite = currentRunner.config.sequence.shuffle ? suite.shuffle('') : currentRunner.config.sequence.concurrent ? suite.concurrent('') : suite('')
runner = currentRunner
currentTestFilepath = filepath
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: [],
}
}
function parseArguments<T extends (...args: any[]) => any>(
optionsOrFn: T | object | undefined,
optionsOrTest: object | T | number | undefined,
) {
let options: TestOptions = {}
let fn: T = (() => {}) as T
// it('', () => {}, { retry: 2 })
if (typeof optionsOrTest === 'object') {
// it('', { retry: 2 }, { retry: 3 })
if (typeof optionsOrFn === 'object')
throw new TypeError('Cannot use two objects as arguments. Please provide options and a function callback in that order.')
// TODO: more info, add a name
// console.warn('The third argument is deprecated. Please use the second argument for options.')
options = optionsOrTest
}
// it('', () => {}, 1000)
else if (typeof optionsOrTest === 'number') {
options = { timeout: optionsOrTest }
}
// it('', { retry: 2 }, () => {})
else if (typeof optionsOrFn === 'object') {
options = optionsOrFn
}
if (typeof optionsOrFn === 'function') {
if (typeof optionsOrTest === 'function')
throw new TypeError('Cannot use two functions as arguments. Please use the second argument for options.')
fn = optionsOrFn as T
}
else if (typeof optionsOrTest === 'function') {
fn = optionsOrTest as T
}
return {
options,
handler: fn,
}
}
// implementations
function createSuiteCollector(name: string, factory: SuiteFactory = () => { }, mode: RunMode, shuffle?: boolean, each?: boolean, suiteOptions?: TestOptions) {
const tasks: (Test | Custom | Suite | SuiteCollector)[] = []
const factoryQueue: (Test | Suite | SuiteCollector)[] = []
let suite: Suite
initSuite(true)
const task = function (name = '', options: TaskCustomOptions = {}) {
const task: Custom = {
id: '',
name,
suite: undefined!,
each: options.each,
fails: options.fails,
context: undefined!,
type: 'custom',
retry: options.retry ?? runner.config.retry,
repeats: options.repeats,
mode: options.only ? 'only' : options.skip ? 'skip' : options.todo ? 'todo' : 'run',
meta: options.meta ?? Object.create(null),
}
const handler = options.handler
if (options.concurrent || (!options.sequential && runner.config.sequence.concurrent))
task.concurrent = true
if (shuffle)
task.shuffle = true
const context = createTestContext(task, runner)
// create test context
Object.defineProperty(task, 'context', {
value: context,
enumerable: false,
})
setFixture(context, options.fixtures)
if (handler) {
setFn(task, withTimeout(
withFixtures(handler, context),
options?.timeout ?? runner.config.testTimeout,
))
}
if (runner.config.includeTaskLocation) {
const limit = Error.stackTraceLimit
// custom can be called from any place, let's assume the limit is 15 stacks
Error.stackTraceLimit = 15
const error = new Error('stacktrace').stack!
Error.stackTraceLimit = limit
const stack = findTestFileStackTrace(error, task.each ?? false)
if (stack)
task.location = stack
}
tasks.push(task)
return task
}
const test = createTest(function (name: string | Function, optionsOrFn?: TestOptions | TestFunction, optionsOrTest?: number | TestOptions | TestFunction) {
let { options, handler } = parseArguments(
optionsOrFn,
optionsOrTest,
)
// inherit repeats, retry, timeout from suite
if (typeof suiteOptions === 'object')
options = Object.assign({}, suiteOptions, options)
// inherit concurrent / sequential from suite
options.concurrent = this.concurrent || (!this.sequential && options?.concurrent)
options.sequential = this.sequential || (!this.concurrent && options?.sequential)
const test = task(
formatName(name),
{ ...this, ...options, handler },
) as unknown as Test
test.type = 'test'
})
const collector: SuiteCollector = {
type: 'collector',
name,
mode,
options: suiteOptions,
test,
tasks,
collect,
task,
clear,
on: addHook,
}
function addHook<T extends keyof SuiteHooks>(name: T, ...fn: SuiteHooks[T]) {
getHooks(suite)[name].push(...fn as any)
}
function initSuite(includeLocation: boolean) {
if (typeof suiteOptions === 'number')
suiteOptions = { timeout: suiteOptions }
suite = {
id: '',
type: 'suite',
name,
mode,
each,
shuffle,
tasks: [],
meta: Object.create(null),
projectName: '',
}
if (runner && includeLocation && runner.config.includeTaskLocation) {
const limit = Error.stackTraceLimit
Error.stackTraceLimit = 15
const error = new Error('stacktrace').stack!
Error.stackTraceLimit = limit
const stack = findTestFileStackTrace(error, suite.each ?? false)
if (stack)
suite.location = stack
}
setHooks(suite, createSuiteHooks())
}
function clear() {
tasks.length = 0
factoryQueue.length = 0
initSuite(false)
}
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 | Function, factoryOrOptions?: SuiteFactory | TestOptions, optionsOrFactory: number | TestOptions | SuiteFactory = {}) {
const mode: RunMode = this.only ? 'only' : this.skip ? 'skip' : this.todo ? 'todo' : 'run'
const currentSuite = getCurrentSuite()
let { options, handler: factory } = parseArguments(
factoryOrOptions,
optionsOrFactory,
)
// inherit options from current suite
if (currentSuite?.options)
options = { ...currentSuite.options, ...options }
// inherit concurrent / sequential from current suite
options.concurrent = this.concurrent || (!this.sequential && options?.concurrent)
options.sequential = this.sequential || (!this.concurrent && options?.sequential)
return createSuiteCollector(formatName(name), factory, mode, this.shuffle, this.each, options)
}
suiteFn.each = function<T>(this: { withContext: () => SuiteAPI; setContext: (key: string, value: boolean | undefined) => SuiteAPI }, cases: ReadonlyArray<T>, ...args: any[]) {
const suite = this.withContext()
this.setContext('each', true)
if (Array.isArray(cases) && args.length)
cases = formatTemplateString(cases, args)
return (name: string | Function, optionsOrFn: ((...args: T[]) => void) | TestOptions, fnOrOptions?: ((...args: T[]) => void) | number | TestOptions) => {
const _name = formatName(name)
const arrayOnlyCases = cases.every(Array.isArray)
const { options, handler } = parseArguments(
optionsOrFn,
fnOrOptions,
)
cases.forEach((i, idx) => {
const items = Array.isArray(i) ? i : [i]
arrayOnlyCases
? suite(formatTitle(_name, items, idx), options, () => handler(...items))
: suite(formatTitle(_name, items, idx), options, () => handler(i))
})
this.setContext('each', undefined)
}
}
suiteFn.skipIf = (condition: any) => (condition ? suite.skip : suite) as SuiteAPI
suiteFn.runIf = (condition: any) => (condition ? suite : suite.skip) as SuiteAPI
return createChainable(
['concurrent', 'sequential', 'shuffle', 'skip', 'only', 'todo'],
suiteFn,
) as unknown as SuiteAPI
}
export function createTaskCollector(
fn: (...args: any[]) => any,
context?: Record<string, unknown>,
) {
const taskFn = fn as any
taskFn.each = function<T>(this: { withContext: () => SuiteAPI; setContext: (key: string, value: boolean | undefined) => SuiteAPI }, cases: ReadonlyArray<T>, ...args: any[]) {
const test = this.withContext()
this.setContext('each', true)
if (Array.isArray(cases) && args.length)
cases = formatTemplateString(cases, args)
return (name: string | Function, optionsOrFn: ((...args: T[]) => void) | TestOptions, fnOrOptions?: ((...args: T[]) => void) | number | TestOptions) => {
const _name = formatName(name)
const arrayOnlyCases = cases.every(Array.isArray)
const { options, handler } = parseArguments(
optionsOrFn,
fnOrOptions,
)
cases.forEach((i, idx) => {
const items = Array.isArray(i) ? i : [i]
arrayOnlyCases
? test(formatTitle(_name, items, idx), options, () => handler(...items))
: test(formatTitle(_name, items, idx), options, () => handler(i))
})
this.setContext('each', undefined)
}
}
taskFn.skipIf = function (this: TestAPI, condition: any) {
return condition ? this.skip : this
}
taskFn.runIf = function (this: TestAPI, condition: any) {
return condition ? this : this.skip
}
taskFn.extend = function (fixtures: Fixtures<Record<string, any>>) {
const _context = mergeContextFixtures(fixtures, context)
return createTest(function fn(name: string | Function, optionsOrFn?: TestOptions | TestFunction, optionsOrTest?: number | TestOptions | TestFunction) {
getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn as TestOptions, optionsOrTest as TestFunction)
}, _context)
}
const _test = createChainable(
['concurrent', 'sequential', 'skip', 'only', 'todo', 'fails'],
taskFn,
) as CustomAPI
if (context)
(_test as any).mergeContext(context)
return _test
}
function createTest(fn: (
(
this: Record<'concurrent' | 'sequential' | 'skip' | 'only' | 'todo' | 'fails' | 'each', boolean | undefined> & { fixtures?: FixtureItem[] },
title: string,
optionsOrFn?: TestOptions | TestFunction,
optionsOrTest?: number | TestOptions | TestFunction,
) => void
), context?: Record<string, any>) {
return createTaskCollector(fn, context) as TestAPI
}
function formatName(name: string | Function) {
return typeof name === 'string' ? name : name instanceof Function ? (name.name || '<anonymous>') : String(name)
}
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 = format(template, ...items.slice(0, count))
if (isObject(items[0])) {
formatted = formatted.replace(
/\$([$\w_.]+)/g,
// https://github.com/chaijs/chai/pull/1490
(_, key) => objDisplay(objectAttr(items[0], key), { truncate: runner?.config?.chaiConfig?.truncateThreshold }) as unknown as string,
)
}
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
}
function findTestFileStackTrace(error: string, each: boolean) {
// first line is the error message
const lines = error.split('\n').slice(1)
for (const line of lines) {
const stack = parseSingleStack(line)
if (stack && stack.file === getTestFilepath()) {
return {
line: stack.line,
/**
* test.each([1, 2])('name')
* ^ leads here, but should
* ^ lead here
* in source maps it's the same boundary, so it just points to the start of it
*/
column: each ? stack.column + 1 : stack.column,
}
}
}
}