forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathworker.ts
More file actions
320 lines (283 loc) · 13.5 KB
/
worker.ts
File metadata and controls
320 lines (283 loc) · 13.5 KB
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
namespace Harness.Parallel.Worker {
export function start() {
function hookUncaughtExceptions() {
if (!exceptionsHooked) {
process.on("uncaughtException", handleUncaughtException);
process.on("unhandledRejection", handleUncaughtException);
exceptionsHooked = true;
}
}
function unhookUncaughtExceptions() {
if (exceptionsHooked) {
process.removeListener("uncaughtException", handleUncaughtException);
process.removeListener("unhandledRejection", handleUncaughtException);
exceptionsHooked = false;
}
}
let exceptionsHooked = false;
hookUncaughtExceptions();
// Capitalization is aligned with the global `Mocha` namespace for typespace/namespace references.
const Mocha = require("mocha") as typeof import("mocha");
/**
* Mixin helper.
* @param base The base class constructor.
* @param mixins The mixins to apply to the constructor.
*/
function mixin<T extends new (...args: any[]) => any>(base: T, ...mixins: ((klass: T) => T)[]) {
for (const mixin of mixins) {
base = mixin(base);
}
return base;
}
/**
* Mixes in overrides for `resetTimeout` and `clearTimeout` to support parallel test execution in a worker.
*/
function Timeout<T extends typeof Mocha.Runnable>(base: T) {
return class extends (base as typeof Mocha.Runnable) {
resetTimeout() {
this.clearTimeout();
if (this.timeout() > 0) {
sendMessage({ type: "timeout", payload: { duration: this.timeout() || 1e9 } });
this.timer = true;
}
}
clearTimeout() {
if (this.timer) {
sendMessage({ type: "timeout", payload: { duration: "reset" } });
this.timer = false;
}
}
} as T;
}
/**
* Mixes in an override for `clone` to support parallel test execution in a worker.
*/
function Clone<T extends typeof Mocha.Suite | typeof Mocha.Test>(base: T) {
return class extends (base as new (...args: any[]) => { clone(): any; }) {
clone() {
const cloned = super.clone();
Object.setPrototypeOf(cloned, this.constructor.prototype);
return cloned;
}
} as T;
}
/**
* A `Mocha.Suite` subclass to support parallel test execution in a worker.
*/
class Suite extends mixin(Mocha.Suite, Clone) {
_createHook(title: string, fn?: Mocha.Func | Mocha.AsyncFunc) {
const hook = super._createHook(title, fn);
Object.setPrototypeOf(hook, Hook.prototype);
return hook;
}
}
/**
* A `Mocha.Hook` subclass to support parallel test execution in a worker.
*/
class Hook extends mixin(Mocha.Hook, Timeout) {
}
/**
* A `Mocha.Test` subclass to support parallel test execution in a worker.
*/
class Test extends mixin(Mocha.Test, Timeout, Clone) {
}
/**
* Shims a 'bdd'-style test interface to support parallel test execution in a worker.
* @param rootSuite The root suite.
* @param context The test context (usually the NodeJS `global` object).
*/
function shimTestInterface(rootSuite: Mocha.Suite, context: Mocha.MochaGlobals) {
const suites = [rootSuite];
context.before = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => { suites[0].beforeAll(title as string, fn); };
context.after = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => { suites[0].afterAll(title as string, fn); };
context.beforeEach = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => { suites[0].beforeEach(title as string, fn); };
context.afterEach = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => { suites[0].afterEach(title as string, fn); };
context.describe = context.context = ((title: string, fn: (this: Mocha.Suite) => void) => addSuite(title, fn)) as Mocha.SuiteFunction;
context.describe.skip = context.xdescribe = context.xcontext = (title: string) => addSuite(title, /*fn*/ undefined);
context.describe.only = (title: string, fn?: (this: Mocha.Suite) => void) => addSuite(title, fn);
context.it = context.specify = ((title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => addTest(title, fn)) as Mocha.TestFunction;
context.it.skip = context.xit = context.xspecify = (title: string | Mocha.Func | Mocha.AsyncFunc) => addTest(typeof title === "function" ? title.name : title, /*fn*/ undefined);
context.it.only = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => addTest(title, fn);
function addSuite(title: string, fn: ((this: Mocha.Suite) => void) | undefined): Mocha.Suite {
const suite = new Suite(title, suites[0].ctx);
suites[0].addSuite(suite);
suite.pending = !fn;
suites.unshift(suite);
if (fn) {
fn.call(suite);
}
suites.shift();
return suite;
}
function addTest(title: string | Mocha.Func | Mocha.AsyncFunc, fn: Mocha.Func | Mocha.AsyncFunc | undefined): Mocha.Test {
if (typeof title === "function") {
fn = title;
title = fn.name;
}
const test = new Test(title, suites[0].pending ? undefined : fn);
suites[0].addTest(test);
return test;
}
}
/**
* Run the tests in the requested task.
*/
function runTests(task: Task, fn: (payload: TaskResult) => void) {
if (task.runner === "unittest") {
return executeUnitTests(task, fn);
}
else {
return runFileTests(task, fn);
}
}
function executeUnitTests(task: UnitTestTask, fn: (payload: TaskResult) => void) {
if (!unitTestSuiteMap && unitTestSuite.suites.length) {
unitTestSuiteMap = new ts.Map<string, Mocha.Suite>();
for (const suite of unitTestSuite.suites) {
unitTestSuiteMap.set(suite.title, suite);
}
}
if (!unitTestTestMap && unitTestSuite.tests.length) {
unitTestTestMap = new ts.Map<string, Mocha.Test>();
for (const test of unitTestSuite.tests) {
unitTestTestMap.set(test.title, test);
}
}
if (!unitTestSuiteMap && !unitTestTestMap) {
throw new Error(`Asked to run unit test ${task.file}, but no unit tests were discovered!`);
}
let suite = unitTestSuiteMap.get(task.file);
const test = unitTestTestMap.get(task.file);
if (!suite && !test) {
throw new Error(`Unit test with name "${task.file}" was asked to be run, but such a test does not exist!`);
}
const root = new Suite("", new Mocha.Context());
root.timeout(globalTimeout || 40_000);
if (suite) {
root.addSuite(suite);
Object.setPrototypeOf(suite.ctx, root.ctx);
}
else if (test) {
const newSuite = new Suite("", new Mocha.Context());
newSuite.addTest(test);
root.addSuite(newSuite);
Object.setPrototypeOf(newSuite.ctx, root.ctx);
Object.setPrototypeOf(test.ctx, root.ctx);
test.parent = newSuite;
suite = newSuite;
}
runSuite(task, suite!, payload => {
suite!.parent = unitTestSuite;
Object.setPrototypeOf(suite!.ctx, unitTestSuite.ctx);
fn(payload);
});
}
function runFileTests(task: RunnerTask, fn: (result: TaskResult) => void) {
let instance = runners.get(task.runner);
if (!instance) runners.set(task.runner, instance = createRunner(task.runner));
instance.tests = [task.file];
const suite = new Suite("", new Mocha.Context());
suite.timeout(globalTimeout || 40_000);
shimTestInterface(suite, global);
instance.initializeTests();
runSuite(task, suite, fn);
}
function runSuite(task: Task, suite: Mocha.Suite, fn: (result: TaskResult) => void) {
const errors: ErrorInfo[] = [];
const passes: TestInfo[] = [];
const start = +new Date();
const runner = new Mocha.Runner(suite, /*delay*/ false);
const uncaught = (err: any) => runner.uncaught(err);
runner
.on("start", () => {
unhookUncaughtExceptions(); // turn off global uncaught handling
process.on("unhandledRejection", uncaught); // turn on unhandled rejection handling (not currently handled in mocha)
})
.on("pass", (test: Mocha.Test) => {
passes.push({ name: test.titlePath() });
})
.on("fail", (test: Mocha.Test | Mocha.Hook, err: any) => {
errors.push({ name: test.titlePath(), error: err.message, stack: err.stack });
})
.on("end", () => {
process.removeListener("unhandledRejection", uncaught);
hookUncaughtExceptions();
})
.run(() => {
fn({ task, errors, passes, passing: passes.length, duration: +new Date() - start });
});
}
/**
* Validates a message received from the host is well-formed.
*/
function validateHostMessage(message: ParallelHostMessage) {
switch (message.type) {
case "test": return validateTest(message.payload);
case "batch": return validateBatch(message.payload);
case "close": return true;
default: return false;
}
}
/**
* Validates a test task is well formed.
*/
function validateTest(task: Task) {
return !!task && !!task.runner && !!task.file;
}
/**
* Validates a batch of test tasks are well formed.
*/
function validateBatch(tasks: Task[]) {
return !!tasks && Array.isArray(tasks) && tasks.length > 0 && tasks.every(validateTest);
}
function processHostMessage(message: ParallelHostMessage) {
if (!validateHostMessage(message)) {
console.log("Invalid message:", message);
return;
}
switch (message.type) {
case "test": return processTest(message.payload, /*last*/ true);
case "batch": return processBatch(message.payload);
case "close": return process.exit(0);
}
}
function processTest(task: Task, last: boolean, fn?: () => void) {
runTests(task, payload => {
sendMessage(last ? { type: "result", payload } : { type: "progress", payload });
if (fn) fn();
});
}
function processBatch(tasks: Task[], fn?: () => void) {
const next = () => {
const task = tasks.shift();
if (task) return processTest(task, tasks.length === 0, next);
if (fn) fn();
};
next();
}
function handleUncaughtException(err: any) {
const error = err instanceof Error ? err : new Error("" + err);
sendMessage({ type: "error", payload: { error: error.message, stack: error.stack! } });
}
function sendMessage(message: ParallelClientMessage) {
process.send!(message);
}
// A cache of test harness Runner instances.
const runners = new ts.Map<string, RunnerBase>();
// The root suite for all unit tests.
let unitTestSuite: Suite;
let unitTestSuiteMap: ts.ESMap<string, Mocha.Suite>;
// (Unit) Tests directly within the root suite
let unitTestTestMap: ts.ESMap<string, Mocha.Test>;
if (runUnitTests) {
unitTestSuite = new Suite("", new Mocha.Context());
unitTestSuite.timeout(globalTimeout || 40_000);
shimTestInterface(unitTestSuite, global);
}
else {
// ensure unit tests do not get run
shimNoopTestInterface(global);
}
process.on("message", processHostMessage);
}
}