-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
212 lines (194 loc) · 6.1 KB
/
index.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
const Promise = require('bluebird');
const child_process = require('child_process');
const {Cli: CucumberCli} = require('cucumber');
const ArgvParser = require('cucumber/lib/cli/argv_parser').default;
const cucumberVersion = require('cucumber/package.json').version;
const EventEmitter = require('events');
const fs = require('fs');
const _ = require('lodash');
const path = require('path');
const {getWorkerJson} = require('./util');
const IS_WINDOWS = process.platform === 'win32';
const ROUNDROBIN = 'roundrobin';
const UNIFORM = 'uniform';
const CUCUMBER_JS_PATH = process.env.CUCUMBER_JS_PATH ||
(IS_WINDOWS ? 'node_modules\\.bin\\cucumber-js.cmd' : 'node_modules/.bin/cucumber-js');
const NUM_WORKERS = parseInt(process.env.CUCUMBER_PARALLEL_WORKERS, 10) || 4;
const REPORT_DIR = process.env.CUCUMBER_PARALLEL_REPORT_DIR || 'reports';
const DISTRIBUTION = process.env.CUCUMBER_PARALLEL_DISTRIBUTION === UNIFORM ? UNIFORM : ROUNDROBIN;
const mkdir = Promise.promisify(fs.mkdir);
const unlink = Promise.promisify(fs.unlink);
async function main() {
const features = await enumerateFeatures();
const workerArgv = cleanupArgv(process.argv);
await ensureReportDirectory();
await deleteWorkerJson();
const promises = await (DISTRIBUTION === UNIFORM ? uniform : roundrobin)(features, workerArgv);
const [rejected] = _.partition(promises, (p) => p.isRejected());
if (rejected.length) {
console.error(`${rejected.length} workers had failures.`);
process.exit(2);
}
}
async function enumerateFeatures() {
console.log(`Cucumber version: ${cucumberVersion}`);
const cli = new CucumberCli({
argv: process.argv,
cwd: process.cwd(),
stdout: process.stdout
});
const configuration = await cli.getConfiguration();
if (/^2/.test(cucumberVersion)) {
const ScenarioFilter = require('cucumber/lib/scenario_filter').default;
const {getFeatures} = require('cucumber/lib/cli/helpers');
const {
featurePaths,
scenarioFilterOptions
} = configuration;
const scenarioFilter = new ScenarioFilter(scenarioFilterOptions);
const cwd = `${process.cwd()}/`;
return getFeatures({
featurePaths,
scenarioFilter
}).map(f => f.uri.replace(cwd, ''));
} else { // Cucumber 3
const PickleFilter = require('cucumber/lib/pickle_filter').default;
const {getTestCasesFromFilesystem} = require('cucumber/lib/cli/helpers');
const eventBroadcaster = new EventEmitter();
const {
featurePaths,
pickleFilterOptions
} = configuration;
const pickleFilter = new PickleFilter(pickleFilterOptions);
const testCases = await getTestCasesFromFilesystem({
cwd: cli.cwd,
eventBroadcaster,
featurePaths,
order: 'defined',
pickleFilter
});
const features = new Set(testCases.map(t => t.uri));
return [...features.values()];
}
}
async function uniform(features, argv) {
return Promise.map(
distributeFeatures(features),
(chunk, index) => spawnWorker(chunk, argv, path.join(REPORT_DIR, `worker-${index}.json`)).reflect()
);
}
async function roundrobin(features, argv) {
console.log(`Doling out ${features.length} features across ${NUM_WORKERS} workers as they are available.`);
const queue = [...features];
const promises = [];
let index = 0;
const runPipeline = () => {
// keep taking features until the queue is empty
if (queue.length) {
const feature = queue.shift();
console.log(`${queue.length} features remaining`);
const reflection = spawnWorker([feature], argv, path.join(REPORT_DIR, `worker-${index++}.json`)).reflect();
promises.push(reflection);
return reflection.then(runPipeline);
}
}
// wait for all worker pipelines to run their courses
await Promise.map(Array(NUM_WORKERS), runPipeline);
// resolve promise reflections
return Promise.all(promises);
}
/**
* Trim 'node ./index.js' and feature arguments.
*/
function cleanupArgv(argv) {
const argSet = new Set(ArgvParser.parse(argv).args);
return argv.slice(2).filter(arg => !argSet.has(arg));
}
async function ensureReportDirectory() {
const reportDir = path.resolve(REPORT_DIR);
try {
await mkdir(reportDir);
} catch (error) {
// already exists
}
}
async function deleteWorkerJson() {
const reportDir = path.resolve(REPORT_DIR);
const workerJson = await getWorkerJson(reportDir);
return Promise.map(workerJson, (file) => unlink(file));
}
/**
* Bucket features based on NUM_WORKERS
*/
function distributeFeatures(features) {
const size = Math.ceil(features.length / NUM_WORKERS);
const chunks = _.chunk(features, size).filter((c) => c.length);
console.log(`Splitting ${features.length} features into ${chunks.length} groups of ${size}.`);
return chunks;
}
function spawnWorker(features, argv, outfile) {
// If argv targets specific scenario lines within these features,
// go with those instead of running the features entirely.
const expandedFeatures = _.flatMap(features, feature => {
const argMatches = process.argv.filter(arg => arg.includes(feature));
if (argMatches.length > 0) {
return argMatches;
}
return feature;
});
return new Promise((resolve, reject) => {
const worker = child_process.spawn(CUCUMBER_JS_PATH, [
...argv,
'--format', `json:${outfile}`,
...expandedFeatures
]);
let stderrBuffer = '';
let stdoutBuffer = '';
worker.stderr.on('data', (data) => {
stderrBuffer += data;
});
worker.stdout.on('data', (data) => {
stdoutBuffer += data;
});
worker.on('error', (error) => {
reject(error);
});
worker.on('exit', (code, signal) => {
if (code) {
reject(new WorkerError(`worker exited with code ${code}`, code, stderrBuffer, stdoutBuffer));
} else {
resolve([stdoutBuffer, stderrBuffer]);
}
});
})
.tap(([stdout, stderr]) => {
console.log(stdout);
})
.catch((error) => {
if (error.stdout) {
console.log(error.stdout);
}
if (error.stderr) {
console.error(error.stderr);
}
console.error(error.stack);
throw error;
});
}
class WorkerError extends Error {
constructor(message, code, stderr, stdout) {
super(...arguments);
this.code = code;
this.stderr = stderr;
this.stdout = stdout;
}
}
module.exports = function () {
main().catch((error) => {
console.error(error.stack);
process.exit(1);
});
};
if (require.main === module) {
module.exports();
}