/
run-helpers.js
243 lines (216 loc) · 6.7 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
'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 utils = require('../utils');
const watchRun = require('./watch-run');
const cwd = (exports.cwd = process.cwd());
exports.watchRun = watchRun;
/**
* 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();
};
/**
* 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.ignore] - Files, dirs, globs to ignore
* @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 = ({
ignore = [],
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 =>
ignore.every(pattern => !minimatch(fileName, pattern))
);
}
files = files.concat(newFiles);
});
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);
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}`));
});
}
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);
};
/**
* 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 = [], grep = '', ui = 'bdd', exit = false} = {},
files = []
) => {
if (watch) {
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();
}
}
}
};