UNPKG

@wdio/mocha-framework

Version:
1,073 lines (1,066 loc) • 40.5 kB
// src/index.ts import path from "node:path"; import Mocha2 from "mocha"; import { handleRequires } from "mocha/lib/cli/run-helpers.cjs"; import logger3 from "@wdio/logger"; import { executeHooksWithArgs, specFilePath } from "@wdio/utils"; // src/common.ts import logger from "@wdio/logger"; import { wrapGlobalTestMethod } from "@wdio/utils"; // src/constants.ts var INTERFACES = { bdd: ["it", "specify", "before", "beforeEach", "after", "afterEach"], tdd: ["test", "suiteSetup", "setup", "suiteTeardown", "teardown"], qunit: ["test", "before", "beforeEach", "after", "afterEach"] }; var TEST_INTERFACES = { bdd: ["it", "specify"], tdd: ["test"], qunit: ["test"] }; var EVENTS = { "suite": "suite:start", "suite end": "suite:end", "test": "test:start", "test end": "test:end", "hook": "hook:start", "hook end": "hook:end", "pass": "test:pass", "fail": "test:fail", "retry": "test:retry", "pending": "test:pending" }; var NOOP = ( /* istanbul ignore next */ function() { } ); var MOCHA_TIMEOUT_MESSAGE = 'For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.'; // src/common.ts var log = logger("@wdio/mocha-framework"); var MOCHA_UI_TYPE_EXTRACTOR = /^(?:.*-)?([^-.]+)(?:.js)?$/; var DEFAULT_INTERFACE_TYPE = "bdd"; var HOOK_LISTS = [["_beforeAll", "beforeAll"], ["_beforeEach", "beforeEach"], ["_afterEach", "afterEach"], ["_afterAll", "afterAll"]]; var TITLE_KINDS = { "before all": "beforeAll", "before each": "beforeEach", "after each": "afterEach", "after all": "afterAll" }; function checkHookKind(hook, kind) { const titleKind = TITLE_KINDS[(hook.originalTitle ?? hook.title)?.match(/^"(before|after) (all|each)" hook/)?.slice(1).join(" ") ?? ""]; if (titleKind && titleKind !== kind) { log.debug(`hook "${hook.title}" is a ${kind} hook, but its title says ${titleKind}`); } return kind; } function mochaHookKind(hook) { const parent = hook.parent; const kind = HOOK_LISTS.find(([list]) => parent?.[list]?.includes(hook))?.[1]; return kind && checkHookKind(hook, kind); } function dottedFullTitle(title, parent) { let fullTitle = title; while (parent && parent.title) { fullTitle = parent.title + "." + fullTitle; parent = parent.parent; } return fullTitle; } function formatError(err, testName) { if (err.message && err.message.includes(MOCHA_TIMEOUT_MESSAGE)) { const replacement = `The execution in the test "${testName}" took too long. Try to reduce the run time or increase your timeout for test specs (https://webdriver.io/docs/timeouts).`; err.message = err.message.replace(MOCHA_TIMEOUT_MESSAGE, replacement); err.stack = err.stack?.replace(MOCHA_TIMEOUT_MESSAGE, replacement); } return { name: err.name, message: err.message, stack: err.stack, type: err.type || err.name, expected: err.expected, actual: err.actual }; } function formatMessage(params) { const message = { type: params.type }; const payload = params.payload; const mochaAllHooksIfPresent = payload?.title?.match(/^"(before|after)( all| each)?" hook/); if (params.err) { const isSkipError2 = /^(sync|async) skip; aborting execution$/.test(params.err.message || ""); const isHookSkip = isSkipError2 && mochaAllHooksIfPresent; if (isHookSkip) { message.type = "hook:end"; } else { const testName = (payload?.parent?.title ? `${payload.parent.title} ${payload.title}` : payload?.title) || "unknown test"; message.error = formatError(params.err, testName); if (mochaAllHooksIfPresent) { message.type = "hook:end"; } } } if (payload) { message.title = payload.title; message.parent = payload.parent ? payload.parent.title : void 0; message.fullTitle = dottedFullTitle(message.title, payload.parent); message.pending = payload.pending || false; message.file = payload.file; message.duration = payload.duration; message.body = payload.body; if (payload.ctx && payload.ctx.currentTest) { message.currentTest = payload.ctx.currentTest.title; } if (params.type.match(/Test/)) { message.passed = payload.state === "passed"; } if (payload.parent?.title && mochaAllHooksIfPresent) { const hookName = mochaAllHooksIfPresent[0]; message.title = `${hookName} for ${payload.parent.title}`; } if (payload.context) { message.context = payload.context; } const hookKind = message.type.startsWith("hook:") ? mochaHookKind(payload) : void 0; if (hookKind) { message.hookKind = hookKind; } } return message; } function applyMochaDefaults(mochaOpts) { if (mochaOpts.failHookAffectedTests === void 0) { mochaOpts.failHookAffectedTests = true; } return mochaOpts; } function setupEnv(cid, options, beforeTest, beforeHook, afterTest, afterHook) { const match = MOCHA_UI_TYPE_EXTRACTOR.exec(options.ui); const type = match && INTERFACES[match[1]] && match[1] || DEFAULT_INTERFACE_TYPE; const hookArgsFn = (context) => { return [{ ...context.test, parent: context.test?.parent?.title }, context]; }; INTERFACES[type].forEach((fnName) => { const isTest = TEST_INTERFACES[type].flatMap((testCommand) => [testCommand, testCommand + ".only"]).includes(fnName); wrapGlobalTestMethod( isTest, isTest ? beforeTest : beforeHook, // @ts-ignore hookArgsFn, isTest ? afterTest : afterHook, hookArgsFn, fnName, cid ); }); } // src/parallel.ts import os from "node:os"; import Mocha from "mocha"; import logger2 from "@wdio/logger"; import { allocateContext, cleanupAllocation, resolveMaxContexts } from "@wdio/utils"; var log2 = logger2("@wdio/mocha-framework:parallel"); var DEFAULT_TIMEOUT_MS = 2e3; var MAX_TIMEOUT_MS = Math.pow(2, 31) - 1; var TIMEOUT_STRING_RE = /^(\d+(?:\.\d+)?)\s*(milliseconds?|seconds?|minutes?|hours?|ms|s|m|h)?$/i; function parseTimeoutString(value) { const match = TIMEOUT_STRING_RE.exec(value.trim()); if (!match) { return void 0; } const n = parseFloat(match[1]); switch (match[2]?.toLowerCase()) { case "ms": case "millisecond": case "milliseconds": return n; case "s": case "second": case "seconds": return n * 1e3; case "m": case "minute": case "minutes": return n * 60 * 1e3; case "h": case "hour": case "hours": return n * 60 * 60 * 1e3; default: return n; } } function resolveTimeoutMs(timeout) { const ms = typeof timeout === "string" ? parseTimeoutString(timeout) : timeout; if (ms === void 0) { return DEFAULT_TIMEOUT_MS; } return ms > 0 && ms < MAX_TIMEOUT_MS ? ms : 0; } var suiteUid = (cid, index) => `suite-${cid}-${index}`; var parentUidField = (cid, index) => ({ parentUid: index === void 0 ? null : suiteUid(cid, index) }); function collectAll(suite, match) { const tests = []; const suiteStubs = /* @__PURE__ */ new Map(); const suiteIndexOf = /* @__PURE__ */ new Map(); const matchedSuites = /* @__PURE__ */ new Set(); let nextDepth = 0; const walk = (s, parentBeforeEach, parentAfterEach, parentBeforeAll, parentAfterAll, depth, ancestors, parentIndex) => { const suiteIndex = depth > 0 ? nextDepth++ : void 0; if (suiteIndex !== void 0) { suiteIndexOf.set(s, suiteIndex); } const ownBeforeEach = s._beforeEach || []; const ownAfterEach = s._afterEach || []; const ownBeforeAll = s._beforeAll || []; const ownAfterAll = s._afterAll || []; const mergedBeforeEach = [...parentBeforeEach, ...ownBeforeEach]; const mergedAfterEach = [...ownAfterEach, ...parentAfterEach]; const mergedBeforeAll = [...parentBeforeAll, ...ownBeforeAll]; const mergedAfterAll = [...ownAfterAll, ...parentAfterAll]; for (const test of s.tests) { const fn = test.fn; const collected = { title: test.title, fullTitle: test.fullTitle(), reportFullTitle: dottedFullTitle(test.title, test.parent), fn: fn || (() => { }), parentTitle: s.title, _beforeEach: mergedBeforeEach, _afterEach: mergedAfterEach, _beforeAll: mergedBeforeAll, _afterAll: mergedAfterAll, pending: !!test.pending || !fn, file: test.file || void 0, suiteIndex, timeout: test._timeout, retries: test._retries, suiteIndexOf }; if (!match || match(collected)) { tests.push(collected); for (const ancestor of ancestors) { matchedSuites.add(ancestor); } matchedSuites.add(s); } } if (depth > 0) { suiteStubs.set(s, { title: s.title, fullTitle: dottedFullTitle(s.title, s.parent), file: s.file, depth: suiteIndex, parentIndex, timeout: s._timeout }); } for (const child of s.suites) { walk(child, mergedBeforeEach, mergedAfterEach, mergedBeforeAll, mergedAfterAll, depth + 1, [...ancestors, s], suiteIndex); } }; walk(suite, [], [], [], [], 0, []); return { tests, suites: [...suiteStubs.entries()].filter(([s]) => matchedSuites.has(s)).map(([, stub]) => stub) }; } var testNameOf = (test) => test.parentTitle ? `${test.parentTitle} ${test.title}` : test.title; function mochaTimeoutError(ms, file) { const err = new Error(`Timeout of ${ms}ms exceeded. ${MOCHA_TIMEOUT_MESSAGE}${file ? ` (${file})` : ""}`); return Object.assign(err, { code: "ERR_MOCHA_TIMEOUT", timeout: ms, file }); } function hookSkipError(hookTitle, err) { const skipError = new Error(`Test skipped due to failure in hook "${hookTitle}": ${err.message}`); skipError.stack = err.stack; return skipError; } function baseMessage(type, test, cid, specs, uid, contextId) { return { type, cid, specs, uid, title: test.title, fullTitle: test.reportFullTitle, parent: test.parentTitle, file: test.file || specs[0], ...parentUidField(cid, test.suiteIndex), ...contextId ? { contextId } : {} }; } function emitTestStart(reporter, test, cid, specs, uid, contextId) { reporter.emit("test:start", baseMessage("test:start", test, cid, specs, uid, contextId)); } function emitTestPass(reporter, test, cid, specs, uid, duration, contextId) { reporter.emit("test:pass", { ...baseMessage("test:pass", test, cid, specs, uid, contextId), duration, passed: true }); reporter.emit("test:end", { ...baseMessage("test:end", test, cid, specs, uid, contextId), duration, passed: true }); } function emitTestFail(reporter, test, cid, specs, uid, duration, error, contextId) { const errorPayload = formatError(error, testNameOf(test)); reporter.emit("test:fail", { ...baseMessage("test:fail", test, cid, specs, uid, contextId), duration, error: errorPayload }); reporter.emit("test:end", { ...baseMessage("test:end", test, cid, specs, uid, contextId), duration, passed: false, error: errorPayload }); } function emitTestPending(reporter, test, cid, specs, uid, duration, contextId) { reporter.emit("test:pending", { ...baseMessage("test:pending", test, cid, specs, uid, contextId), duration, pending: true }); reporter.emit("test:end", { ...baseMessage("test:end", test, cid, specs, uid, contextId), duration, passed: false, pending: true }); } function hookCurrentTest(kind, hook, test) { const siblings = hook.parent?.tests; return kind === "before all" ? siblings?.[0]?.title : kind === "after all" ? siblings?.[siblings.length - 1]?.title : test.title; } function nativeHookTitle(kind, hook, currentTest) { const original = hook.originalTitle ?? hook.title ?? `"${kind}" hook`; return currentTest !== void 0 ? `${original} for "${currentTest}"` : `${original} in "${hook.parent?.title || (hook.parent?.root ? "{root}" : "")}"`; } function hookBaseMessage(type, kind, hook, test, cid, specs, uid, contextId) { const currentTest = hookCurrentTest(kind, hook, test); const native = nativeHookTitle(kind, hook, currentTest); const declaringSuite = hook.parent?.title; const declaringIndex = hook.parent && test.suiteIndexOf.get(hook.parent); const ownSuite = (kind === "before all" || kind === "after all") && declaringIndex !== void 0; return { type, cid, specs, uid, title: declaringSuite ? `"${kind}" hook for ${declaringSuite}` : native, fullTitle: dottedFullTitle(native, hook.parent), parent: ownSuite ? declaringSuite ?? "" : test.parentTitle, file: test.file || specs[0], ...parentUidField(cid, ownSuite ? declaringIndex : test.suiteIndex), contextId, ...currentTest !== void 0 && { currentTest }, hookKind: checkHookKind(hook, TITLE_KINDS[kind]), ...ownSuite && { hookSuiteUid: suiteUid(cid, declaringIndex) } }; } function emitHookStart(reporter, kind, hook, test, cid, specs, uid, contextId) { reporter.emit("hook:start", hookBaseMessage("hook:start", kind, hook, test, cid, specs, uid, contextId)); } function emitHookEnd(reporter, kind, hook, test, cid, specs, uid, contextId, duration, error, pending) { const native = nativeHookTitle(kind, hook, hookCurrentTest(kind, hook, test)); const errorPayload = error ? formatError(error, hook.parent?.title ? `${hook.parent.title} ${native}` : native) : void 0; reporter.emit("hook:end", { ...hookBaseMessage("hook:end", kind, hook, test, cid, specs, uid, contextId), duration, // `this.skip()` in a hook: no state and no error, as in a sequential run (#14649) ...pending ? { pending: true } : { state: error ? "fail" : "pass" }, ...errorPayload ? { error: errorPayload } : {} }); } function emitSuiteStart(reporter, suite, cid, specs, uid) { reporter.emit("suite:start", { type: "suite:start", cid, specs, uid, title: suite.title, fullTitle: suite.fullTitle, parent: "", file: suite.file || specs[0], ...parentUidField(cid, suite.parentIndex) }); } function emitSuiteEnd(reporter, suite, cid, specs, uid) { reporter.emit("suite:end", { type: "suite:end", cid, specs, uid, title: suite.title, fullTitle: suite.fullTitle, parent: "", file: suite.file || specs[0], ...parentUidField(cid, suite.parentIndex) }); } var SKIP_ERROR_RE = /^(sync|async) skip; aborting execution$/; function isSkipError(err) { return err instanceof Error && (SKIP_ERROR_RE.test(err.message) || /marked Pending/.test(err.message)); } function createHookContext(testTitle, parentTitle, timeoutMs, fullTitle, file) { const test = testTitle ? { title: testTitle, parent: { title: parentTitle || "" }, state: void 0 } : void 0; const resolvedFullTitle = fullTitle ?? `${parentTitle || ""} ${testTitle || ""}`.trim(); return { test, currentTest: test, // `_timeoutError`: the wdio shim fails a timed-out runnable with Mocha's own error _runnable: { _timeout: timeoutMs, title: testTitle, file, fullTitle: () => resolvedFullTitle, _timeoutError: (ms) => mochaTimeoutError(ms, file) }, skip: () => { throw new Error("sync skip; aborting execution"); }, timeout: () => { throw new Error("this.timeout() is not supported in parallel mode"); }, retries: () => { throw new Error("this.retries() is not supported in parallel mode"); } }; } var ignoreUnhandledRejection = () => { }; function keepWorkerOnUnhandledRejection() { if (!process.listeners("unhandledRejection").includes(ignoreUnhandledRejection)) { process.on("unhandledRejection", ignoreUnhandledRejection); } } function isError(value) { return value instanceof Error || typeof value?.message === "string"; } function toError(value) { if (isError(value)) { return value; } if (!value) { return new Error("Caught falsy/undefined exception which would otherwise be uncaught. No stack trace found; try a debugger"); } const { canonicalType } = Mocha.utils; return new Error(`the ${canonicalType(value)} ${Mocha.utils.stringify(value)} was thrown, throw an Error :)`); } function callHook(hook, ctx, timeoutMs, uncaught) { const fn = typeof hook.fn === "function" ? hook.fn : hook; const run = () => { if (fn.length >= 1) { return Promise.resolve(fn.call(ctx, (err) => { throw err || new Error("done() callback is not supported in parallel mode"); })); } return Promise.resolve(fn.call(ctx)); }; return new Promise((resolve, reject) => { const runnable = ctx._runnable; const rejectTimeout = () => { uncaught?.clear(fail); reject(mochaTimeoutError(timeoutMs, runnable?.file)); }; let graceTimer; const timer = timeoutMs && timeoutMs > 0 ? setTimeout(() => { graceTimer = setTimeout(rejectTimeout, timeoutMs); }, timeoutMs) : void 0; const fail = (err) => { if (graceTimer) { log2.error(`[Parallel] uncaught error after the timeout of ${timeoutMs}ms: ${err.stack ?? err.message}`); } settle(() => reject(err)); }; const settle = (onTime) => { clearTimeout(timer); if (!graceTimer) { uncaught?.clear(fail); return onTime(); } clearTimeout(graceTimer); rejectTimeout(); }; uncaught?.set(fail); Promise.resolve().then(run).then( (value) => settle(() => resolve(value)), (err) => settle(() => reject(err)) ); }); } async function runOneTest(test, allocation, cid, specs, uid, reporter, parallelStore, timeoutMs, failHookAffectedTests, uncaughtTargets) { const contextId = allocation.context; const uncaught = { set: (fail) => uncaughtTargets.set(contextId, fail), clear: (fail) => { if (uncaughtTargets.get(contextId) === fail) { uncaughtTargets.delete(contextId); } } }; const runInContext = async () => { if (test.pending) { emitTestPending(reporter, test, cid, specs, uid, 0, contextId); return { status: "pending", name: test.title, duration: 0, hookFailures: 0 }; } let hookCnt = 0; const ctx = createHookContext(test.title, test.parentTitle, timeoutMs, test.fullTitle, test.file); let caughtError; let failedHook; let started = false; let fnDuration = 0; let passed = false; let hookFailures = 0; const runHookChain = async (hooks, kind, fatal) => { for (const fn of hooks) { const hook = fn; const hookUid = `hook-${uid}-${hookCnt++}`; emitHookStart(reporter, kind, hook, test, cid, specs, hookUid, contextId); const hookStart = Date.now(); try { await callHook(fn, ctx, timeoutMs, uncaught); emitHookEnd(reporter, kind, hook, test, cid, specs, hookUid, contextId, Date.now() - hookStart); } catch (err) { let hookError = isError(err) ? err : new Error(String(err)); if (isSkipError(hookError) && kind === "after all") { hookError = Object.assign(new Error("`this.skip` forbidden"), { code: "ERR_MOCHA_UNSUPPORTED" }); } if (isSkipError(hookError)) { emitHookEnd(reporter, kind, hook, test, cid, specs, hookUid, contextId, Date.now() - hookStart, void 0, true); if (fatal) { caughtError = hookError; break; } continue; } emitHookEnd(reporter, kind, hook, test, cid, specs, hookUid, contextId, Date.now() - hookStart, hookError); if (fatal) { caughtError = hookError; failedHook = { kind, hook }; break; } hookFailures++; log2.warn(`[Parallel] ${kind} hook failed for "${test.title}": ${hookError.message}`); } } }; const report = () => { if (isSkipError(caughtError)) { emitTestPending(reporter, test, cid, specs, uid, started ? fnDuration : 0, contextId); return { status: "pending", name: test.title, duration: started ? fnDuration : 0 }; } if (passed) { emitTestPass(reporter, test, cid, specs, uid, fnDuration, contextId); return { status: "passed", name: test.title, duration: fnDuration }; } const error = failedHook ? hookSkipError(nativeHookTitle(failedHook.kind, failedHook.hook, hookCurrentTest(failedHook.kind, failedHook.hook, test)), caughtError) : caughtError; if (!failedHook || failHookAffectedTests) { if (!started) { emitTestStart(reporter, test, cid, specs, uid, contextId); } emitTestFail(reporter, test, cid, specs, uid, fnDuration, error, contextId); } return { status: "failed", name: test.title, duration: fnDuration, error: error.message }; }; let result; await runHookChain(test._beforeAll, "before all", true); if (!caughtError) { started = true; emitTestStart(reporter, test, cid, specs, uid, contextId); await runHookChain(test._beforeEach, "before each", true); if (!caughtError) { const fnStart = Date.now(); try { await callHook(test.fn, ctx, timeoutMs, uncaught); passed = true; } catch (err) { caughtError = isError(err) ? err : new Error(String(err)); } finally { fnDuration = Date.now() - fnStart; } } if (ctx.test && !isSkipError(caughtError)) { ctx.test.state = passed ? "passed" : "failed"; } result = report(); await runHookChain(test._afterEach, "after each", false); } else { result = report(); } await runHookChain(test._afterAll, "after all", false); return { ...result, hookFailures }; }; return parallelStore.run(contextId, () => runInContext().finally(() => { reporter.emit("context:end", { type: "context:end", cid, specs, uid, contextId }); })); } async function runParallelTests(mochaSuite, browser, reporter, cid, specs, maxParallelContexts, mochaOptions) { const bidi = browser; const mode = mochaOptions?.mode ?? "contexts"; if (!bidi.isBidi) { throw new Error( `Parallel mode (parallelMode: "${mode}") requires a WebDriver Bidi session. Ensure your capabilities enable Bidi.` ); } if (mode === "userContexts" && (!bidi.browserCreateUserContext || !bidi.browserRemoveUserContext)) { throw new Error( 'parallelMode: "userContexts" requires browser.createUserContext and browser.removeUserContext, which this driver does not support. Use parallelMode: "contexts" or a driver with BiDi user context support.' ); } const grep = mochaOptions?.grep; const invert = !!mochaOptions?.invert; const { tests, suites } = collectAll( mochaSuite, grep ? (test) => grep.test(test.fullTitle) !== invert : void 0 ); if (tests.length === 0) { log2.info("No tests found for parallel execution."); return 0; } if (tests.some((t) => t._beforeAll.length > 0 || t._afterAll.length > 0)) { log2.warn( `Suite-level hooks (before()/after()) run once per test in parallel mode (parallelMode: "${mode}") because each test runs in its own browsing context. Use beforeSuite/afterSuite hooks in wdio.conf.ts for setup that should run only once per spec file.` ); } const timeoutMs = resolveTimeoutMs(mochaOptions?.timeout); const hasCustomTimeout = (r) => r.timeout !== void 0 && r.timeout !== timeoutMs; if (tests.some(hasCustomTimeout) || suites.some(hasCustomTimeout)) { log2.warn( `Per-test and per-suite timeouts (it(...).timeout(n), this.timeout(n)) are not supported in parallel mode (parallelMode: "${mode}"); mochaOpts.timeout (${timeoutMs}ms) applies.` ); } const retried = tests.find((t) => !t.pending && (t.retries ?? 0) > 0); if (retried) { const count = retried.retries; throw new Error( `retries is not supported in parallel mode (parallelMode: "${mode}"): "${retried.fullTitle}" has ${count} ${count === 1 ? "retry" : "retries"}` ); } const parallelStore = browser.__parallelContextStore; if (!parallelStore) { throw new Error("Parallel context store not found on browser."); } const parallelContexts = browser.__parallelContexts; if (!parallelContexts) { throw new Error( "Parallel context registry not found on browser. The session ContextManager must expose __parallelContexts for re-anchor protection." ); } for (const s of suites) { emitSuiteStart(reporter, s, cid, specs, suiteUid(cid, s.depth)); } const maxContexts = resolveMaxContexts(maxParallelContexts, os.cpus().length); const slotCount = Math.min(maxContexts, tests.length); const runStart = Date.now(); const allResults = new Array(tests.length); const cleanups = []; let cursor = 0; const spares = []; let allocationError; let allocationFailed = false; const uncaughtTargets = /* @__PURE__ */ new Map(); let uncaughtOutside = 0; const onUncaught = (err) => { const error = toError(err); const contextId = parallelStore.getStore(); const fail = contextId ? uncaughtTargets.get(contextId) : void 0; if (fail) { return fail(error); } if (isSkipError(error)) { return; } uncaughtOutside++; log2.error(`[Parallel] uncaught error outside a running test or hook: ${error.stack ?? error.message}`); }; log2.info( `[Parallel] Collected ${tests.length} tests. Slots: ${slotCount}, max contexts: ${maxContexts}` ); const runSlot = async () => { let closing; const scheduleClose = async (alloc) => { await closing?.catch(() => { }); closing = cleanupAllocation(bidi, alloc); cleanups.push(closing); }; while (!allocationFailed) { const index = cursor++; if (index >= tests.length) { break; } let allocation; try { allocation = await (spares.shift() ?? allocateContext(bidi, mode)); } catch (err) { if (!allocationFailed) { allocationFailed = true; allocationError = err; } break; } if (!allocationFailed && tests.length - cursor > spares.length) { const next = allocateContext(bidi, mode); next.catch(() => { }); spares.push(next); } try { allResults[index] = { status: "fulfilled", value: await runOneTest( tests[index], allocation, cid, specs, `test-${cid}-${index}`, reporter, parallelStore, timeoutMs, mochaOptions?.failHookAffectedTests !== false, uncaughtTargets ) }; } catch (reason) { allResults[index] = { status: "rejected", reason }; } finally { await scheduleClose(allocation); } } }; if (!mochaOptions?.allowUncaught) { process.on("uncaughtException", onUncaught); } keepWorkerOnUnhandledRejection(); try { await Promise.all(Array.from({ length: slotCount }, runSlot)); } finally { for (const spare of spares.splice(0)) { const unused = await spare.catch(() => void 0); if (unused) { cleanups.push(cleanupAllocation(bidi, unused)); } } const settled = await Promise.allSettled(cleanups); for (const r of settled) { if (r.status === "rejected") { log2.warn(`[Parallel] cleanup failed: ${r.reason.message}`); } } process.removeListener("uncaughtException", onUncaught); } const totalDuration = Date.now() - runStart; const passed = allResults.filter((r) => r.status === "fulfilled" && r.value.status === "passed").length; const pending = allResults.filter((r) => r.status === "fulfilled" && r.value.status === "pending").length; const hookFailures = allResults.reduce((n, r) => n + (r.status === "fulfilled" ? r.value.hookFailures : 0), 0); const failed = tests.length - passed - pending + hookFailures + uncaughtOutside; for (const s of [...suites].reverse()) { emitSuiteEnd(reporter, s, cid, specs, suiteUid(cid, s.depth)); } if (allocationFailed) { throw allocationError; } log2.info( `[Parallel] ${tests.length} tests: ${passed} passed, ${failed} failed, ${pending} pending in ${totalDuration}ms` ); return failed; } // src/types.ts import { default as default2 } from "mocha"; // src/index.ts var log3 = logger3("@wdio/mocha-framework"); function hasHooks(hooks) { return [hooks].flat().some((hook) => typeof hook === "function"); } function rootHookMessage(kind, tests = []) { const test = kind === "before all" ? tests[0] : tests[tests.length - 1]; const hook = `"${kind}" hook: ${kind === "before all" ? "beforeSuite" : "afterSuite"}`; const title = test ? `${hook} for "${test.title}"` : `${hook} in "{root}"`; return { title, fullTitle: title, parent: "", hookKind: kind === "before all" ? "beforeAll" : "afterAll" }; } var MochaAdapter = class { constructor(_cid, _config, _specs, _capabilities, _reporter) { this._cid = _cid; this._config = _config; this._specs = _specs; this._capabilities = _capabilities; this._reporter = _reporter; this._config = Object.assign({ mochaOpts: {} }, _config); } _cid; _config; _specs; _capabilities; _reporter; _mocha; _runner; _specLoadError; _level = 0; _hasTests = true; _browser; _suiteIds = ["0"]; _suiteCnt = /* @__PURE__ */ new Map(); _hookCnt = /* @__PURE__ */ new Map(); _testCnt = /* @__PURE__ */ new Map(); /** Mocha test and its uid between its test:start and its test:end */ _openTest; /** Mocha suite → the uid of its suite:start */ _suiteUids = /* @__PURE__ */ new WeakMap(); _suiteStartDate = Date.now(); async init() { const { mochaOpts } = this._config; if (Array.isArray(mochaOpts.require)) { const plugins = await handleRequires( mochaOpts.require.filter((p) => typeof p === "string").map((p) => path.resolve(this._config.rootDir, p)) ); Object.assign(mochaOpts, plugins); } applyMochaDefaults(mochaOpts); const mocha = this._mocha = new Mocha2(mochaOpts); mocha.reporter(NOOP); mocha.fullTrace(); this._specs.forEach((spec) => mocha.addFile(specFilePath(spec))); const { beforeTest, beforeHook, afterTest, afterHook } = this._config; mocha.suite.on("pre-require", () => setupEnv(this._cid, this._config.mochaOpts, beforeTest, beforeHook, afterTest, afterHook)); mocha.suite.on("require", () => mocha.unloadFiles()); await this._loadFiles(mochaOpts); return this; } async _loadFiles(mochaOpts) { try { await this._mocha.loadFilesAsync({ esmDecorator: (file) => `${file}?invalidateCache=${Math.random()}` }); const mochaRunner = new Mocha2.Runner(this._mocha.suite, { delay: false }); if (mochaOpts.grep) { mochaRunner.grep(this._mocha.options.grep, mochaOpts.invert); } this._hasTests = mochaRunner.total > 0; } catch (err) { const error = `Unable to load spec files quite likely because they rely on \`browser\` object that is not fully initialized. \`browser\` object has only \`capabilities\` and some flags like \`isMobile\`. Helper files that use other \`browser\` commands have to be moved to \`before\` hook. Spec file(s): ${this._specs.join(",")} Error: ${err.stack}`; this._specLoadError = new Error(error); log3.warn(error); } } setBrowser(browser) { this._browser = browser; } hasTests() { return this._hasTests; } async run() { const mocha = this._mocha; this._suiteStartDate = Date.now(); const parallelMode = this._config.mochaOpts?.parallelMode; if (parallelMode === "contexts" || parallelMode === "userContexts") { return this._runParallelMode(mocha, parallelMode); } return this._runSequential(mocha); } async _runParallelMode(mocha, mode) { const browser = this._browser ?? globalThis.browser; if (!browser) { throw new Error( "Parallel mode requires a browser instance. Ensure WebDriver session is initialized before tests run." ); } if (!browser.isBidi) { log3.warn( `parallelMode: "${mode}" is set but the browser session does not support WebDriver Bidi. This may be because "wdio:enforceWebDriverClassic" is enabled or the browser does not support Bidi. Falling back to sequential execution.` ); return this._runSequential(mocha); } if (browser.__bidiCommandsEnabled !== true) { log3.warn( `parallelMode: "${mode}" requires 'wdio:experimentalBiDiCommands': true to be set in capabilities. Without it, element commands use classic protocol which cannot target Bidi-created browsing contexts. Falling back to sequential execution.` ); return this._runSequential(mocha); } if (this._config.mochaOpts.bail) { throw new Error(`bail is not supported in parallel mode (parallelMode: "${mode}")`); } if (this._config.mochaOpts.retries) { throw new Error(`retries is not supported in parallel mode (parallelMode: "${mode}")`); } const mochaSuite = mocha.suite; if (mochaSuite.hasOnly?.()) { mochaSuite.filterOnly?.(); } const rootTests = mocha.suite.tests; await this._runRootHook("beforeSuite", rootTests); let failures; let runtimeError; try { failures = await runParallelTests( mocha.suite, browser, this._reporter, this._cid, this._specs, this._config.mochaOpts.maxParallelContexts, { // the Mocha constructor already compiled grep/fgrep into // options.grep (fgrep wins when both are set) grep: mocha.options?.grep, invert: mocha.options?.invert, timeout: this._config.mochaOpts.timeout, mode, failHookAffectedTests: this._config.mochaOpts.failHookAffectedTests, allowUncaught: this._config.mochaOpts.allowUncaught } ); } catch (err) { runtimeError = err; failures = 1; } await this._runRootHook("afterSuite", rootTests); return this._finalize(failures, runtimeError); } /** * Parallel mode: the config hooks surface as paired hook:start/hook:end events like sequential mode's * root-suite hooks (wrapHook): prepareMessage payloads with Mocha's root hook title. They run against * the session-global context (no tab) */ async _runRootHook(hookName, rootTests) { if (!hasHooks(this._config[hookName])) { return; } const message = this.prepareMessage(hookName); const hook = { ...message, ...rootHookMessage(hookName === "beforeSuite" ? "before all" : "after all", rootTests) }; const fields = { cid: this._cid, specs: this._specs, uid: this.getSyncEventIdStart("hook") }; const start = Date.now(); this._reporter.emit("hook:start", { ...hook, type: "hook:start", ...fields }); try { await executeHooksWithArgs(hookName, this._config[hookName], [message]); this._reporter.emit("hook:end", { ...hook, type: "hook:end", state: "pass", duration: Date.now() - start, ...fields }); } catch (err) { log3.error(`Error in ${hookName} hook: ${err.stack?.slice(7) || err.message}`); this._reporter.emit("hook:end", { ...hook, type: "hook:end", state: "fail", duration: Date.now() - start, error: { name: err.name || "Error", message: err.message, stack: err.stack }, ...fields }); } } async _runSequential(mocha) { let runtimeError; const result = await new Promise((resolve) => { try { this._runner = mocha.run(resolve); } catch (err) { runtimeError = err; return resolve(1); } Object.keys(EVENTS).forEach((e) => this._runner.on(e, this.emit.bind(this, EVENTS[e]))); if (hasHooks(this._config.beforeSuite)) { this._runner.suite.beforeAll("beforeSuite", this.wrapHook("beforeSuite")); } if (hasHooks(this._config.afterSuite)) { this._runner.suite.afterAll("afterSuite", this.wrapHook("afterSuite")); } }); return this._finalize(result, runtimeError); } /** * Shared teardown: emit 'after' hook, then conditionally throw stored errors. */ async _finalize(result, error) { await executeHooksWithArgs("after", this._config.after, [ error || this._specLoadError || result, this._capabilities, this._specs ]); if (error || this._specLoadError) { throw error || this._specLoadError; } return result; } /** * Hooks which are added as true Mocha hooks need to call done() to notify async */ wrapHook(hookName) { return () => executeHooksWithArgs( hookName, this._config[hookName], [this.prepareMessage(hookName)] ).catch((e) => { log3.error(`Error in ${hookName} hook: ${e.stack.slice(7)}`); }); } prepareMessage(hookName) { const params = { type: hookName }; switch (hookName) { case "beforeSuite": this._suiteStartDate = Date.now(); params.payload = this._runner?.suite.suites[0] || this._mocha?.suite?.suites?.[0]; break; case "afterSuite": params.payload = this._runner?.suite.suites[0] || this._mocha?.suite?.suites?.[0]; if (params.payload) { params.payload.duration = params.payload.duration || Date.now() - this._suiteStartDate; } break; case "beforeTest": case "afterTest": params.payload = this._runner?.test; break; } return formatMessage(params); } emit(event, payload, err) { if (payload.root) { return; } const isOpenTest = payload === this._openTest?.payload; if (event === "test:start" && isOpenTest) { return; } const message = formatMessage({ type: event, payload, err }); message.cid = this._cid; message.specs = this._specs; message.uid = event === "test:pending" && isOpenTest ? this._openTest.uid : this.getUID(message); if (event === "test:start") { this._openTest = { payload, uid: message.uid }; } else if (event === "test:end") { this._openTest = void 0; } if (event === "suite:start") { this._suiteUids.set(payload, message.uid); } const hookSuiteUid = (message.hookKind === "beforeAll" || message.hookKind === "afterAll") && this._suiteUids.get(payload.parent); if (hookSuiteUid) { message.hookSuiteUid = hookSuiteUid; } this._reporter.emit(message.type, message); } getSyncEventIdStart(type) { const prop = `_${type}Cnt`; const suiteId = this._suiteIds[this._suiteIds.length - 1]; const cnt = this[prop].has(suiteId) ? this[prop].get(suiteId) || 0 : 0; this[prop].set(suiteId, cnt + 1); return `${type}-${suiteId}-${cnt}`; } getSyncEventIdEnd(type) { const prop = `_${type}Cnt`; const suiteId = this._suiteIds[this._suiteIds.length - 1]; const cnt = this[prop].get(suiteId) - 1; return `${type}-${suiteId}-${cnt}`; } getUID(message) { if (message.type === "suite:start") { const suiteCnt = this._suiteCnt.has(this._level.toString()) ? this._suiteCnt.get(this._level.toString()) : 0; const suiteId = `suite-${this._level}-${suiteCnt}`; if (this._suiteCnt.has(this._level.toString())) { this._suiteCnt.set(this._level.toString(), this._suiteCnt.get(this._level.toString()) + 1); } else { this._suiteCnt.set(this._level.toString(), 1); } this._suiteIds.push(`${this._level}${suiteCnt}`); this._level++; return suiteId; } if (message.type === "suite:end") { this._level--; const suiteCnt = this._suiteCnt.get(this._level.toString()) - 1; const suiteId = `suite-${this._level}-${suiteCnt}`; this._suiteIds.pop(); return suiteId; } if (message.type === "hook:start") { return this.getSyncEventIdStart("hook"); } if (message.type === "hook:end") { return this.getSyncEventIdEnd("hook"); } if (message.type === "test:start" || message.type === "test:pending") { return this.getSyncEventIdStart("test"); } if (["test:end", "test:pass", "test:fail", "test:retry"].includes(message.type)) { return this.getSyncEventIdEnd("test"); } throw new Error(`Unknown message type : ${message.type}`); } }; var adapterFactory = {}; adapterFactory.init = async function(...args) { const adapter = new MochaAdapter(...args); const instance = await adapter.init(); return instance; }; var index_default = adapterFactory; export { MochaAdapter, adapterFactory, index_default as default };