-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathrun-helpers.js
337 lines (301 loc) · 8.41 KB
/
run-helpers.js
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
'use strict';
/**
* Helper scripts for the `run` command
* @see module:lib/cli/run
* @module
* @private
*/
const fs = require('fs');
const path = require('path');
const ansi = require('ansi-colors');
const debug = require('debug')('mocha:cli:run:helpers');
const minimatch = require('minimatch');
const Context = require('../context');
const Mocha = require('../mocha');
const utils = require('../utils');
const cwd = (exports.cwd = process.cwd());
/**
* Exits Mocha when tests + code under test has finished execution (default)
* @param {number} code - Exit code; typically # of failures
* @ignore
* @private
*/
const exitMochaLater = code => {
process.on('exit', () => {
process.exitCode = Math.min(code, 255);
});
};
/**
* Exits Mocha when Mocha itself has finished execution, regardless of
* what the tests or code under test is doing.
* @param {number} code - Exit code; typically # of failures
* @ignore
* @private
*/
const exitMocha = code => {
const clampedCode = Math.min(code, 255);
let draining = 0;
// Eagerly set the process's exit code in case stream.write doesn't
// execute its callback before the process terminates.
process.exitCode = clampedCode;
// flush output for Node.js Windows pipe bug
// https://github.com/joyent/node/issues/6247 is just one bug example
// https://github.com/visionmedia/mocha/issues/333 has a good discussion
const done = () => {
if (!draining--) {
process.exit(clampedCode);
}
};
const streams = [process.stdout, process.stderr];
streams.forEach(stream => {
// submit empty write request and wait for completion
draining += 1;
stream.write('', done);
});
done();
};
/**
* Hide the cursor.
* @ignore
* @private
*/
const hideCursor = () => {
process.stdout.write('\u001b[?25l');
};
/**
* Show the cursor.
* @ignore
* @private
*/
const showCursor = () => {
process.stdout.write('\u001b[?25h');
};
/**
* Stop cursor business
* @private
*/
const stop = () => {
process.stdout.write('\u001b[2K');
};
/**
* Coerce a comma-delimited string (or array thereof) into a flattened array of
* strings
* @param {string|string[]} str - Value to coerce
* @returns {string[]} Array of strings
* @private
*/
exports.list = str =>
Array.isArray(str) ? exports.list(str.join(',')) : str.split(/ *, */);
/**
* `require()` the modules as required by `--require <require>`
* @param {string[]} requires - Modules to require
* @private
*/
exports.handleRequires = (requires = []) => {
requires.forEach(mod => {
let modpath = mod;
if (fs.existsSync(mod, {cwd}) || fs.existsSync(`${mod}.js`, {cwd})) {
modpath = path.resolve(mod);
debug(`resolved ${mod} to ${modpath}`);
}
require(modpath);
debug(`loaded require "${mod}"`);
});
};
/**
* Smash together an array of test files in the correct order
* @param {Object} [opts] - Options
* @param {string[]} [opts.extension] - File extensions to use
* @param {string[]} [opts.spec] - Files, dirs, globs to run
* @param {string[]} [opts.exclude] - Files, dirs, globs to exclude
* @param {boolean} [opts.recursive=false] - Find files recursively
* @param {boolean} [opts.sort=false] - Sort test files
* @returns {string[]} List of files to test
* @private
*/
exports.handleFiles = ({
exclude = [],
extension = [],
file = [],
recursive = false,
sort = false,
spec = []
} = {}) => {
let files = [];
const unmatched = [];
spec.forEach(arg => {
let newFiles;
try {
newFiles = utils.lookupFiles(arg, extension, recursive);
} catch (err) {
if (err.code === 'ERR_MOCHA_NO_FILES_MATCH_PATTERN') {
unmatched.push({message: err.message, pattern: err.pattern});
return;
}
throw err;
}
if (typeof newFiles !== 'undefined') {
if (typeof newFiles === 'string') {
newFiles = [newFiles];
}
newFiles = newFiles.filter(fileName =>
exclude.every(pattern => !minimatch(fileName, pattern))
);
}
files = files.concat(newFiles);
});
if (!files.length) {
// give full message details when only 1 file is missing
const noneFoundMsg =
unmatched.length === 1
? `Error: No test files found: ${JSON.stringify(unmatched[0].pattern)}` // stringify to print escaped characters raw
: 'Error: No test files found';
console.error(ansi.red(noneFoundMsg));
process.exit(1);
} else {
// print messages as an warning
unmatched.forEach(warning => {
console.warn(ansi.yellow(`Warning: ${warning.message}`));
});
}
const fileArgs = file.map(filepath => path.resolve(filepath));
files = files.map(filepath => path.resolve(filepath));
// ensure we don't sort the stuff from fileArgs; order is important!
if (sort) {
files.sort();
}
// add files given through --file to be ran first
files = fileArgs.concat(files);
debug('files (in order): ', files);
return files;
};
/**
* Give Mocha files and tell it to run
* @param {Mocha} mocha - Mocha instance
* @param {Options} [opts] - Options
* @param {string[]} [opts.files] - List of test files
* @param {boolean} [opts.exit] - Whether or not to force-exit after tests are complete
* @returns {Runner}
* @private
*/
exports.singleRun = (mocha, {files = [], exit = false} = {}) => {
mocha.files = files;
return mocha.run(exit ? exitMocha : exitMochaLater);
};
/**
* Run Mocha in "watch" mode
* @param {Mocha} mocha - Mocha instance
* @param {Object} [opts] - Options
* @param {string[]} [opts.extension] - List of extensions to watch
* @param {string|RegExp} [opts.grep] - Grep for test titles
* @param {string} [opts.ui=bdd] - User interface
* @param {string[]} [files] - Array of test files
* @private
*/
exports.watchRun = (
mocha,
{extension = ['js'], grep = '', ui = 'bdd', files = []} = {}
) => {
let runner;
console.log();
hideCursor();
process.on('SIGINT', () => {
showCursor();
console.log('\n');
process.exit(130);
});
const watchFiles = utils.files(cwd, extension);
let runAgain = false;
const loadAndRun = () => {
try {
mocha.files = files;
runAgain = false;
runner = mocha.run(() => {
runner = null;
if (runAgain) {
rerun();
}
});
} catch (e) {
console.log(e.stack);
}
};
const purge = () => {
watchFiles.forEach(Mocha.unloadFile);
};
loadAndRun();
const rerun = () => {
purge();
stop();
if (!grep) {
mocha.grep(null);
}
mocha.suite = mocha.suite.clone();
mocha.suite.ctx = new Context();
mocha.ui(ui);
loadAndRun();
};
utils.watch(watchFiles, () => {
runAgain = true;
if (runner) {
runner.abort();
} else {
rerun();
}
});
};
/**
* Actually run tests
* @param {Mocha} mocha - Mocha instance
* @param {Object} [opts] - Options
* @param {boolean} [opts.watch=false] - Enable watch mode
* @param {string[]} [opts.extension] - List of extensions to watch
* @param {string|RegExp} [opts.grep] - Grep for test titles
* @param {string} [opts.ui=bdd] - User interface
* @param {boolean} [opts.exit=false] - Force-exit Mocha when tests done
* @param {string[]} [files] - Array of test files
* @private
*/
exports.runMocha = (
mocha,
{watch = false, extension = ['js'], grep = '', ui = 'bdd', exit = false} = {},
files = []
) => {
if (watch) {
exports.watchRun(mocha, {extension, grep, ui, files});
} else {
exports.singleRun(mocha, {files, exit});
}
};
/**
* Used for `--reporter` and `--ui`. Ensures there's only one, and asserts
* that it actually exists.
* @todo XXX This must get run after requires are processed, as it'll prevent
* interfaces from loading.
* @param {Object} opts - Options object
* @param {string} key - Resolvable module name or path
* @param {Object} [map] - An object perhaps having key `key`
* @private
*/
exports.validatePlugin = (opts, key, map = {}) => {
if (Array.isArray(opts[key])) {
throw new TypeError(`"--${key} <${key}>" can only be specified once`);
}
const unknownError = () => new Error(`Unknown "${key}": ${opts[key]}`);
if (!map[opts[key]]) {
try {
opts[key] = require(opts[key]);
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
// Try to load reporters from a path (absolute or relative)
try {
opts[key] = require(path.resolve(process.cwd(), opts[key]));
} catch (err) {
throw unknownError();
}
} else {
throw unknownError();
}
}
}
};