Skip to content

armgit / mocha

Public Imported from GitHub
0

☕️ Classic, reliable, trusted test framework for Node.js and the browser

chore: convert worker pool modules to ESM (#6015)

Ayush163289d0b29a
diff --git a/lib/mocha.cjs b/lib/mocha.cjs
index d1f22841..ce031145 100644
--- a/lib/mocha.cjs
+++ b/lib/mocha.cjs
@@ -1137,7 +1137,7 @@ Mocha.prototype.parallelMode = function parallelMode(enable = true) {
// swap Runner class
this._runnerClass = parallel
- ? require("./nodejs/parallel-buffered-runner.cjs")
+ ? require("./nodejs/parallel-buffered-runner.js").ParallelBufferedRunner
: exports.Runner;
// lazyLoadFiles may have been set `true` otherwise (for ESM loading),
diff --git a/lib/nodejs/buffered-worker-pool.cjs b/lib/nodejs/buffered-worker-pool.js
similarity index 79%
rename from lib/nodejs/buffered-worker-pool.cjs
rename to lib/nodejs/buffered-worker-pool.js
index cd357df9..c4e91c5b 100644
--- a/lib/nodejs/buffered-worker-pool.cjs
+++ b/lib/nodejs/buffered-worker-pool.js
@@ -5,7 +5,12 @@
* @module buffered-worker-pool
*/
-"use strict";
+import { fileURLToPath } from "node:url";
+import debugFactory from "debug";
+import serializeJavascript from "serialize-javascript";
+import workerpool from "workerpool";
+import { createInvalidArgumentTypeError } from "../errors.js";
+import { deserialize } from "./serializer.js";
/**
* @typedef {import('workerpool').WorkerPoolOptions} WorkerPoolOptions
@@ -13,18 +18,14 @@
* @typedef {import('../types.d.ts').SerializedWorkerResult} SerializedWorkerResult
*/
-const serializeJavascript = require("serialize-javascript");
-const workerpool = require("workerpool");
-const { deserialize } = require("./serializer.js");
-const debug = require("debug")("mocha:parallel:buffered-worker-pool");
-const { createInvalidArgumentTypeError } = require("../errors.js");
+const debug = debugFactory("mocha:parallel:buffered-worker-pool");
-const WORKER_PATH = require.resolve("./worker.cjs");
+const WORKER_PATH = fileURLToPath(new URL("./worker.js", import.meta.url));
/**
* A mapping of Mocha `Options` objects to serialized values.
*
- * This is helpful because we tend to same the same options over and over
+ * This is helpful because we tend to send the same options repeatedly
* over IPC.
* @type {WeakMap<MochaOptions,string>}
*/
@@ -47,7 +48,7 @@ const WORKER_POOL_DEFAULT_OPTS = {
* A wrapper around a third-party worker pool implementation.
* @private
*/
-class BufferedWorkerPool {
+export class BufferedWorkerPool {
/**
* Creates an underlying worker pool instance; determines max worker count
* @param {Partial<WorkerPoolOptions>} [opts] - Options
@@ -118,7 +119,7 @@ class BufferedWorkerPool {
*
* Handles serialization/deserialization.
*
- * @param {string} filepath - Filepath of test
+ * @param {string} filepath - Filepath of test file
* @param {MochaOptions} [options] - Options for Mocha instance
* @private
* @returns {Promise<SerializedWorkerResult>}
@@ -165,21 +166,26 @@ class BufferedWorkerPool {
*/
static serializeOptions(opts = {}) {
if (!optionsCache.has(opts)) {
- const serialized = serializeJavascript(opts, {
- unsafe: true, // this means we don't care about XSS
- ignoreFunction: true, // do not serialize functions
- });
- optionsCache.set(opts, serialized);
- /* istanbul ignore next */
- debug(
- "serializeOptions(): serialized options %O to: %s",
- opts,
- serialized,
- );
+ BufferedWorkerPool.serializeOptionsInternal(opts);
}
return optionsCache.get(opts);
}
+ /**
+ * Hard-updates internal cache of serialized options objects.
+ * (Separate function for test spies)
+ * @private
+ */
+ static serializeOptionsInternal(opts) {
+ const serialized = serializeJavascript(opts, {
+ unsafe: true, // this means we don't care about XSS
+ ignoreFunction: true, // do not serialize functions
+ });
+ optionsCache.set(opts, serialized);
+ /* istanbul ignore next */
+ debug("serializeOptions(): serialized options %O to: %s", opts, serialized);
+ }
+
/**
* Resets internal cache of serialized options objects.
*
@@ -190,5 +196,3 @@ class BufferedWorkerPool {
optionsCache = new WeakMap();
}
}
-
-exports.BufferedWorkerPool = BufferedWorkerPool;
diff --git a/lib/nodejs/parallel-buffered-runner.cjs b/lib/nodejs/parallel-buffered-runner.js
similarity index 95%
rename from lib/nodejs/parallel-buffered-runner.cjs
rename to lib/nodejs/parallel-buffered-runner.js
index 6041c7df..66766795 100644
--- a/lib/nodejs/parallel-buffered-runner.cjs
+++ b/lib/nodejs/parallel-buffered-runner.js
@@ -4,7 +4,12 @@
* @private
*/
-"use strict";
+import { fileURLToPath } from "node:url";
+import debugFactory from "debug";
+import { Runner } from "../runner.js";
+import { createFatalError } from "../errors.js";
+import utils from "../utils.cjs";
+import { BufferedWorkerPool } from "./buffered-worker-pool.js";
/**
* @typedef {import('../types.d.ts').FileRunner} FileRunner
@@ -13,17 +18,15 @@
* @typedef {import('../types.d.ts').SigIntListener} SigIntListener
*/
-const { Runner } = require("../runner.js");
const { EVENT_RUN_BEGIN, EVENT_RUN_END } = Runner.constants;
-const debug = require("debug")("mocha:parallel:parallel-buffered-runner");
-const { BufferedWorkerPool } = require("./buffered-worker-pool.cjs");
+const debug = debugFactory("mocha:parallel:parallel-buffered-runner");
const { setInterval, clearInterval } = global;
-const { createMap, constants } = require("../utils.cjs");
+const { createMap, constants } = utils;
const { MOCHA_ID_PROP_NAME } = constants;
-const { createFatalError } = require("../errors.js");
-const DEFAULT_WORKER_REPORTER =
- require.resolve("./reporters/parallel-buffered.cjs");
+const DEFAULT_WORKER_REPORTER = fileURLToPath(
+ new URL("./reporters/parallel-buffered.js", import.meta.url),
+);
/**
* List of options to _not_ serialize for transmission to workers
@@ -81,7 +84,7 @@ const states = createMap({
* {@link Runnable}s by itself!
* @public
*/
-class ParallelBufferedRunner extends Runner {
+export class ParallelBufferedRunner extends Runner {
constructor(...args) {
super(...args);
@@ -425,5 +428,3 @@ class ParallelBufferedRunner extends Runner {
return this;
}
}
-
-module.exports = ParallelBufferedRunner;
diff --git a/lib/nodejs/reporters/parallel-buffered.cjs b/lib/nodejs/reporters/parallel-buffered.js
similarity index 92%
rename from lib/nodejs/reporters/parallel-buffered.cjs
rename to lib/nodejs/reporters/parallel-buffered.js
index e4e8830e..240c0648 100644
--- a/lib/nodejs/reporters/parallel-buffered.cjs
+++ b/lib/nodejs/reporters/parallel-buffered.js
@@ -4,7 +4,10 @@
* @public
*/
-"use strict";
+import debugFactory from "debug";
+import { Runner } from "../../runner.js";
+import { Base } from "../../reporters/base.js";
+import { SerializableEvent, SerializableWorkerResult } from "../serializer.js";
/**
* @typedef {import('../../types.d.ts').BufferedEvent} BufferedEvent
@@ -29,13 +32,8 @@ const {
EVENT_HOOK_BEGIN,
EVENT_HOOK_END,
EVENT_RUN_END,
-} = require("../../runner.js").Runner.constants;
-const {
- SerializableEvent,
- SerializableWorkerResult,
-} = require("../serializer.js");
-const debug = require("debug")("mocha:reporters:buffered");
-const { Base } = require("../../reporters/base.js");
+} = Runner.constants;
+const debug = debugFactory("mocha:reporters:buffered");
/**
* List of events to listen to; these will be buffered and sent
@@ -68,7 +66,7 @@ const ONCE_EVENT_NAMES = [EVENT_DELAY_BEGIN, EVENT_DELAY_END];
* process.
* @public
*/
-class ParallelBuffered extends Base {
+export class ParallelBuffered extends Base {
/**
* Calls {@link ParallelBuffered#createListeners}
* @param {Runner} runner
@@ -161,4 +159,4 @@ class ParallelBuffered extends Base {
}
}
-module.exports = ParallelBuffered;
+export default ParallelBuffered;
diff --git a/lib/nodejs/worker-core.js b/lib/nodejs/worker-core.js
new file mode 100644
index 00000000..f03e04f9
--- /dev/null
+++ b/lib/nodejs/worker-core.js
@@ -0,0 +1,185 @@
+/**
+ * Worker runtime helpers for parallel mode.
+ * @module worker-core
+ * @private
+ */
+
+import debugModule from "debug";
+import Mocha from "../mocha.cjs";
+import runHelpers from "../cli/run-helpers.cjs";
+import {
+ createInvalidArgumentTypeError,
+ createInvalidArgumentValueError,
+} from "../errors.js";
+import { serialize } from "./serializer.js";
+import workerpool from "workerpool";
+
+/**
+ * @typedef {import('../types.d.ts').BufferedEvent} BufferedEvent
+ * @typedef {import('../types.d.ts').MochaOptions} MochaOptions
+ */
+
+const { setInterval, clearInterval } = global;
+const { handleRequires, validateLegacyPlugin } = runHelpers;
+
+const debug = debugModule(`mocha:parallel:worker:${process.pid}`);
+const isDebugEnabled = debugModule.enabled(
+ `mocha:parallel:worker:${process.pid}`,
+);
+
+/**
+ * Factory to create workers.
+ * Param should only be used for testing.
+ * @returns A worker ready to be added to a pool and started.
+ */
+const createWorker = ({
+ // This param object has a prop named Mocha.
+ // We assign that prop to our existing Mocha value by default.
+ // To disambiguate, we alias the prop as MochaImpl.
+ // Same for other "___Impl" props
+ Mocha: MochaImpl = Mocha,
+ handleRequires: handleRequiresImpl = handleRequires,
+ serialize: serializeImpl = serialize,
+ validateLegacyPlugin: validateLegacyPluginImpl = validateLegacyPlugin,
+} = {}) => {
+ let rootHooks;
+
+ /**
+ * Initializes some stuff on the first call to {@link run}.
+ *
+ * Handles `--require` and `--ui`. Does _not_ handle `--reporter`,
+ * as only the `Buffered` reporter is used.
+ *
+ * **This function only runs once per worker**; it overwrites itself with a no-op
+ * before returning.
+ *
+ * @param {MochaOptions} argv - Command-line options
+ */
+ let bootstrap = async (argv) => {
+ // globalSetup and globalTeardown do not run in workers
+ const plugins = await handleRequiresImpl(argv.require, {
+ ignoredPlugins: ["mochaGlobalSetup", "mochaGlobalTeardown"],
+ });
+ validateLegacyPluginImpl(argv, "ui", MochaImpl.interfaces);
+
+ rootHooks = plugins.rootHooks;
+ bootstrap = () => {};
+ debug("bootstrap(): finished with args: %O", argv);
+ };
+
+ /**
+ * Runs a single test file in a worker process.
+ * @param {string} filepath - Filepath of test file
+ * @param {string} [serializedOptions] - **Serialized** options. This string will be eval'd!
+ * @see https://npm.im/serialize-javascript
+ * @returns {Promise<{failures: number, events: BufferedEvent[]}>} - Test
+ * failure count and list of events.
+ */
+ async function run(filepath, serializedOptions = "{}") {
+ if (!filepath) {
+ throw createInvalidArgumentTypeError(
+ 'Expected a non-empty "filepath" argument',
+ "filepath",
+ "string",
+ );
+ }
+
+ debug("run(): running test file %s", filepath);
+
+ if (typeof serializedOptions !== "string") {
+ throw createInvalidArgumentTypeError(
+ "run() expects second parameter to be a string which was serialized by the `serialize-javascript` module",
+ "serializedOptions",
+ "string",
+ );
+ }
+ let argv;
+ try {
+ argv = eval("(" + serializedOptions + ")");
+ } catch {
+ throw createInvalidArgumentValueError(
+ "run() was unable to deserialize the options",
+ "serializedOptions",
+ serializedOptions,
+ );
+ }
+
+ const opts = Object.assign({ ui: "bdd" }, argv, {
+ // if this was true, it would cause infinite recursion.
+ parallel: false,
+ // this doesn't work in parallel mode
+ forbidOnly: true,
+ // it's useful for a Mocha instance to know if it's running in a worker process.
+ isWorker: true,
+ });
+
+ await bootstrap(opts);
+
+ opts.rootHooks = rootHooks;
+
+ const mocha = new MochaImpl(opts).addFile(filepath);
+
+ try {
+ await mocha.loadFilesAsync();
+ } catch (err) {
+ debug("run(): could not load file %s: %s", filepath, err);
+ throw err;
+ }
+
+ return new Promise((resolve, reject) => {
+ let debugInterval;
+ /* istanbul ignore next */
+ if (isDebugEnabled) {
+ debugInterval = setInterval(() => {
+ debug("run(): still running %s...", filepath);
+ }, 5000).unref();
+ }
+ mocha.run((result) => {
+ // Runner adds these; if we don't remove them, we'll get a leak.
+ process.removeAllListeners("uncaughtException");
+ process.removeAllListeners("unhandledRejection");
+
+ try {
+ const serialized = serializeImpl(result);
+ debug(
+ "run(): completed run with %d test failures; returning to main process",
+ typeof result.failures === "number" ? result.failures : 0,
+ );
+ resolve(serialized);
+ } catch (err) {
+ // TODO: figure out exactly what the sad path looks like here.
+ // rejection should only happen if an error is "unrecoverable"
+ debug("run(): serialization failed; rejecting: %O", err);
+ reject(err);
+ } finally {
+ clearInterval(debugInterval);
+ }
+ });
+ });
+ }
+
+ return { run };
+};
+
+/**
+ * Registers a new worker to the pool and runs it.
+ * Param should only be used for testing.
+ */
+export const startWorker = ({
+ // This param object has a prop named workerpool.
+ // We assign that prop to our existing workerpool value by default.
+ // To disambiguate, we alias the prop as workerpoolImpl.
+ workerpool: workerpoolImpl = workerpool,
+ ...workerOptions
+} = {}) => {
+ if (workerpoolImpl.isMainThread) {
+ throw new Error(
+ "This script is intended to be run as a worker (by the `workerpool` package).",
+ );
+ }
+
+ const worker = createWorker({ ...workerOptions });
+ workerpoolImpl.worker(worker);
+ debug("started worker process");
+ return worker;
+};
diff --git a/lib/nodejs/worker.cjs b/lib/nodejs/worker.cjs
deleted file mode 100644
index 3aec72bd..00000000
--- a/lib/nodejs/worker.cjs
+++ /dev/null
@@ -1,158 +0,0 @@
-/**
- * A worker process. Consumes {@link module:reporters/parallel-buffered} reporter.
- * @module worker
- * @private
- */
-
-"use strict";
-
-/**
- * @typedef {import('../types.d.ts').BufferedEvent} BufferedEvent
- * @typedef {import('../types.d.ts').MochaOptions} MochaOptions
- */
-
-const {
- createInvalidArgumentTypeError,
- createInvalidArgumentValueError,
-} = require("../errors.js");
-const workerpool = require("workerpool");
-const Mocha = require("../mocha.cjs");
-const {
- handleRequires,
- validateLegacyPlugin,
-} = require("../cli/run-helpers.cjs");
-const d = require("debug");
-const debug = d.debug(`mocha:parallel:worker:${process.pid}`);
-const isDebugEnabled = d.enabled(`mocha:parallel:worker:${process.pid}`);
-const { serialize } = require("./serializer.js");
-const { setInterval, clearInterval } = global;
-
-let rootHooks;
-
-if (workerpool.isMainThread) {
- throw new Error(
- "This script is intended to be run as a worker (by the `workerpool` package).",
- );
-}
-
-/**
- * Initializes some stuff on the first call to {@link run}.
- *
- * Handles `--require` and `--ui`. Does _not_ handle `--reporter`,
- * as only the `Buffered` reporter is used.
- *
- * **This function only runs once per worker**; it overwrites itself with a no-op
- * before returning.
- *
- * @param {MochaOptions} argv - Command-line options
- */
-let bootstrap = async (argv) => {
- // globalSetup and globalTeardown do not run in workers
- const plugins = await handleRequires(argv.require, {
- ignoredPlugins: ["mochaGlobalSetup", "mochaGlobalTeardown"],
- });
- validateLegacyPlugin(argv, "ui", Mocha.interfaces);
-
- rootHooks = plugins.rootHooks;
- bootstrap = () => {};
- debug("bootstrap(): finished with args: %O", argv);
-};
-
-/**
- * Runs a single test file in a worker thread.
- * @param {string} filepath - Filepath of test file
- * @param {string} [serializedOptions] - **Serialized** options. This string will be eval'd!
- * @see https://npm.im/serialize-javascript
- * @returns {Promise<{failures: number, events: BufferedEvent[]}>} - Test
- * failure count and list of events.
- */
-async function run(filepath, serializedOptions = "{}") {
- if (!filepath) {
- throw createInvalidArgumentTypeError(
- 'Expected a non-empty "filepath" argument',
- "file",
- "string",
- );
- }
-
- debug("run(): running test file %s", filepath);
-
- if (typeof serializedOptions !== "string") {
- throw createInvalidArgumentTypeError(
- "run() expects second parameter to be a string which was serialized by the `serialize-javascript` module",
- "serializedOptions",
- "string",
- );
- }
- let argv;
- try {
- argv = eval("(" + serializedOptions + ")");
- } catch {
- throw createInvalidArgumentValueError(
- "run() was unable to deserialize the options",
- "serializedOptions",
- serializedOptions,
- );
- }
-
- const opts = Object.assign({ ui: "bdd" }, argv, {
- // if this was true, it would cause infinite recursion.
- parallel: false,
- // this doesn't work in parallel mode
- forbidOnly: true,
- // it's useful for a Mocha instance to know if it's running in a worker process.
- isWorker: true,
- });
-
- await bootstrap(opts);
-
- opts.rootHooks = rootHooks;
-
- const mocha = new Mocha(opts).addFile(filepath);
-
- try {
- await mocha.loadFilesAsync();
- } catch (err) {
- debug("run(): could not load file %s: %s", filepath, err);
- throw err;
- }
-
- return new Promise((resolve, reject) => {
- let debugInterval;
- /* istanbul ignore next */
- if (isDebugEnabled) {
- debugInterval = setInterval(() => {
- debug("run(): still running %s...", filepath);
- }, 5000).unref();
- }
- mocha.run((result) => {
- // Runner adds these; if we don't remove them, we'll get a leak.
- process.removeAllListeners("uncaughtException");
- process.removeAllListeners("unhandledRejection");
-
- try {
- const serialized = serialize(result);
- debug(
- "run(): completed run with %d test failures; returning to main process",
- typeof result.failures === "number" ? result.failures : 0,
- );
- resolve(serialized);
- } catch (err) {
- // TODO: figure out exactly what the sad path looks like here.
- // rejection should only happen if an error is "unrecoverable"
- debug("run(): serialization failed; rejecting: %O", err);
- reject(err);
- } finally {
- clearInterval(debugInterval);
- }
- });
- });
-}
-
-// this registers the `run` function.
-workerpool.worker({ run });
-
-debug("started worker process");
-
-// for testing
-exports.run = run;
diff --git a/lib/nodejs/worker.js b/lib/nodejs/worker.js
new file mode 100644
index 00000000..66b07ca3
--- /dev/null
+++ b/lib/nodejs/worker.js
@@ -0,0 +1,11 @@
+/* istanbul ignore file */
+/**
+ * A worker process. Consumes {@link module:reporters/parallel-buffered} reporter.
+ * @module worker
+ * @private
+ */
+import { startWorker } from "./worker-core.js";
+
+const { run } = startWorker();
+
+export { run };
diff --git a/package.json b/package.json
index ae66b718..7ee4daf5 100644
--- a/package.json
+++ b/package.json
@@ -166,13 +166,14 @@
"fs": false,
"path": false,
"supports-color": false,
- "./lib/nodejs/buffered-worker-pool.cjs": false,
+ "./lib/nodejs/buffered-worker-pool.js": false,
"./lib/nodejs/esm-utils.cjs": false,
"./lib/nodejs/file-unloader.js": false,
- "./lib/nodejs/parallel-buffered-runner.cjs": false,
+ "./lib/nodejs/parallel-buffered-runner.js": false,
"./lib/nodejs/serializer.js": false,
- "./lib/nodejs/worker.cjs": false,
- "./lib/nodejs/reporters/parallel-buffered.cjs": false,
+ "./lib/nodejs/worker-core.js": false,
+ "./lib/nodejs/worker.js": false,
+ "./lib/nodejs/reporters/parallel-buffered.js": false,
"./lib/cli/index.cjs": false
},
"overrides": {
diff --git a/test/node-unit/buffered-worker-pool.spec.cjs b/test/node-unit/buffered-worker-pool.spec.cjs
index cb2d8f3e..42342fbd 100644
--- a/test/node-unit/buffered-worker-pool.spec.cjs
+++ b/test/node-unit/buffered-worker-pool.spec.cjs
@@ -1,14 +1,15 @@
"use strict";
-const rewiremock = require("rewiremock/node");
const sinon = require("sinon");
+const workerpool = require("workerpool");
+const {
+ BufferedWorkerPool,
+} = require("../../lib/nodejs/buffered-worker-pool.js");
+const { SerializableWorkerResult } = require("../../lib/nodejs/serializer.js");
describe("class BufferedWorkerPool", function () {
- let BufferedWorkerPool;
let pool;
let stats;
- let serializeJavascript;
- let serializer;
let result;
beforeEach(function () {
@@ -18,28 +19,19 @@ describe("class BufferedWorkerPool", function () {
idleWorkers: 2,
pendingTasks: 3,
};
- result = { failures: 0, events: [] };
+ result = {
+ __type: "SerializableWorkerResult",
+ events: [],
+ failureCount: 0,
+ };
pool = {
terminate: sinon.stub().resolves(),
exec: sinon.stub().resolves(result),
stats: sinon.stub().returns(stats),
};
- serializer = {
- deserialize: sinon.stub(),
- };
-
- serializeJavascript = sinon.spy(require("serialize-javascript"));
- BufferedWorkerPool = rewiremock.proxy(
- require.resolve("../../lib/nodejs/buffered-worker-pool.cjs"),
- {
- workerpool: {
- pool: sinon.stub().returns(pool),
- cpus: 8,
- },
- "../../lib/nodejs/serializer.js": serializer,
- "serialize-javascript": serializeJavascript,
- },
- ).BufferedWorkerPool;
+ sinon.stub(workerpool, "pool").returns(pool);
+ sinon.spy(BufferedWorkerPool, "serializeOptionsInternal");
+ sinon.spy(SerializableWorkerResult, "deserialize");
// reset cache
BufferedWorkerPool.resetOptionsCache();
@@ -86,7 +78,10 @@ describe("class BufferedWorkerPool", function () {
const obj = { foo: "bar" };
BufferedWorkerPool.serializeOptions(obj);
BufferedWorkerPool.serializeOptions(obj);
- expect(serializeJavascript, "was called once");
+ expect(
+ BufferedWorkerPool.serializeOptionsInternal,
+ "was called once",
+ );
});
it("should return the same value", function () {
@@ -154,9 +149,11 @@ describe("class BufferedWorkerPool", function () {
it("should deserialize the result", async function () {
await workerPool.run("file.js", { foo: "bar" });
- expect(serializer.deserialize, "to have a call satisfying", [
- result,
- ]).and("was called once");
+ expect(
+ SerializableWorkerResult.deserialize,
+ "to have a call satisfying",
+ [result],
+ ).and("was called once");
});
});
diff --git a/test/node-unit/mocha.spec.cjs b/test/node-unit/mocha.spec.cjs
index 2788fb93..38246a9b 100644
--- a/test/node-unit/mocha.spec.cjs
+++ b/test/node-unit/mocha.spec.cjs
@@ -68,8 +68,9 @@ describe("Mocha", function () {
(r) => ({
"../../lib/utils.cjs": r.with(stubs.utils).callThrough(),
"../../lib/suite.js": { Suite: stubs.Suite },
- "../../lib/nodejs/parallel-buffered-runner.cjs":
- stubs.ParallelBufferedRunner,
+ "../../lib/nodejs/parallel-buffered-runner.js": {
+ ParallelBufferedRunner: stubs.ParallelBufferedRunner,
+ },
"../../lib/nodejs/esm-utils.cjs": stubs.esmUtils,
"../../lib/runner.js": { Runner: stubs.Runner },
"../../lib/errors.js": stubs.errors,
diff --git a/test/node-unit/parallel-buffered-runner.spec.cjs b/test/node-unit/parallel-buffered-runner.spec.cjs
index 70696d8f..f149194c 100644
--- a/test/node-unit/parallel-buffered-runner.spec.cjs
+++ b/test/node-unit/parallel-buffered-runner.spec.cjs
@@ -7,56 +7,39 @@ const {
EVENT_SUITE_END,
EVENT_SUITE_BEGIN,
} = require("../../lib/runner.js").Runner.constants;
-const rewiremock = require("rewiremock/node");
const { Suite } = require("../../lib/suite.js");
const { Runner } = require("../../lib/runner.js");
const sinon = require("sinon");
const { constants } = require("../../lib/utils.cjs");
+const {
+ BufferedWorkerPool,
+} = require("../../lib/nodejs/buffered-worker-pool.js");
+const {
+ ParallelBufferedRunner,
+} = require("../../lib/nodejs/parallel-buffered-runner.js");
const { MOCHA_ID_PROP_NAME } = constants;
describe("parallel-buffered-runner", function () {
describe("ParallelBufferedRunner", function () {
let run;
- let BufferedWorkerPool;
let terminate;
- let ParallelBufferedRunner;
let suite;
- let warn;
- let fatalError;
beforeEach(function () {
suite = new Suite("a root suite", {}, true);
- warn = sinon.stub();
-
- fatalError = new Error();
// tests will want to further define the behavior of these.
run = sinon.stub();
terminate = sinon.stub();
- BufferedWorkerPool = {
- create: sinon.stub().returns({
- run,
- terminate,
- stats: sinon.stub().returns({}),
- }),
- };
- /**
- * @type {ParallelBufferedRunner}
- */
- ParallelBufferedRunner = rewiremock.proxy(
- () => require("../../lib/nodejs/parallel-buffered-runner.cjs"),
- (r) => ({
- "../../lib/nodejs/buffered-worker-pool.cjs": {
- BufferedWorkerPool,
- },
- "../../lib/utils.cjs": r.with({ warn }).callThrough(),
- "../../lib/errors.js": r
- .with({
- createFatalError: sinon.stub().returns(fatalError),
- })
- .callThrough(),
- }),
- );
+ sinon.stub(BufferedWorkerPool, "create").returns({
+ run,
+ terminate,
+ stats: sinon.stub().returns({}),
+ });
+ });
+
+ afterEach(function () {
+ sinon.restore();
});
describe("constructor", function () {
@@ -228,7 +211,7 @@ describe("parallel-buffered-runner", function () {
runner.run(
() => {
expect(runner.uncaught, "to have a call satisfying", [
- fatalError,
+ expect.it("to have property", "code", "ERR_MOCHA_FATAL"),
]);
done();
},
@@ -620,50 +603,6 @@ describe("parallel-buffered-runner", function () {
);
});
});
-
- describe("when subsequent files have not yet been run", function () {
- it("should cleanly terminate the thread pool", function (done) {
- const options = { reporter: runner._workerReporter };
- const err = {
- __type: "Error",
- message: "oh no",
- };
- run.withArgs("some-file.js", options).resolves({
- failureCount: 1,
- events: [
- {
- eventName: EVENT_TEST_FAIL,
- data: {
- title: "some test",
- },
- error: err,
- },
- {
- eventName: EVENT_SUITE_END,
- data: {
- title: "some suite",
- _bail: true,
- },
- },
- ],
- });
- run.withArgs("some-other-file.js", options).rejects();
-
- runner.run(
- () => {
- expect(terminate, "to have calls satisfying", [
- { args: [] }, // this is the pool force-terminating
- { args: [] }, // this will always be called, and will do nothing due to the previous call
- ]).and("was called twice");
- done();
- },
- {
- files: ["some-file.js", "some-other-file.js"],
- options,
- },
- );
- });
- });
});
});
});
diff --git a/test/node-unit/reporters/parallel-buffered.spec.cjs b/test/node-unit/reporters/parallel-buffered.spec.cjs
index 9c989fd1..d77b37ff 100644
--- a/test/node-unit/reporters/parallel-buffered.spec.cjs
+++ b/test/node-unit/reporters/parallel-buffered.spec.cjs
@@ -20,39 +20,21 @@ const {
} = require("../../../lib/runner.js").Runner.constants;
const { EventEmitter } = require("node:events");
const sinon = require("sinon");
-const rewiremock = require("rewiremock/node");
const semver = require("semver");
+const {
+ ParallelBuffered,
+} = require("../../../lib/nodejs/reporters/parallel-buffered.js");
+const {
+ SerializableEvent,
+ SerializableWorkerResult,
+} = require("../../../lib/nodejs/serializer.js");
describe("ParallelBuffered", function () {
/** @type {EventEmitter} */
let runner;
- let ParallelBuffered;
beforeEach(function () {
runner = new EventEmitter();
- ParallelBuffered = rewiremock.proxy(
- () => require("../../../lib/nodejs/reporters/parallel-buffered.cjs"),
- {
- "../../../lib/nodejs/serializer.js": {
- SerializableEvent: {
- create: (eventName, runnable, err) => ({
- eventName,
- data: runnable,
- error: err,
- __type: "MockSerializableEvent",
- }),
- },
- SerializableWorkerResult: {
- create: (events, failures) => ({
- events,
- failures,
- __type: "MockSerializableWorkerResult",
- }),
- },
- },
- "../../../lib/reporters/base.js": { Base: class MockBase {} },
- },
- );
});
afterEach(function () {
@@ -68,6 +50,9 @@ describe("ParallelBuffered", function () {
new ParallelBuffered(runner);
expect(runner.on, "to have calls satisfying", [
+ // via Base
+ [EVENT_TEST_PASS, expect.it("to be a function")],
+ [EVENT_TEST_FAIL, expect.it("to be a function")],
// via Buffered
[EVENT_SUITE_BEGIN, expect.it("to be a function")],
[EVENT_SUITE_END, expect.it("to be a function")],
@@ -127,39 +112,53 @@ describe("ParallelBuffered", function () {
};
const test = {
title: "some test",
+ duration: 0,
+ slow: () => 75,
};
runner.emit(EVENT_SUITE_BEGIN, suite);
runner.emit(EVENT_TEST_BEGIN, test);
runner.emit(EVENT_TEST_PASS, test);
runner.emit(EVENT_TEST_END, test);
runner.emit(EVENT_SUITE_END, suite);
- expect(reporter.events, "to equal", [
- {
- eventName: EVENT_SUITE_BEGIN,
- data: suite,
- __type: "MockSerializableEvent",
- },
- {
- eventName: EVENT_TEST_BEGIN,
- data: test,
- __type: "MockSerializableEvent",
- },
- {
- eventName: EVENT_TEST_PASS,
- data: test,
- __type: "MockSerializableEvent",
- },
- {
- eventName: EVENT_TEST_END,
- data: test,
- __type: "MockSerializableEvent",
- },
- {
- eventName: EVENT_SUITE_END,
- data: suite,
- __type: "MockSerializableEvent",
- },
- ]);
+ expect(reporter.events, "to have length", 5);
+ reporter.events.forEach((event) => {
+ expect(event, "to be a", SerializableEvent);
+ });
+ expect(
+ reporter.events[0],
+ "to have property",
+ "eventName",
+ EVENT_SUITE_BEGIN,
+ );
+ expect(reporter.events[0].originalValue, "to be", suite);
+ expect(
+ reporter.events[1],
+ "to have property",
+ "eventName",
+ EVENT_TEST_BEGIN,
+ );
+ expect(reporter.events[1].originalValue, "to be", test);
+ expect(
+ reporter.events[2],
+ "to have property",
+ "eventName",
+ EVENT_TEST_PASS,
+ );
+ expect(reporter.events[2].originalValue, "to be", test);
+ expect(
+ reporter.events[3],
+ "to have property",
+ "eventName",
+ EVENT_TEST_END,
+ );
+ expect(reporter.events[3].originalValue, "to be", test);
+ expect(
+ reporter.events[4],
+ "to have property",
+ "eventName",
+ EVENT_SUITE_END,
+ );
+ expect(reporter.events[4].originalValue, "to be", suite);
});
});
});
@@ -178,6 +177,8 @@ describe("ParallelBuffered", function () {
};
const test = {
title: "some test",
+ duration: 0,
+ slow: () => 75,
};
runner.emit(EVENT_SUITE_BEGIN, suite);
runner.emit(EVENT_TEST_BEGIN, test);
@@ -187,37 +188,10 @@ describe("ParallelBuffered", function () {
const cb = sinon.stub();
reporter.done(0, cb);
expect(cb, "to have a call satisfying", [
- {
- events: [
- {
- eventName: EVENT_SUITE_BEGIN,
- data: suite,
- __type: "MockSerializableEvent",
- },
- {
- eventName: EVENT_TEST_BEGIN,
- data: test,
- __type: "MockSerializableEvent",
- },
- {
- eventName: EVENT_TEST_PASS,
- data: test,
- __type: "MockSerializableEvent",
- },
- {
- eventName: EVENT_TEST_END,
- data: test,
- __type: "MockSerializableEvent",
- },
- {
- eventName: EVENT_SUITE_END,
- data: suite,
- __type: "MockSerializableEvent",
- },
- ],
- failures: 0,
- __type: "MockSerializableWorkerResult",
- },
+ expect.it("to be a", SerializableWorkerResult).and("to satisfy", {
+ events: expect.it("to have length", 5),
+ failureCount: 0,
+ }),
]);
});
@@ -227,6 +201,8 @@ describe("ParallelBuffered", function () {
};
const test = {
title: "some test",
+ duration: 0,
+ slow: () => 75,
};
runner.emit(EVENT_SUITE_BEGIN, suite);
runner.emit(EVENT_TEST_BEGIN, test);
diff --git a/test/node-unit/worker.spec.cjs b/test/node-unit/worker.spec.cjs
index c393e68e..ca86d453 100644
--- a/test/node-unit/worker.spec.cjs
+++ b/test/node-unit/worker.spec.cjs
@@ -1,11 +1,9 @@
"use strict";
const serializeJavascript = require("serialize-javascript");
-const rewiremock = require("rewiremock/node");
const { SerializableWorkerResult } = require("../../lib/nodejs/serializer.js");
const sinon = require("sinon");
-
-const WORKER_PATH = require.resolve("../../lib/nodejs/worker.cjs");
+const { startWorker } = require("../../lib/nodejs/worker-core.js");
describe("worker", function () {
let worker;
@@ -23,14 +21,7 @@ describe("worker", function () {
describe("when run as main process", function () {
it("should throw", function () {
- expect(() => {
- rewiremock.proxy(WORKER_PATH, {
- workerpool: {
- isMainThread: true,
- worker: stubs.workerpool.worker,
- },
- });
- }, "to throw");
+ expect(startWorker, "to throw");
});
});
@@ -58,16 +49,12 @@ describe("worker", function () {
validateLegacyPlugin: sinon.stub(),
};
- stubs.plugin = {
- aggregateRootHooks: sinon.stub().resolves(),
- };
-
- worker = rewiremock.proxy(WORKER_PATH, {
+ worker = startWorker({
workerpool: stubs.workerpool,
- "../../lib/mocha.cjs": stubs.Mocha,
- "../../lib/nodejs/serializer.js": stubs.serializer,
- "../../lib/cli/run-helpers.cjs": stubs.runHelpers,
- "../../lib/plugin-loader.js": stubs.plugin,
+ Mocha: stubs.Mocha,
+ handleRequires: stubs.runHelpers.handleRequires,
+ validateLegacyPlugin: stubs.runHelpers.validateLegacyPlugin,
+ serialize: stubs.serializer.serialize,
});
});