forked from codeceptjs/CodeceptJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkers.js
398 lines (352 loc) · 10.4 KB
/
workers.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
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/* eslint-disable max-classes-per-file */
const { EventEmitter } = require('events');
const path = require('path');
const mkdirp = require('mkdirp');
const { Worker } = require('worker_threads');
const { Suite, Test, reporters: { Base } } = require('mocha');
const Codecept = require('./codecept');
const MochaFactory = require('./mochaFactory');
const Container = require('./container');
const { getTestRoot } = require('./command/utils');
const { isFunction, fileExists } = require('./utils');
const mainConfig = require('./config');
const output = require('./output');
const event = require('./event');
const recorder = require('./recorder');
const runHook = require('./hooks');
const WorkerStorage = require('./workerStorage');
const pathToWorker = path.join(__dirname, 'command', 'workers', 'runTests.js');
const initializeCodecept = (configPath, options = {}) => {
const codecept = new Codecept(mainConfig.load(configPath || '.'), options);
codecept.init(getTestRoot(configPath));
codecept.loadTests();
return codecept;
};
const createOutputDir = (configPath) => {
const config = mainConfig.load(configPath || '.');
const testRoot = getTestRoot(configPath);
const outputDir = path.isAbsolute(config.output) ? config.output : path.join(testRoot, config.output);
if (!fileExists(outputDir)) {
output.print(`creating output directory: ${outputDir}`);
mkdirp.sync(outputDir);
}
};
const populateGroups = (numberOfWorkers) => {
const groups = [];
for (let i = 0; i < numberOfWorkers; i++) {
groups[i] = [];
}
return groups;
};
const createWorker = (workerObject) => {
const worker = new Worker(pathToWorker, {
workerData: {
options: simplifyObject(workerObject.options),
tests: workerObject.tests,
testRoot: workerObject.testRoot,
workerIndex: workerObject.workerIndex + 1,
},
});
worker.on('error', err => output.error(`Worker Error: ${err.stack}`));
WorkerStorage.addWorker(worker);
return worker;
};
const simplifyObject = (object) => {
return Object.keys(object)
.filter((k) => k.indexOf('_') !== 0)
.filter((k) => typeof object[k] !== 'function')
.filter((k) => typeof object[k] !== 'object')
.reduce((obj, key) => {
obj[key] = object[key];
return obj;
}, {});
};
const repackTest = (test) => {
test = Object.assign(new Test(test.title || '', () => { }), test);
test.parent = Object.assign(new Suite(test.parent.title), test.parent);
return test;
};
const createWorkerObjects = (testGroups, config, testRoot, options) => {
return testGroups.map((tests, index) => {
const workerObj = new WorkerObject(index);
workerObj.addConfig(config);
workerObj.addTests(tests);
workerObj.setTestRoot(testRoot);
workerObj.addOptions(options);
return workerObj;
});
};
const indexOfSmallestElement = (groups) => {
let i = 0;
for (let j = 1; j < groups.length; j++) {
if (groups[j - 1].length > groups[j].length) {
i = j;
}
}
return i;
};
const convertToMochaTests = (testGroup) => {
const group = [];
if (testGroup instanceof Array) {
const mocha = MochaFactory.create({}, {});
mocha.files = testGroup;
mocha.loadFiles();
mocha.suite.eachTest((test) => {
const { id } = test;
group.push(id);
});
mocha.unloadFiles();
}
return group;
};
class WorkerObject {
/**
* @param {Number} workerIndex - Unique ID for worker
*/
constructor(workerIndex) {
this.workerIndex = workerIndex;
this.options = {};
this.tests = [];
this.testRoot = getTestRoot();
}
addConfig(config) {
const oldConfig = JSON.parse(this.options.override || '{}');
const newConfig = {
...oldConfig,
...config,
};
this.options.override = JSON.stringify(newConfig);
}
addTestFiles(testGroup) {
this.addTests(convertToMochaTests(testGroup));
}
addTests(tests) {
this.tests = this.tests.concat(tests);
}
setTestRoot(path) {
this.testRoot = getTestRoot(path);
}
addOptions(opts) {
this.options = {
...this.options,
...opts,
};
}
}
class Workers extends EventEmitter {
/**
* @param {Number} numberOfWorkers
* @param {Object} config
*/
constructor(numberOfWorkers, config = { by: 'test' }) {
super();
this.setMaxListeners(50);
this.codecept = initializeCodecept(config.testConfig, config.options);
this.finishedTests = {};
this.errors = [];
this.numberOfWorkers = 0;
this.closedWorkers = 0;
this.workers = [];
this.stats = {
passes: 0,
failures: 0,
tests: 0,
pending: 0,
};
this.testGroups = [];
createOutputDir(config.testConfig);
if (numberOfWorkers) this._initWorkers(numberOfWorkers, config);
}
_initWorkers(numberOfWorkers, config) {
this.splitTestsByGroups(numberOfWorkers, config);
this.workers = createWorkerObjects(this.testGroups, this.codecept.config, config.testConfig, config.options);
this.numberOfWorkers = this.workers.length;
}
/**
* This splits tests by groups.
* Strategy for group split is taken from a constructor's config.by value:
*
* `config.by` can be:
*
* - `suite`
* - `test`
* - function(numberOfWorkers)
*
* This method can be overridden for a better split.
*/
splitTestsByGroups(numberOfWorkers, config) {
if (isFunction(config.by)) {
const createTests = config.by;
const testGroups = createTests(numberOfWorkers);
if (!(testGroups instanceof Array)) {
throw new Error('Test group should be an array');
}
for (const testGroup of testGroups) {
this.testGroups.push(convertToMochaTests(testGroup));
}
} else if (typeof numberOfWorkers === 'number' && numberOfWorkers > 0) {
this.testGroups = config.by === 'suite' ? this.createGroupsOfSuites(numberOfWorkers) : this.createGroupsOfTests(numberOfWorkers);
}
}
/**
* Creates a new worker
*
* @returns {WorkerObject}
*/
spawn() {
const worker = new WorkerObject(this.numberOfWorkers);
this.workers.push(worker);
this.numberOfWorkers += 1;
return worker;
}
/**
* @param {Number} numberOfWorkers
*/
createGroupsOfTests(numberOfWorkers) {
const files = this.codecept.testFiles;
const mocha = Container.mocha();
mocha.files = files;
mocha.loadFiles();
const groups = populateGroups(numberOfWorkers);
let groupCounter = 0;
mocha.suite.eachTest((test) => {
const i = groupCounter % groups.length;
if (test) {
const { id } = test;
groups[i].push(id);
groupCounter++;
}
});
return groups;
}
/**
* @param {Number} numberOfWorkers
*/
createGroupsOfSuites(numberOfWorkers) {
const groups = populateGroups(numberOfWorkers);
const mocha = Container.mocha();
mocha.suite.suites.forEach((suite) => {
const i = indexOfSmallestElement(groups);
suite.tests.forEach((test) => {
if (test) {
const { id } = test;
groups[i].push(id);
}
});
});
return groups;
}
/**
* @param {Object} config
*/
overrideConfig(config) {
for (const worker of this.workers) {
worker.addConfig(config);
}
}
async bootstrapAll() {
return runHook(this.codecept.config.bootstrapAll, 'bootstrapAll');
}
async teardownAll() {
return runHook(this.codecept.config.teardownAll, 'teardownAll');
}
run() {
this.stats.start = new Date();
recorder.startUnlessRunning();
event.dispatcher.emit(event.workers.before);
recorder.add('starting workers', () => {
for (const worker of this.workers) {
const workerThread = createWorker(worker);
this._listenWorkerEvents(workerThread);
}
});
return new Promise(resolve => this.on('end', resolve));
}
/**
* @returns {Array<WorkerObject>}
*/
getWorkers() {
return this.workers;
}
/**
* @returns {Boolean}
*/
isFailed() {
return (this.stats.failures || this.errors.length) > 0;
}
_listenWorkerEvents(worker) {
worker.on('message', (message) => {
output.process(message.workerIndex);
switch (message.event) {
case event.hook.failed:
this.errors.push(message.data.err);
break;
case event.test.failed:
this._updateFinishedTests(repackTest(message.data));
this.emit(event.test.failed, repackTest(message.data));
break;
case event.test.passed:
this._updateFinishedTests(repackTest(message.data));
this.emit(event.test.passed, repackTest(message.data));
break;
case event.test.skipped:
this._updateFinishedTests(repackTest(message.data));
this.emit(event.test.skipped, repackTest(message.data));
break;
case event.test.finished: this.emit(event.test.finished, repackTest(message.data)); break;
case event.all.after:
this._appendStats(message.data); break;
}
});
worker.on('error', (err) => {
this.errors.push(err);
});
worker.on('exit', () => {
this.closedWorkers += 1;
if (this.closedWorkers === this.numberOfWorkers) {
this._finishRun();
}
});
}
_finishRun() {
event.dispatcher.emit(event.workers.after);
if (this.isFailed()) {
process.exitCode = 1;
} else {
process.exitCode = 0;
}
this.emit(event.all.result, !this.isFailed(), this.finishedTests, this.stats);
this.emit('end'); // internal event
}
_appendStats(newStats) {
this.stats.passes += newStats.passes;
this.stats.failures += newStats.failures;
this.stats.tests += newStats.tests;
this.stats.pending += newStats.pending;
}
_updateFinishedTests(test) {
const { id } = test;
if (this.finishedTests[id]) {
const stats = { passes: 0, failures: -1, tests: 0 };
this._appendStats(stats);
}
this.finishedTests[id] = test;
}
printResults() {
this.stats.end = new Date();
this.stats.duration = this.stats.end - this.stats.start;
output.print();
if (this.stats.tests === 0 || (this.stats.passes && !this.errors.length)) {
output.result(this.stats.passes, this.stats.failures, this.stats.pending, `${this.stats.duration || 0 / 1000}s`);
}
if (this.stats.failures) {
output.print();
output.print('-- FAILURES:');
const failedList = Object.keys(this.finishedTests)
.filter(key => this.finishedTests[key].err)
.map(key => this.finishedTests[key]);
Base.list(failedList);
}
}
}
module.exports = Workers;