-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
391 lines (341 loc) · 9.27 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
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
'use-strict';
var xml = require('xml');
var Base = require('mocha').reporters.Base;
var fs = require('fs');
var path = require('path');
var debug = require('debug')('mocha-xunit-reporter');
var mkdirp = require('mkdirp');
var md5 = require('md5');
var stripAnsi = require('strip-ansi');
var createStatsCollector = require("mocha/lib/stats-collector");
module.exports = MochaXUnitReporter;
// A subset of invalid characters as defined in http://www.w3.org/TR/xml/#charsets that can occur in e.g. stacktraces
var INVALID_CHARACTERS = ['\u001b'];
function configureDefaults(options) {
debug(options);
if (!options) {
options = {};
} else if (options.reporterOptions) {
options = options.reporterOptions;
} else {
/*
* Mocha parses mocharc files by flattening nested properties into
* top-level properties with period-delimited property names.
*
* Example .mocharc.json (abbreviated):
*
* {
* "reporter": "mocha-xunit-reporter",
* "reporterOptions": {
* "mochaFile": "my-test-results.xml",
* }
* }
*
* The resulting options object includes a property under the key
* `reporterOptions.mochaFile`, rather than including an object under key
* `reporterOptions`.
*
* To honor reporter options specified in these files, check for options
* prefixed with `reporterOptions.`.
*/
options = Object.keys(options).reduce(function(reporterOptions, key) {
if (key.startsWith('reporterOptions.')) {
reporterOptions[key.substring('reporterOptions.'.length)] = options[key];
}
return reporterOptions;
}, {});
}
options.mochaFile =
options.mochaFile || process.env.MOCHA_FILE || 'test-results.xml';
options.toConsole = !!options.toConsole;
options.assemblyName = options.assemblyName || 'Mocha Tests';
options.addTags = options.addTags || false;
return options;
}
function isValidSuite(suite) {
return !(
(!suite.root && suite.title === '') ||
(suite.tests.length === 0 && suite.suites.length === 0)
);
}
/**
* Parses title for tags in format @tagName=value
* @param {} testTitle
*/
function getTags(testTitle) {
var regexAllTags = /@[A-Za-z]+=[A-Za-z0-9\-]+/gi;
var regexTag = /@([A-Za-z]+)=([A-Za-z0-9\-]+)/i;
var result = {
tags: {},
cleanTitle: testTitle,
tagsFound: false
};
var foundTags = testTitle.match(regexAllTags);
if (foundTags && foundTags.length > 0) {
result.tagsFound = true;
foundTags.forEach(tag => {
var parts = tag.match(regexTag);
result.cleanTitle = result.cleanTitle.replace(tag, '');
if (parts.length > 0) {
result.tags[parts[1]] = parts[2];
}
});
}
result.cleanTitle = result.cleanTitle.trim();
return result;
}
/**
* XUnit reporter for mocha.js.
* @module mocha-xunit-reporter
* @param {EventEmitter} runner - the test runner
* @param {Object} options - mocha options
*/
function MochaXUnitReporter(runner, options) {
createStatsCollector(runner);
this._options = configureDefaults(options);
this._runner = runner;
// get functionality from the Base reporter
Base.call(this, runner);
var collections = [];
function lastCollection() {
return collections[collections.length - 1].collection;
}
// remove old results
this._runner.on(
'start',
function() {
if (fs.existsSync(this._options.mochaFile)) {
debug('removing report file', this._options.mochaFile);
fs.unlinkSync(this._options.mochaFile);
}
}.bind(this)
);
this._runner.on(
'suite',
function(suite) {
if (isValidSuite(suite)) {
collections.push(this.getCollectionData(suite));
}
}.bind(this)
);
this._runner.on(
'pass',
function(test) {
lastCollection().push(this.getTestData(test, 'Pass'));
}.bind(this)
);
this._runner.on(
'fail',
function(test, err) {
lastCollection().push(this.getTestData(test, 'Fail'));
}.bind(this)
);
if (this._options.includePending) {
this._runner.on(
'pending',
function(test) {
var test = this.getTestData(test, 'Skip');
lastCollection().push(test);
}.bind(this)
);
}
this._runner.on(
'end',
function() {
this.flush(collections);
}.bind(this)
);
}
/**
* Produces an xml node for a test suite
* @param {Object} suite - a test suite
* @return {Object} - an object representing the xml node
*/
MochaXUnitReporter.prototype.getCollectionData = function(suite) {
var collection = {
collection: [
{
_attr: {
name: suite.title || 'Root Suite',
total: suite.tests.length
}
}
]
};
return collection;
};
/**
* Produces an xml config for a given test case.
* @param {object} test - test case
* @param {object} err - if test failed, the failure object
* @returns {object}
*/
MochaXUnitReporter.prototype.getTestData = function(test, status) {
var name = stripAnsi(test.fullTitle());
var tagResult = null;
if (this._options.addTags) {
tagResult = getTags(name);
if (tagResult.tagsFound) {
name = stripAnsi(tagResult.cleanTitle);
}
}
var testCase = {
test: [
{
_attr: {
name: name,
time: typeof test.duration === 'undefined' ? 0 : test.duration / 1000,
result: status
}
}
]
};
if (tagResult && tagResult.tags) {
var trait = {
traits: []
};
testCase.test[1] = trait;
Object.keys(tagResult.tags).forEach(tagName => {
var tagValue = '';
if (tagResult.tags[tagName]) {
tagValue = tagResult.tags[tagName];
}
testCase.test[0]._attr[tagName] = tagValue;
testCase.test[1].traits.push({
trait: {
_attr: {
name: tagName,
value: tagValue
}
}
});
});
}
if (status === 'Fail') {
testCase.test.push({
failure: [
{
_attr: {
'exception-type': test.err.name
}
},
{
message: {
_cdata: test.err.message
}
},
{
'stack-trace': {
_cdata: test.err.stack
}
}
]
});
}
return testCase;
};
/**
* @param {string} input
* @returns {string} without invalid characters
*/
MochaXUnitReporter.prototype.removeInvalidCharacters = function(input) {
return INVALID_CHARACTERS.reduce(function(text, invalidCharacter) {
return text.replace(new RegExp(invalidCharacter, 'g'), '');
}, input);
};
/**
* Writes xml to disk and ouputs content if "toConsole" is set to true.
* @param {Array.<Object>} testsuites - a list of xml configs
*/
MochaXUnitReporter.prototype.flush = function(collections) {
var xml = this.getXml(collections);
this.writeXmlToDisk(xml, this._options.mochaFile);
if (this._options.toConsole === true) {
console.log(xml); // eslint-disable-line no-console
}
};
/**
* Produces an XML string from the given test data.
* @param {Array.<Object>} testsuites - a list of xml configs
* @returns {string}
*/
MochaXUnitReporter.prototype.getXml = function(collections) {
var totalSuitesTime = 0;
var totalTests = 0;
var totalPassed = 0;
var totalFailed = 0;
var totalSkipped = 0;
var stats = this._runner.stats;
collections.forEach(function(collection) {
var _collAttr = collection.collection[0]._attr;
var _cases = collection.collection.slice(1);
_collAttr.failed = 0;
_collAttr.passed = 0;
_collAttr.total = 0;
_collAttr.time = 0;
_collAttr.skipped = 0;
_cases.forEach(function(test) {
if (test.test[0]._attr.result == 'Skip') {
_collAttr.skipped++;
}
if (test.test[0]._attr.result == 'Fail') {
_collAttr.failed++;
}
if (test.test[0]._attr.result == 'Pass') {
_collAttr.passed++;
}
_collAttr.time += test.test[0]._attr.time;
});
_collAttr.total = _collAttr.skipped + _collAttr.failed + _collAttr.passed;
totalSuitesTime += _collAttr.time;
totalTests += _collAttr.total;
totalPassed += _collAttr.passed;
totalSkipped += _collAttr.skipped;
totalFailed += _collAttr.failed;
});
var assembly = {
assembly: [
{
_attr: {
name: this._options.assemblyName,
time: totalSuitesTime,
total: totalTests,
failed: totalFailed,
passed: totalPassed,
skipped: totalSkipped,
'run-date': stats.start.toISOString().split('T')[0],
'run-time': stats.start
.toISOString()
.split('T')[1]
.split('.')[0]
}
}
].concat(collections)
};
return xml(
{
assemblies: [assembly]
},
{ declaration: true, indent: ' ' }
);
};
/**
* Writes a XUnit test report XML document.
* @param {string} xml - xml string
* @param {string} filePath - path to output file
*/
MochaXUnitReporter.prototype.writeXmlToDisk = function(xml, filePath) {
if (filePath) {
if (filePath.indexOf('[hash]') !== -1) {
filePath = filePath.replace('[hash]', md5(xml));
}
debug('writing file to', filePath);
mkdirp.sync(path.dirname(filePath));
try {
fs.writeFileSync(filePath, xml, 'utf-8');
} catch (exc) {
debug('problem writing results: ' + exc);
}
debug('results written successfully');
}
};