-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
305 lines (263 loc) · 7.81 KB
/
index.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
/*
* @japa/runner
*
* (c) Japa
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { fileURLToPath } from 'node:url'
import { ErrorsPrinter } from '@japa/errors-printer'
import type { TestExecutor } from '@japa/core/types'
import debug from './src/debug.js'
import validator from './src/validator.js'
import { Planner } from './src/planner.js'
import { GlobalHooks } from './src/hooks.js'
import { CliParser } from './src/cli_parser.js'
import { retryPlugin } from './src/plugins/retry.js'
import { ConfigManager } from './src/config_manager.js'
import { ExceptionsManager } from './src/exceptions_manager.js'
import { createTest, createTestGroup } from './src/create_test.js'
import type { CLIArgs, Config, NormalizedConfig } from './src/types.js'
import { Emitter, Group, Runner, Suite, Test, TestContext } from './modules/core/main.js'
type OmitFirstArg<F> = F extends [_: any, ...args: infer R] ? R : never
/**
* Global emitter instance used by the test
*/
const emitter = new Emitter()
/**
* The current active test
*/
let activeTest: Test<any> | undefined
/**
* Parsed commandline arguments
*/
let cliArgs: CLIArgs = {}
/**
* Hydrated config
*/
let runnerConfig: NormalizedConfig | undefined
/**
* The state refers to the phase where we configure suites and import
* test files. We stick this metadata to the test instance one can
* later reference within the test.
*/
const executionPlanState: {
phase: 'idle' | 'planning' | 'executing'
file?: string
suite?: Suite
group?: Group
timeout?: number
retries?: number
} = {
phase: 'idle',
}
/**
* Create a Japa test. Defining a test without the callback
* will create a todo test.
*/
export function test(title: string, callback?: TestExecutor<TestContext, undefined>) {
validator.ensureIsInPlanningPhase(executionPlanState.phase)
const testInstance = createTest(title, emitter, runnerConfig!.refiner, executionPlanState)
testInstance.setup((t) => {
activeTest = t
return () => {
activeTest = undefined
}
})
if (callback) {
testInstance.run(callback, new Error())
}
return testInstance
}
/**
* Create a Japa test group
*/
test.group = function (title: string, callback: (group: Group) => void) {
validator.ensureIsInPlanningPhase(executionPlanState.phase)
executionPlanState.group = createTestGroup(
title,
emitter,
runnerConfig!.refiner,
executionPlanState
)
/**
* Enable bail on the group an when bailLayer is set to "group"
*/
if (cliArgs.bail && cliArgs.bailLayer === 'group') {
executionPlanState.group.bail(true)
}
callback(executionPlanState.group)
executionPlanState.group = undefined
}
/**
* Create a test bound macro. Within the macro, you can access the
* currently executed test to read its context values or define
* cleanup hooks
*/
test.macro = function <T extends (test: Test, ...args: any[]) => any>(
callback: T
): (...args: OmitFirstArg<Parameters<T>>) => ReturnType<T> {
return (...args) => {
if (!activeTest) {
throw new Error('Cannot invoke macro outside of the test callback')
}
return callback(activeTest, ...args)
}
}
/**
* Get the test of currently running test
*/
export function getActiveTest() {
return activeTest
}
/**
* Make Japa process command line arguments. Later the parsed output
* will be used by Japa to compute the configuration
*/
export function processCLIArgs(argv: string[]) {
cliArgs = new CliParser().parse(argv)
}
/**
* Configure the tests runner with inline configuration. You must
* call configure method before the run method.
*
* Do note: The CLI flags will overwrite the options provided
* to the configure method.
*/
export function configure(options: Config) {
runnerConfig = new ConfigManager(options, cliArgs).hydrate()
}
/**
* Execute Japa tests. Calling this function will import the test
* files behind the scenes
*/
export async function run() {
/**
* Display help when help flag is used
*/
if (cliArgs.help) {
console.log(new CliParser().getHelp())
return
}
validator.ensureIsConfigured(runnerConfig)
executionPlanState.phase = 'planning'
const runner = new Runner(emitter)
/**
* Enable bail on the runner and all the layers after the
* runner when no specific bailLayer is specified
*/
if (cliArgs.bail && cliArgs.bailLayer === '') {
runner.bail(true)
}
const globalHooks = new GlobalHooks()
const exceptionsManager = new ExceptionsManager()
try {
/**
* Executing the retry plugin as the first thing
*/
await retryPlugin({ config: runnerConfig!, runner, emitter, cliArgs })
/**
* Step 1: Executing plugins before creating a plan, so that it can mutate
* the config
*/
for (let plugin of runnerConfig!.plugins) {
debug('executing "%s" plugin', plugin.name || 'anonymous')
await plugin({ runner, emitter, cliArgs, config: runnerConfig! })
}
/**
* Step 2: Creating an execution plan. The output is the result of
* applying all the filters and validations.
*/
const { config, reporters, suites, refinerFilters } = await new Planner(runnerConfig!).plan()
/**
* Step 3: Registering reporters and filters with the runner
*/
reporters.forEach((reporter) => {
debug('registering "%s" reporter', reporter.name)
runner.registerReporter(reporter)
})
refinerFilters.forEach((filter) => {
debug('apply %s filters "%O" ', filter.layer, filter.filters)
config.refiner.add(filter.layer, filter.filters)
})
config.refiner.matchAllTags(cliArgs.matchAll ?? false)
runner.onSuite(config.configureSuite)
/**
* Step 4: Running the setup hooks
*/
debug('executing global hooks')
globalHooks.apply(config)
await globalHooks.setup(runner)
/**
* Step 5: Register suites and import test files
*/
for (let suite of suites) {
/**
* Creating and configuring the suite
*/
executionPlanState.suite = new Suite(suite.name, emitter, config.refiner)
executionPlanState.retries = suite.retries
executionPlanState.timeout = suite.timeout
if (typeof suite.configure === 'function') {
suite.configure(executionPlanState.suite)
}
/**
* Enable bail on the suite and all the layers after the
* suite when bailLayer is set to "suite"
*/
if (cliArgs.bail && cliArgs.bailLayer === 'suite') {
executionPlanState.suite.bail(true)
}
runner.add(executionPlanState.suite)
/**
* Importing suite files
*/
for (let fileURL of suite.filesURLs) {
executionPlanState.file = fileURLToPath(fileURL)
debug('importing test file %s', executionPlanState.file)
await config.importer(fileURL)
}
/**
* Resetting global state
*/
executionPlanState.suite = undefined
}
/**
* Onto execution phase
*/
executionPlanState.phase = 'executing'
/**
* Monitor for unhandled erorrs and rejections
*/
exceptionsManager.monitor()
await runner.start()
await runner.exec()
await globalHooks.teardown(null, runner)
await runner.end()
/**
* Print unhandled errors
*/
await exceptionsManager.report()
const summary = runner.getSummary()
if (summary.hasError || exceptionsManager.hasErrors) {
process.exitCode = 1
}
if (config.forceExit) {
process.exit()
}
} catch (error) {
await globalHooks.teardown(error, runner)
const printer = new ErrorsPrinter()
await printer.printError(error)
/**
* Print unhandled errors in case the code inside
* the try block never got triggered
*/
await exceptionsManager.report()
process.exitCode = 1
if (runnerConfig!.forceExit) {
process.exit()
}
}
}