Spaces:
Running
Running
File size: 10,842 Bytes
5c2ed06 |
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 |
'use strict';
const logSymbols = require('log-symbols');
const debug = require('debug')('mocha:cli:watch');
const path = require('path');
const chokidar = require('chokidar');
const Context = require('../context');
const collectFiles = require('./collect-files');
/**
* Exports the `watchRun` function that runs mocha in "watch" mode.
* @see module:lib/cli/run-helpers
* @module
* @private
*/
/**
* Run Mocha in parallel "watch" mode
* @param {Mocha} mocha - Mocha instance
* @param {Object} opts - Options
* @param {string[]} [opts.watchFiles] - List of paths and patterns to
* watch. If not provided all files with an extension included in
* `fileCollectionParams.extension` are watched. See first argument of
* `chokidar.watch`.
* @param {string[]} opts.watchIgnore - List of paths and patterns to
* exclude from watching. See `ignored` option of `chokidar`.
* @param {FileCollectionOptions} fileCollectParams - Parameters that control test
* @private
*/
exports.watchParallelRun = (
mocha,
{watchFiles, watchIgnore},
fileCollectParams
) => {
debug('creating parallel watcher');
return createWatcher(mocha, {
watchFiles,
watchIgnore,
beforeRun({mocha}) {
// I don't know why we're cloning the root suite.
const rootSuite = mocha.suite.clone();
// ensure we aren't leaking event listeners
mocha.dispose();
// this `require` is needed because the require cache has been cleared. the dynamic
// exports set via the below call to `mocha.ui()` won't work properly if a
// test depends on this module (see `required-tokens.spec.js`).
const Mocha = require('../mocha');
// ... and now that we've gotten a new module, we need to use it again due
// to `mocha.ui()` call
const newMocha = new Mocha(mocha.options);
// don't know why this is needed
newMocha.suite = rootSuite;
// nor this
newMocha.suite.ctx = new Context();
// reset the list of files
newMocha.files = collectFiles(fileCollectParams);
// because we've swapped out the root suite (see the `run` inner function
// in `createRerunner`), we need to call `mocha.ui()` again to set up the context/globals.
newMocha.ui(newMocha.options.ui);
// we need to call `newMocha.rootHooks` to set up rootHooks for the new
// suite
newMocha.rootHooks(newMocha.options.rootHooks);
// in parallel mode, the main Mocha process doesn't actually load the
// files. this flag prevents `mocha.run()` from autoloading.
newMocha.lazyLoadFiles(true);
return newMocha;
},
fileCollectParams
});
};
/**
* Run Mocha in "watch" mode
* @param {Mocha} mocha - Mocha instance
* @param {Object} opts - Options
* @param {string[]} [opts.watchFiles] - List of paths and patterns to
* watch. If not provided all files with an extension included in
* `fileCollectionParams.extension` are watched. See first argument of
* `chokidar.watch`.
* @param {string[]} opts.watchIgnore - List of paths and patterns to
* exclude from watching. See `ignored` option of `chokidar`.
* @param {FileCollectionOptions} fileCollectParams - Parameters that control test
* file collection. See `lib/cli/collect-files.js`.
* @private
*/
exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
debug('creating serial watcher');
return createWatcher(mocha, {
watchFiles,
watchIgnore,
beforeRun({mocha}) {
mocha.unloadFiles();
// I don't know why we're cloning the root suite.
const rootSuite = mocha.suite.clone();
// ensure we aren't leaking event listeners
mocha.dispose();
// this `require` is needed because the require cache has been cleared. the dynamic
// exports set via the below call to `mocha.ui()` won't work properly if a
// test depends on this module (see `required-tokens.spec.js`).
const Mocha = require('../mocha');
// ... and now that we've gotten a new module, we need to use it again due
// to `mocha.ui()` call
const newMocha = new Mocha(mocha.options);
// don't know why this is needed
newMocha.suite = rootSuite;
// nor this
newMocha.suite.ctx = new Context();
// reset the list of files
newMocha.files = collectFiles(fileCollectParams);
// because we've swapped out the root suite (see the `run` inner function
// in `createRerunner`), we need to call `mocha.ui()` again to set up the context/globals.
newMocha.ui(newMocha.options.ui);
// we need to call `newMocha.rootHooks` to set up rootHooks for the new
// suite
newMocha.rootHooks(newMocha.options.rootHooks);
return newMocha;
},
fileCollectParams
});
};
/**
* Bootstraps a chokidar watcher. Handles keyboard input & signals
* @param {Mocha} mocha - Mocha instance
* @param {Object} opts
* @param {BeforeWatchRun} [opts.beforeRun] - Function to call before
* `mocha.run()`
* @param {string[]} [opts.watchFiles] - List of paths and patterns to watch. If
* not provided all files with an extension included in
* `fileCollectionParams.extension` are watched. See first argument of
* `chokidar.watch`.
* @param {string[]} [opts.watchIgnore] - List of paths and patterns to exclude
* from watching. See `ignored` option of `chokidar`.
* @param {FileCollectionOptions} opts.fileCollectParams - List of extensions to watch if `opts.watchFiles` is not given.
* @returns {FSWatcher}
* @ignore
* @private
*/
const createWatcher = (
mocha,
{watchFiles, watchIgnore, beforeRun, fileCollectParams}
) => {
if (!watchFiles) {
watchFiles = fileCollectParams.extension.map(ext => `**/*.${ext}`);
}
debug('ignoring files matching: %s', watchIgnore);
let globalFixtureContext;
// we handle global fixtures manually
mocha.enableGlobalSetup(false).enableGlobalTeardown(false);
const watcher = chokidar.watch(watchFiles, {
ignored: watchIgnore,
ignoreInitial: true
});
const rerunner = createRerunner(mocha, watcher, {
beforeRun
});
watcher.on('ready', async () => {
if (!globalFixtureContext) {
debug('triggering global setup');
globalFixtureContext = await mocha.runGlobalSetup();
}
rerunner.run();
});
watcher.on('all', () => {
rerunner.scheduleRun();
});
hideCursor();
process.on('exit', () => {
showCursor();
});
// this is for testing.
// win32 cannot gracefully shutdown via a signal from a parent
// process; a `SIGINT` from a parent will cause the process
// to immediately exit. during normal course of operation, a user
// will type Ctrl-C and the listener will be invoked, but this
// is not possible in automated testing.
// there may be another way to solve this, but it too will be a hack.
// for our watch tests on win32 we must _fork_ mocha with an IPC channel
if (process.connected) {
process.on('message', msg => {
if (msg === 'SIGINT') {
process.emit('SIGINT');
}
});
}
let exiting = false;
process.on('SIGINT', async () => {
showCursor();
console.error(`${logSymbols.warning} [mocha] cleaning up, please wait...`);
if (!exiting) {
exiting = true;
if (mocha.hasGlobalTeardownFixtures()) {
debug('running global teardown');
try {
await mocha.runGlobalTeardown(globalFixtureContext);
} catch (err) {
console.error(err);
}
}
process.exit(130);
}
});
// Keyboard shortcut for restarting when "rs\n" is typed (ala Nodemon)
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', data => {
const str = data
.toString()
.trim()
.toLowerCase();
if (str === 'rs') rerunner.scheduleRun();
});
return watcher;
};
/**
* Create an object that allows you to rerun tests on the mocha instance.
*
* @param {Mocha} mocha - Mocha instance
* @param {FSWatcher} watcher - chokidar `FSWatcher` instance
* @param {Object} [opts] - Options!
* @param {BeforeWatchRun} [opts.beforeRun] - Function to call before `mocha.run()`
* @returns {Rerunner}
* @ignore
* @private
*/
const createRerunner = (mocha, watcher, {beforeRun} = {}) => {
// Set to a `Runner` when mocha is running. Set to `null` when mocha is not
// running.
let runner = null;
// true if a file has changed during a test run
let rerunScheduled = false;
const run = () => {
try {
mocha = beforeRun ? beforeRun({mocha, watcher}) || mocha : mocha;
runner = mocha.run(() => {
debug('finished watch run');
runner = null;
blastCache(watcher);
if (rerunScheduled) {
rerun();
} else {
console.error(`${logSymbols.info} [mocha] waiting for changes...`);
}
});
} catch (e) {
console.error(e.stack);
}
};
const scheduleRun = () => {
if (rerunScheduled) {
return;
}
rerunScheduled = true;
if (runner) {
runner.abort();
} else {
rerun();
}
};
const rerun = () => {
rerunScheduled = false;
eraseLine();
run();
};
return {
scheduleRun,
run
};
};
/**
* Return the list of absolute paths watched by a chokidar watcher.
*
* @param watcher - Instance of a chokidar watcher
* @return {string[]} - List of absolute paths
* @ignore
* @private
*/
const getWatchedFiles = watcher => {
const watchedDirs = watcher.getWatched();
return Object.keys(watchedDirs).reduce(
(acc, dir) => [
...acc,
...watchedDirs[dir].map(file => path.join(dir, file))
],
[]
);
};
/**
* Hide the cursor.
* @ignore
* @private
*/
const hideCursor = () => {
process.stdout.write('\u001b[?25l');
};
/**
* Show the cursor.
* @ignore
* @private
*/
const showCursor = () => {
process.stdout.write('\u001b[?25h');
};
/**
* Erases the line on stdout
* @private
*/
const eraseLine = () => {
process.stdout.write('\u001b[2K');
};
/**
* Blast all of the watched files out of `require.cache`
* @param {FSWatcher} watcher - chokidar FSWatcher
* @ignore
* @private
*/
const blastCache = watcher => {
const files = getWatchedFiles(watcher);
files.forEach(file => {
delete require.cache[file];
});
debug('deleted %d file(s) from the require cache', files.length);
};
/**
* Callback to be run before `mocha.run()` is called.
* Optionally, it can return a new `Mocha` instance.
* @callback BeforeWatchRun
* @private
* @param {{mocha: Mocha, watcher: FSWatcher}} options
* @returns {Mocha}
*/
/**
* Object containing run control methods
* @typedef {Object} Rerunner
* @private
* @property {Function} run - Calls `mocha.run()`
* @property {Function} scheduleRun - Schedules another call to `run`
*/
|