forked from glenjamin/mocha-multi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mocha-multi.js
300 lines (259 loc) · 8.13 KB
/
mocha-multi.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
const fs = require('fs');
const once = require('lodash.once');
const util = require('util');
const assign = require('object-assign');
const debug = require('debug')('mocha:multi');
const path = require('path');
const isString = require('is-string');
const mkdirp = require('mkdirp');
// Let mocha decide about tty early
require('mocha/lib/reporters/base');
// Make sure we don't lose these!
const { stdout } = process;
function defineGetter(obj, prop, get, set) {
Object.defineProperty(obj, prop, { get, set });
}
const waitOn = fn => v => new Promise(resolve => fn(v, () => resolve()));
const waitStream = waitOn((r, fn) => r.end(fn));
function awaitOnExit(waitFor) {
if (!waitFor) {
return;
}
const { exit } = process;
process.exit = function mochaMultiExitPatch(...args) {
const quit = exit.bind(this, ...args);
if (process._exiting) {
return quit();
}
waitFor().then(quit);
return undefined;
};
}
function identity(x) {
return x;
}
const msgs = {
no_definitions: 'reporter definitions should be set in ' +
'the `multi` shell variable\n' +
"eg. `multi='dot=- xunit=file.xml' mocha`",
invalid_definition: "'%s' is an invalid definition\n" +
'expected <reporter>=<destination>',
invalid_reporter: "Unable to find '%s' reporter",
invalid_setup: "Invalid setup for reporter '%s' (%s)",
invalid_outfile: "Invalid stdout filename for reporter '%s' (%s)",
bad_file: "Missing or malformed options file '%s' -- Error: %s",
};
function bombOut(id, ...args) {
const newArgs = [`ERROR: ${msgs[id]}`, ...args];
process.stderr.write(`${util.format(...newArgs)}\n`);
process.exit(1);
}
function parseReporter(definition) {
const pair = definition.split('=');
if (pair.length !== 2) {
bombOut('invalid_definition', definition);
}
return pair;
}
function convertSetup(reporters) {
let setup = [];
Object.keys(reporters).forEach((reporter) => {
if (reporter === 'mocha-multi') {
debug('loading reporters from file %j', reporters[reporter]);
try {
setup = setup.concat(convertSetup(JSON.parse(fs.readFileSync(reporters[reporter]))));
} catch (e) {
bombOut('bad_file', reporters[reporter], e.message);
}
} else {
const r = reporters[reporter];
debug('adding reporter %j %j', reporter, r);
if (isString(r)) {
setup.push([reporter, r, null]);
} else if (typeof r !== 'object') {
bombOut('invalid_setup', reporter, typeof r);
} else {
if (typeof r.stdout !== 'string') { bombOut('invalid_setup', reporter, typeof r); }
setup.push([reporter, r.stdout, r.options]);
}
}
});
return setup;
}
function parseSetup() {
const reporterDefinition = process.env.multi || '';
const reporterDefs = reporterDefinition.trim().split(/\s/).filter(identity);
if (!reporterDefs.length) { bombOut('no_definitions'); }
debug('Got reporter defs: %j', reporterDefs);
const reporters = {}; // const but not readonly
reporterDefs.forEach((def) => {
const [reporter, r] = parseReporter(def);
reporters[reporter] = r;
});
return convertSetup(reporters);
}
function resolveStream(destination) {
if (destination === '-') {
debug("Resolved stream '-' into stdout and stderr");
return null;
}
debug("Resolved stream '%s' into writeable file stream", destination);
// Create directory if not existing
const destinationDir = path.dirname(destination);
if (!fs.existsSync(destinationDir)) {
mkdirp.sync(destinationDir);
}
// Ensure we can write here
fs.writeFileSync(destination, '');
return fs.createWriteStream(destination);
}
function safeRequire(module) {
try {
return require(module);
} catch (err) {
if (!/Cannot find/.exec(err.message)) {
throw err;
}
return null;
}
}
function resolveReporter(name) {
// Cribbed from Mocha.prototype.reporter()
const reporter = (
safeRequire(`mocha/lib/reporters/${name}`) ||
safeRequire(name) ||
safeRequire(path.resolve(process.cwd(), name)) ||
bombOut('invalid_reporter', name)
);
debug("Resolved reporter '%s' into '%s'", name, util.inspect(reporter));
return reporter;
}
function withReplacedStdout(stream, func) {
if (!stream) {
return func();
}
// The hackiest of hacks
debug('Replacing stdout');
const stdoutGetter = Object.getOwnPropertyDescriptor(process, 'stdout').get;
// eslint-disable-next-line no-console
console._stdout = stream;
defineGetter(process, 'stdout', () => stream);
try {
return func();
} finally {
// eslint-disable-next-line no-console
console._stdout = stdout;
defineGetter(process, 'stdout', stdoutGetter);
debug('stdout restored');
}
}
function createRunnerShim(runner, stream) {
const shim = new (require('events').EventEmitter)();
function addDelegate(prop) {
defineGetter(shim, prop,
() => {
const property = runner[prop];
if (typeof property === 'function') {
return property.bind(runner);
}
return property;
},
() => runner[prop]);
}
addDelegate('grepTotal');
addDelegate('suite');
addDelegate('total');
addDelegate('stats');
const delegatedEvents = {};
shim.on('newListener', (event) => {
if (event in delegatedEvents) return;
delegatedEvents[event] = true;
debug("Shim: Delegating '%s'", event);
runner.on(event, (...eventArgs) => {
eventArgs.unshift(event);
withReplacedStdout(stream, () => {
shim.emit(...eventArgs);
});
});
});
return shim;
}
function initReportersAndStreams(runner, setup, multiOptions) {
return setup
.map(([reporter, outstream, options]) => {
debug("Initialising reporter '%s' to '%s' with options %j", reporter, outstream, options);
const stream = resolveStream(outstream);
const shim = createRunnerShim(runner, stream);
debug("Shimming runner into reporter '%s' %j", reporter, options);
return withReplacedStdout(stream, () => {
const Reporter = resolveReporter(reporter);
return {
stream,
reporter: new Reporter(shim, assign({}, multiOptions, {
reporterOptions: options || {},
})),
};
});
});
}
function promiseProgress(items, fn) {
let count = 0;
fn(count);
items.forEach(v => v.then(() => {
count += 1;
fn(count);
}));
return Promise.all(items);
}
/**
* Override done to allow done processing for any reporters that have a done method.
*/
function done(failures, fn, reportersWithDone, waitFor = identity) {
const count = reportersWithDone.length;
const waitReporter = waitOn((r, f) => r.done(failures, f));
const progress = v => debug('Awaiting on %j reporters to invoke done callback.', count - v);
promiseProgress(reportersWithDone.map(waitReporter), progress)
.then(() => {
debug('All reporters invoked done callback.');
})
.then(waitFor)
.then(() => fn && fn(failures));
}
function mochaMulti(runner, options) {
// keep track of reporters that have a done method.
const reporters = (options && options.reporterOptions);
const setup = (() => {
if (reporters && Object.keys(reporters).length > 0) {
debug('options %j', options);
return convertSetup(reporters);
}
return parseSetup();
})();
debug('setup %j', setup);
// If the reporter possess a done() method register it so we can
// wait for it to complete when done.
const reportersAndStreams = initReportersAndStreams(runner, setup, options);
const streams = reportersAndStreams
.map(v => v.stream)
.filter(identity);
const reportersWithDone = reportersAndStreams
.map(v => v.reporter)
.filter(v => v.done);
// we actually need to wait streams only if they are present
const waitFor = streams.length > 0 ?
once(() => Promise.all(streams.map(waitStream))) :
undefined;
awaitOnExit(waitFor);
if (reportersWithDone.length > 0) {
return {
done: (failures, fn) => done(failures, fn, reportersWithDone, waitFor),
};
}
return {};
}
class MochaMulti {
constructor(runner, options) {
Object.assign(this, mochaMulti(runner, options));
}
}
module.exports = MochaMulti;