-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
584 lines (509 loc) · 21.6 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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
var fs = require('fs'),
mkdirp = require('mkdirp'),
_ = require('lodash'),
path = require('path'),
async = require('async'),
hat = require('hat'),
LocalStorage = require('node-localstorage').LocalStorage;
require('string.prototype.startswith');
var UNDEFINED, exportObject = exports, reportDate;
function sanitizeFilename(name) {
name = name.replace(/\s+/gi, '-'); // Replace white space with dash
return name.replace(/[^a-zA-Z0-9\-]/gi, ''); // Strip any special charactere
}
function trim(str) { return str.replace(/^\s+/, "").replace(/\s+$/, ""); }
function elapsed(start, end) { return (end - start) / 1000; }
function isFailed(obj) { return obj.status === "failed"; }
function isSkipped(obj) { return obj.status === "pending"; }
function isDisabled(obj) { return obj.status === "disabled"; }
function isPassed(obj) { return obj.status === "passed"; }
function parseDecimalRoundAndFixed(num, dec) {
var d = Math.pow(10, dec);
return isNaN((Math.round(num * d) / d).toFixed(dec)) === true ? 0 : (Math.round(num * d) / d).toFixed(dec);
}
function extend(dupe, obj) { // performs a shallow copy of all props of `obj` onto `dupe`
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
dupe[prop] = obj[prop];
}
}
return dupe;
}
function escapeInvalidHtmlChars(str) {
return str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function getQualifiedFilename(path, filename, separator) {
if (path && path.substr(-1) !== separator && filename.substr(0) !== separator) {
path += separator;
}
return path + filename;
}
function log(str) {
var con = global.console || console;
if (con && con.log) {
con.log(str);
}
}
function rmdir(dir) {
try {
var list = fs.readdirSync(dir);
for (var i = 0; i < list.length; i++) {
var filename = path.join(dir, list[i]);
var stat = fs.statSync(filename);
if (stat.isDirectory()) {
// rmdir recursively
rmdir(filename);
} else {
// rm fiilename
fs.unlinkSync(filename);
}
}
fs.rmdirSync(dir);
} catch (e) { log("problem trying to remove a folder:" + dir); }
}
function getReportDate() {
if (_.isUndefined(reportDate)) {
reportDate = new Date();
}
return reportDate.getFullYear() + '' +
(reportDate.getMonth() + 1) +
reportDate.getDate() + ' ' +
reportDate.getHours() + '' +
reportDate.getMinutes() + '' +
reportDate.getSeconds() + ',' +
reportDate.getMilliseconds();
}
function Jasmine2HTMLReporter(options) {
var self = this;
self.started = false;
self.finished = false;
// sanitize arguments
options = options || {};
self.takeScreenshots = options.takeScreenshots === UNDEFINED ? true : options.takeScreenshots;
self.savePath = options.savePath || '';
self.takeScreenshotsOnlyOnFailures = options.takeScreenshotsOnlyOnFailures === UNDEFINED ? false : options.takeScreenshotsOnlyOnFailures;
self.screenshotsFolder = (options.screenshotsFolder || 'screenshots').replace(/^\//, '') + '/';
self.useDotNotation = options.useDotNotation === UNDEFINED ? true : options.useDotNotation;
self.fixedScreenshotName = options.fixedScreenshotName === UNDEFINED ? false : options.fixedScreenshotName;
self.consolidate = options.consolidate === UNDEFINED ? true : options.consolidate;
self.consolidateAll = self.consolidate !== false && (options.consolidateAll === UNDEFINED ? true : options.consolidateAll);
self.filePrefix = options.filePrefix || (self.consolidateAll ? 'htmlReport' : 'htmlReport-');
self.retainScreenshots = options.retainScreenshots === UNDEFINED ? false : options.retainScreenshots;
self.fileNameSeparator = options.fileNameSeparator === UNDEFINED ? '-' : options.fileNameSeparator;
self.fileNamePrefix = options.fileNamePrefix === UNDEFINED ? '' : options.fileNamePrefix;
self.fileNameSuffix = options.fileNameSuffix === UNDEFINED ? '' : options.fileNameSuffix;
self.fileNameDateSuffix = options.fileNameDateSuffix === UNDEFINED ? false : options.fileNameDateSuffix;
self.fileName = options.fileName === UNDEFINED ? (options.filePrefix || 'htmlReport') : options.fileName;
self.cleanDestination = options.cleanDestination === UNDEFINED ? false : options.cleanDestination;
self.showPassed = options.showPassed === UNDEFINED ? true : options.showPassed;
self.showFailuresOnly = options.showFailuresOnly === UNDEFINED ? false : options.showFailuresOnly;
var suites = [],
flakes = [],
flakedSuiteNames = {},
currentSuite = null,
totalSpecsExecuted = 0,
totalSpecsDefined,
// when use use fit, jasmine never calls suiteStarted / suiteDone, so make a fake one to use
fakeFocusedSuite = {
id: 'focused',
description: 'focused specs',
fullName: 'focused specs'
};
// use node-localstorage to persist suite names to determine flake
var storage = new LocalStorage(self.savePath + 'temp');
var storageUID = getReportFilename();
var __suites = {}, __specs = {};
function getSuite(suite) {
__suites[suite.id] = extend(__suites[suite.id] || {}, suite);
return __suites[suite.id];
}
function getSpec(spec) {
__specs[spec.id] = extend(__specs[spec.id] || {}, spec);
return __specs[spec.id];
}
function getReportFilename(specName) {
var name = '';
if (self.fileNamePrefix) {
name += self.fileNamePrefix + self.fileNameSeparator;
}
name += self.fileName;
if (!_.isUndefined(specName)) {
name += self.fileNameSeparator + specName;
}
if (self.fileNameSuffix) {
name += self.fileNameSeparator + self.fileNameSuffix;
}
if (self.fileNameDateSuffix) {
name += self.fileNameSeparator + getReportDate();
}
return name;
}
/**
* Remove passed specs but keep specs that failed on first run
* but passed on second.
* @param {object} suite - a suite object
*/
function filterOutPassedSpecs(suite) {
var suiteName = getFullyQualifiedSuiteName(suite);
suite._specs = suite._specs.filter((spec) => {
return !isPassed(spec) || (flakedSuiteNames[suiteName] || []).indexOf(spec.id) > -1;
});
return suite;
}
/**
* Persist failed suite names to node local storage
*/
function saveFlakedSuiteNames() {
if (_.isEmpty(Object.keys(flakedSuiteNames))) {
return;
}
var storedNames = loadFlakedSuiteNames();
namesToBeStored = Object.assign(storedNames, flakedSuiteNames);
storage.setItem(storageUID, JSON.stringify(namesToBeStored));
}
/**
* Retrieve flaked suite names from node local storage to determine if current
* run is a rerun.
*/
function loadFlakedSuiteNames() {
var storedSuiteNames = storage.getItem(storageUID) || {};
if (_.isString(storedSuiteNames)) {
try {
return JSON.parse(storedSuiteNames);
} catch (error) {
log('Error retrieving flaked suite names', error);
}
}
return {};
}
/**
* Check if a suite has failing specs.
* @param {object} suite - suite object
*/
function isFlakeySuite(suite) {
return suite._failures > 0;
}
/**
* Check if a suite is a rerun (failed initially and is being run a second time)
* @param {object} suite - suite object
* @return {boolean}
*/
function isFlakedSuiteRerun(suite) {
var suiteName = getFullyQualifiedSuiteName(suite);
if (flakedSuiteNames[suiteName] && flakedSuiteNames[suiteName].length > 0) {
return true;
}
return false;
}
/**
* Append a flakey suite to displayed suites.
* @param {suite} suite - suite object
*/
function appendFlakeySuite(suite) {
var suiteCopy = Object.assign({}, suite);
suiteCopy._suites = [];
// if it is suite's first run remove all passed specs and save failing spec ids.
if(!isFlakedSuiteRerun(suite)) {
let failedSpecIds = suiteCopy._specs
.filter((spec) => !isPassed(spec))
.map((spec) => spec.id);
flakedSuiteNames[getFullyQualifiedSuiteName(suite)] = failedSpecIds;
}
suiteCopy = filterOutPassedSpecs(suiteCopy);
flakes.push(suiteCopy);
}
self.jasmineStarted = function (summary) {
flakedSuiteNames = loadFlakedSuiteNames();
totalSpecsDefined = summary && summary.totalSpecsDefined || NaN;
exportObject.startTime = new Date();
self.started = true;
if(!self.retainScreenshots) {
// Delete previous screenshots
rmdir(self.savePath);
}
//Delete previous reports unless cleanDirectory is false
if (self.cleanDestination) {
rmdir(self.savePath);
}
};
self.suiteStarted = function (suite) {
suite = getSuite(suite);
suite._startTime = new Date();
suite._specs = [];
suite._suites = [];
suite._failures = 0;
suite._skipped = 0;
suite._disabled = 0;
suite._parent = currentSuite;
if (!currentSuite) {
suites.push(suite);
} else {
currentSuite._suites.push(suite);
}
currentSuite = suite;
};
self.specStarted = function (spec) {
if (!currentSuite) {
// focused spec (fit) -- suiteStarted was never called
self.suiteStarted(fakeFocusedSuite);
}
spec = getSpec(spec);
spec._startTime = new Date();
spec._suite = currentSuite;
currentSuite._specs.push(spec);
};
self.specDone = function (spec) {
spec = getSpec(spec);
spec._endTime = new Date();
if (isSkipped(spec)) { spec._suite._skipped++; }
if (isDisabled(spec)) { spec._suite._disabled++; }
if (isFailed(spec)) { spec._suite._failures++; }
totalSpecsExecuted++;
//Take screenshots taking care of the configuration
if ((self.takeScreenshots && !self.takeScreenshotsOnlyOnFailures) ||
(self.takeScreenshots && self.takeScreenshotsOnlyOnFailures && isFailed(spec))) {
if (!self.fixedScreenshotName)
spec.screenshot = hat() + '.png';
else
spec.screenshot = sanitizeFilename(spec.description) + '.png';
browser.takeScreenshot().then(function (png) {
var screenshotPath = path.join(
self.savePath,
self.screenshotsFolder,
spec.screenshot
);
mkdirp(path.dirname(screenshotPath), function (err) {
if (err) {
throw new Error('Could not create directory for ' + screenshotPath);
}
writeScreenshot(png, screenshotPath);
});
});
}
};
self.suiteDone = function (suite) {
suite = getSuite(suite);
if (suite._parent === UNDEFINED) {
// disabled suite (xdescribe) -- suiteStarted was never called
self.suiteStarted(suite);
}
suite._endTime = new Date();
currentSuite = suite._parent;
if (isFlakedSuiteRerun(suite) || isFlakeySuite(suite)) {
appendFlakeySuite(suite);
}
};
self.jasmineDone = function () {
if (currentSuite) {
// focused spec (fit) -- suiteDone was never called
self.suiteDone(fakeFocusedSuite);
}
// add suite names to storage for to be loaded in the next jasmine run.
saveFlakedSuiteNames();
var outputSuites = self.showFailuresOnly ? flakes : suites;
var output = '';
for (var i = 0; i < outputSuites.length; i++) {
output += self.getOrWriteNestedOutput(outputSuites[i]);
}
// if we have anything to write here, write out the consolidated file
if (output) {
wrapOutputAndWriteFile(getReportFilename(), output);
}
//log("Specs skipped but not reported (entire suite skipped or targeted to specific specs)", totalSpecsDefined - totalSpecsExecuted + totalSpecsDisabled);
self.finished = true;
// this is so phantomjs-testrunner.js can tell if we're done executing
exportObject.endTime = new Date();
};
self.afterLaunch = function(callback) {
// if showFailuresOnly is true and all tests pass, then write a success
// html report
if (self.fileName.substr(-5) !== '.html') { self.fileName += '.html'; }
var filePath = path.join(self.savePath, self.fileName);
if (!fs.existsSync(filePath) && self.showFailuresOnly) {
self.writeSuccessOuput(self.fileName);
}
callback();
}
self.getOrWriteNestedOutput = function (suite) {
var output = suiteAsHtml(suite);
for (var i = 0; i < suite._suites.length; i++) {
output += self.getOrWriteNestedOutput(suite._suites[i]);
}
if (self.consolidateAll || self.consolidate && suite._parent) {
return output;
} else {
// if we aren't supposed to consolidate output, just write it now
wrapOutputAndWriteFile(generateFilename(suite), output);
return '';
}
};
self.writeSuccessOuput = function (fileName) {
var successOutput = getSuccessOutput();
self.writeFile(fileName, successOutput);
}
function getSuccessOutput() {
var successCss = fs.readFileSync(path.join(__dirname, 'static/success.css'));
var successPrefix = '<!DOCTYPE html><html><head lang=en><meta charset=UTF-8><title>Test Report - ' + getReportDate() + '</title>';
successPrefix += ('<style>' + successCss + '</style></head><body>');
var successBody = fs.readFileSync(path.join(__dirname, 'static/success.html'));
var successSuffix = '</body></html>';
return (successPrefix + successBody + successSuffix);
}
/******** Helper functions with closure access for simplicity ********/
function generateFilename(suite) {
return getReportFilename(getFullyQualifiedSuiteName(suite, true));
}
function getFullyQualifiedSuiteName(suite, isFilename) {
var fullName;
if (self.useDotNotation || isFilename) {
fullName = suite.description;
for (var parent = suite._parent; parent; parent = parent._parent) {
fullName = parent.description + '.' + fullName;
}
} else {
fullName = suite.fullName;
}
// Either remove or escape invalid HTML characters
if (isFilename) {
var fileName = "",
rFileChars = /[\w\.]/,
chr;
while (fullName.length) {
chr = fullName[0];
fullName = fullName.substr(1);
if (rFileChars.test(chr)) {
fileName += chr;
}
}
return fileName;
} else {
return escapeInvalidHtmlChars(fullName);
}
}
var writeScreenshot = function (data, filename) {
var stream = fs.createWriteStream(filename);
stream.write(new Buffer(data, 'base64'));
stream.end();
};
function suiteAsHtml(suite) {
var html = '<article class="suite">';
html += '<header>';
html += '<h2>' + getFullyQualifiedSuiteName(suite) + ' - ' + elapsed(suite._startTime, suite._endTime) + 's</h2>';
html += '<ul class="stats">';
html += '<li>Tests: <strong>' + suite._specs.length + '</strong></li>';
html += '<li>Skipped: <strong>' + suite._skipped + '</strong></li>';
html += '<li>Failures: <strong>' + suite._failures + '</strong></li>';
html += '</ul> </header>';
for (var i = 0; i < suite._specs.length; i++) {
var spec = suite._specs[i];
html += '<div class="spec">';
html += specAsHtml(spec);
html += '<div class="resume">';
if (spec.screenshot !== UNDEFINED) {
html += '<a href="' + self.screenshotsFolder + spec.screenshot + '">';
html += '<img src="' + self.screenshotsFolder + spec.screenshot + '" width="100" height="100" />';
html += '</a>';
}
html += '<br />';
var num_tests = spec.failedExpectations.length + spec.passedExpectations.length;
var percentage = (spec.passedExpectations.length * 100) / num_tests;
html += '<span>Tests passed: ' + parseDecimalRoundAndFixed(percentage, 2) + '%</span><br /><progress max="100" value="' + Math.round(percentage) + '"></progress>';
html += '</div>';
html += '</div>';
}
html += '\n </article>';
return html;
}
function specAsHtml(spec) {
var html = '<div class="description">';
html += '<h3>' + escapeInvalidHtmlChars(spec.description) + ' - ' + elapsed(spec._startTime, spec._endTime) + 's</h3>';
if (spec.failedExpectations.length > 0 || spec.passedExpectations.length > 0) {
html += '<ul>';
_.each(spec.failedExpectations, function (expectation) {
// captures any string starting with spec and endoing with .js
const regex = /(specs\S*.js)/g;
const found = expectation.stack.match(regex);
let uniqueFound = [...new Set(found)];
html += '<li>';
html += expectation.message + '<span style="padding:0 1em;color:red;">✗</span>';
html += '</li>';
html += '<div class="specfile">';
html += '<h4>Specfile:</h4>';
html += '<p>'+ uniqueFound.join('</br>')+'</p>'
html += '</div>';
});
if (self.showPassed === true) {
_.each(spec.passedExpectations, function (expectation) {
html += '<li>';
html += expectation.message + '<span style="padding:0 1em;color:green;">✓</span>';
html += '</li>';
});
}
html += '</ul></div>';
}
else {
html += '<span style="padding:0 1em;color:orange;">***Skipped***</span>';
html += '</div>';
}
return html;
}
self.writeFile = function (filename, text) {
var errors = [];
var path = self.savePath;
function appendwrite(path, filename, text) {
var fs = require("fs");
var nodejs_path = require("path");
require("mkdirp").sync(path); // make sure the path exists
var filepath = nodejs_path.join(path, filename);
fs.appendFileSync(filepath, text);
return;
}
function phantomWrite(path, filename, text) {
// turn filename into a qualified path
filename = getQualifiedFilename(path, filename, window.fs_path_separator);
// write via a method injected by phantomjs-testrunner.js
__phantom_writeFile(filename, text);
}
function nodeWrite(path, filename, text) {
var fs = require("fs");
var nodejs_path = require("path");
require("mkdirp").sync(path); // make sure the path exists
var filepath = nodejs_path.join(path, filename);
var htmlfile = fs.openSync(filepath, "w");
fs.writeSync(htmlfile, text, 0);
fs.closeSync(htmlfile);
return;
}
// Attempt writing with each possible environment.
// Track errors in case no write succeeds
try {
// append instead of overwrite, so sharding works!
appendwrite(path, filename, text);
return;
} catch (e) { errors.push(' PhantomJs attempt: ' + e.message); }
try {
nodeWrite(path, filename, text);
return;
} catch (f) { errors.push(' NodeJS attempt: ' + f.message); }
// If made it here, no write succeeded. Let user know.
log("Warning: writing html report failed for '" + path + "', '" +
filename + "'. Reasons:\n" +
errors.join("\n")
);
};
// To remove complexity and be more DRY about the silly preamble and <testsuites> element
var prefix = '<!DOCTYPE html><html><head lang=en><meta charset=UTF-8><title>Test Report - ' + getReportDate() + '</title><style>body{font-family:"open_sans",sans-serif}.suite{width:100%;overflow:auto}.suite .stats{margin:0;width:90%;padding:0}.suite .stats li{display:inline;list-style-type:none;padding-right:20px}.suite h2{margin:0}.suite header{margin:0;padding:5px 0 5px 5px;background:#003d57;color:white}.spec{width:100%;overflow:auto;border-bottom:1px solid #e5e5e5}.spec:hover{background:#e8f3fb}.spec h3{margin:5px 0}.spec .description{margin:1% 2%;width:65%;float:left}.spec .resume{width:29%;margin:1%;float:left;text-align:center}</style></head>';
prefix += '<body><section>';
var suffix = '\n</section></body></html>';
function wrapOutputAndWriteFile(filename, text) {
if (filename.substr(-5) !== '.html') { filename += '.html'; }
self.writeFile(filename, (prefix + text + suffix));
}
return this;
}
module.exports = Jasmine2HTMLReporter;