Skip to content

armgit / mocha

Public Imported from GitHub
0

☕️ Classic, reliable, trusted test framework for Node.js and the browser

update mocha css and js in example as it is outdated

berni5c92ab1187e2
diff --git a/example/mocha.css b/example/mocha.css
index a8a30d7a..274b9776 100644
--- a/example/mocha.css
+++ b/example/mocha.css
@@ -1,10 +1,15 @@
+@charset "utf-8";
+
body {
+ margin:0;
+}
+
+#mocha {
font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
- padding: 60px 50px;
+ margin: 60px 50px;
}
-#mocha ul,
-#mocha li {
+#mocha ul, #mocha li {
margin: 0;
padding: 0;
}
@@ -13,8 +18,7 @@ body {
list-style: none;
}
-#mocha h1,
-#mocha h2 {
+#mocha h1, #mocha h2 {
margin: 0;
}
@@ -38,6 +42,10 @@ body {
font-size: .8em;
}
+#mocha .hidden {
+ display: none;
+}
+
#mocha h2 {
font-size: 12px;
font-weight: normal;
@@ -50,21 +58,12 @@ body {
#mocha .test {
margin-left: 15px;
-}
-
-#mocha .test:hover h2::after {
- position: relative;
- top: 0;
- right: -10px;
- content: '(view source)';
- font-size: 12px;
- font-family: arial;
- color: #888;
+ overflow: hidden;
}
#mocha .test.pending:hover h2::after {
content: '(pending)';
- font-family: arial;
+ font-family: arial, sans-serif;
}
#mocha .test.pass.medium .duration {
@@ -131,57 +130,131 @@ body {
#mocha .test pre.error {
color: #c00;
+ max-height: 300px;
+ overflow: auto;
}
#mocha .test pre {
- display: inline-block;
+ display: block;
+ float: left;
+ clear: left;
font: 12px/1.5 monaco, monospace;
margin: 5px;
padding: 15px;
border: 1px solid #eee;
border-bottom-color: #ddd;
-webkit-border-radius: 3px;
- -moz-border-radius: 3px;
- border-radius: 3px;
-webkit-box-shadow: 0 1px 3px #eee;
+ -moz-border-radius: 3px;
-moz-box-shadow: 0 1px 3px #eee;
- box-shadow: 0 1px 3px #eee;
+ border-radius: 3px;
}
-#error {
+#mocha .test h2 {
+ position: relative;
+}
+
+#mocha .test a.replay {
+ position: absolute;
+ top: 3px;
+ right: 0;
+ text-decoration: none;
+ vertical-align: middle;
+ display: block;
+ width: 15px;
+ height: 15px;
+ line-height: 15px;
+ text-align: center;
+ background: #eee;
+ font-size: 15px;
+ -moz-border-radius: 15px;
+ border-radius: 15px;
+ -webkit-transition: opacity 200ms;
+ -moz-transition: opacity 200ms;
+ transition: opacity 200ms;
+ opacity: 0.3;
+ color: #888;
+}
+
+#mocha .test:hover a.replay {
+ opacity: 1;
+}
+
+#mocha-report.pass .test.fail {
+ display: none;
+}
+
+#mocha-report.fail .test.pass {
+ display: none;
+}
+
+#mocha-report.pending .test.pass,
+#mocha-report.pending .test.fail {
+ display: none;
+}
+#mocha-report.pending .test.pass.pending {
+ display: block;
+}
+
+#mocha-error {
color: #c00;
font-size: 1.5em;
font-weight: 100;
letter-spacing: 1px;
}
-#stats {
+#mocha-stats {
position: fixed;
top: 15px;
right: 10px;
font-size: 12px;
margin: 0;
color: #888;
+ z-index: 1;
}
-#stats .progress {
+#mocha-stats .progress {
float: right;
padding-top: 0;
}
-#stats em {
+#mocha-stats em {
color: black;
}
-#stats li {
+#mocha-stats a {
+ text-decoration: none;
+ color: inherit;
+}
+
+#mocha-stats a:hover {
+ border-bottom: 1px solid #eee;
+}
+
+#mocha-stats li {
display: inline-block;
margin: 0 5px;
list-style: none;
padding-top: 11px;
}
-code .comment { color: #ddd }
-code .init { color: #2F6FAD }
-code .string { color: #5890AD }
-code .keyword { color: #8A6343 }
-code .number { color: #2F6FAD }
+#mocha-stats canvas {
+ width: 40px;
+ height: 40px;
+}
+
+#mocha code .comment { color: #ddd }
+#mocha code .init { color: #2F6FAD }
+#mocha code .string { color: #5890AD }
+#mocha code .keyword { color: #8A6343 }
+#mocha code .number { color: #2F6FAD }
+
+@media screen and (max-device-width: 480px) {
+ #mocha {
+ margin: 60px 0px;
+ }
+
+ #mocha #stats {
+ position: absolute;
+ }
+}
diff --git a/example/mocha.js b/example/mocha.js
index e0c3856f..9c34f90d 100644
--- a/example/mocha.js
+++ b/example/mocha.js
@@ -1,6 +1,5 @@
;(function(){
-
// CommonJS require()
function require(p){
@@ -32,11 +31,11 @@ require.register = function (path, fn){
require.relative = function (parent) {
return function(p){
if ('.' != p.charAt(0)) return require(p);
-
+
var path = parent.split('/')
, segs = p.split('/');
path.pop();
-
+
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
if ('..' == seg) path.pop();
@@ -52,12 +51,366 @@ require.register("browser/debug.js", function(module, exports, require){
module.exports = function(type){
return function(){
-
}
};
+
}); // module: browser/debug.js
require.register("browser/diff.js", function(module, exports, require){
+/* See LICENSE file for terms of use */
+
+/*
+ * Text diff implementation.
+ *
+ * This library supports the following APIS:
+ * JsDiff.diffChars: Character by character diff
+ * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
+ * JsDiff.diffLines: Line based diff
+ *
+ * JsDiff.diffCss: Diff targeted at CSS content
+ *
+ * These methods are based on the implementation proposed in
+ * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
+ * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
+ */
+var JsDiff = (function() {
+ /*jshint maxparams: 5*/
+ function clonePath(path) {
+ return { newPos: path.newPos, components: path.components.slice(0) };
+ }
+ function removeEmpty(array) {
+ var ret = [];
+ for (var i = 0; i < array.length; i++) {
+ if (array[i]) {
+ ret.push(array[i]);
+ }
+ }
+ return ret;
+ }
+ function escapeHTML(s) {
+ var n = s;
+ n = n.replace(/&/g, '&amp;');
+ n = n.replace(/</g, '&lt;');
+ n = n.replace(/>/g, '&gt;');
+ n = n.replace(/"/g, '&quot;');
+
+ return n;
+ }
+
+ var Diff = function(ignoreWhitespace) {
+ this.ignoreWhitespace = ignoreWhitespace;
+ };
+ Diff.prototype = {
+ diff: function(oldString, newString) {
+ // Handle the identity case (this is due to unrolling editLength == 0
+ if (newString === oldString) {
+ return [{ value: newString }];
+ }
+ if (!newString) {
+ return [{ value: oldString, removed: true }];
+ }
+ if (!oldString) {
+ return [{ value: newString, added: true }];
+ }
+
+ newString = this.tokenize(newString);
+ oldString = this.tokenize(oldString);
+
+ var newLen = newString.length, oldLen = oldString.length;
+ var maxEditLength = newLen + oldLen;
+ var bestPath = [{ newPos: -1, components: [] }];
+
+ // Seed editLength = 0
+ var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
+ if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
+ return bestPath[0].components;
+ }
+
+ for (var editLength = 1; editLength <= maxEditLength; editLength++) {
+ for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
+ var basePath;
+ var addPath = bestPath[diagonalPath-1],
+ removePath = bestPath[diagonalPath+1];
+ oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
+ if (addPath) {
+ // No one else is going to attempt to use this value, clear it
+ bestPath[diagonalPath-1] = undefined;
+ }
+
+ var canAdd = addPath && addPath.newPos+1 < newLen;
+ var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
+ if (!canAdd && !canRemove) {
+ bestPath[diagonalPath] = undefined;
+ continue;
+ }
+
+ // Select the diagonal that we want to branch from. We select the prior
+ // path whose position in the new string is the farthest from the origin
+ // and does not pass the bounds of the diff graph
+ if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
+ basePath = clonePath(removePath);
+ this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
+ } else {
+ basePath = clonePath(addPath);
+ basePath.newPos++;
+ this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
+ }
+
+ var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
+
+ if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
+ return basePath.components;
+ } else {
+ bestPath[diagonalPath] = basePath;
+ }
+ }
+ }
+ },
+
+ pushComponent: function(components, value, added, removed) {
+ var last = components[components.length-1];
+ if (last && last.added === added && last.removed === removed) {
+ // We need to clone here as the component clone operation is just
+ // as shallow array clone
+ components[components.length-1] =
+ {value: this.join(last.value, value), added: added, removed: removed };
+ } else {
+ components.push({value: value, added: added, removed: removed });
+ }
+ },
+ extractCommon: function(basePath, newString, oldString, diagonalPath) {
+ var newLen = newString.length,
+ oldLen = oldString.length,
+ newPos = basePath.newPos,
+ oldPos = newPos - diagonalPath;
+ while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
+ newPos++;
+ oldPos++;
+
+ this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
+ }
+ basePath.newPos = newPos;
+ return oldPos;
+ },
+
+ equals: function(left, right) {
+ var reWhitespace = /\S/;
+ if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
+ return true;
+ } else {
+ return left === right;
+ }
+ },
+ join: function(left, right) {
+ return left + right;
+ },
+ tokenize: function(value) {
+ return value;
+ }
+ };
+
+ var CharDiff = new Diff();
+
+ var WordDiff = new Diff(true);
+ var WordWithSpaceDiff = new Diff();
+ WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
+ return removeEmpty(value.split(/(\s+|\b)/));
+ };
+
+ var CssDiff = new Diff(true);
+ CssDiff.tokenize = function(value) {
+ return removeEmpty(value.split(/([{}:;,]|\s+)/));
+ };
+
+ var LineDiff = new Diff();
+ LineDiff.tokenize = function(value) {
+ return value.split(/^/m);
+ };
+
+ return {
+ Diff: Diff,
+
+ diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
+ diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
+ diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); },
+ diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
+
+ diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
+
+ createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
+ var ret = [];
+
+ ret.push('Index: ' + fileName);
+ ret.push('===================================================================');
+ ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
+ ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
+
+ var diff = LineDiff.diff(oldStr, newStr);
+ if (!diff[diff.length-1].value) {
+ diff.pop(); // Remove trailing newline add
+ }
+ diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
+
+ function contextLines(lines) {
+ return lines.map(function(entry) { return ' ' + entry; });
+ }
+ function eofNL(curRange, i, current) {
+ var last = diff[diff.length-2],
+ isLast = i === diff.length-2,
+ isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);
+
+ // Figure out if this is the last line for the given file and missing NL
+ if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
+ curRange.push('\\ No newline at end of file');
+ }
+ }
+
+ var oldRangeStart = 0, newRangeStart = 0, curRange = [],
+ oldLine = 1, newLine = 1;
+ for (var i = 0; i < diff.length; i++) {
+ var current = diff[i],
+ lines = current.lines || current.value.replace(/\n$/, '').split('\n');
+ current.lines = lines;
+
+ if (current.added || current.removed) {
+ if (!oldRangeStart) {
+ var prev = diff[i-1];
+ oldRangeStart = oldLine;
+ newRangeStart = newLine;
+
+ if (prev) {
+ curRange = contextLines(prev.lines.slice(-4));
+ oldRangeStart -= curRange.length;
+ newRangeStart -= curRange.length;
+ }
+ }
+ curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; }));
+ eofNL(curRange, i, current);
+
+ if (current.added) {
+ newLine += lines.length;
+ } else {
+ oldLine += lines.length;
+ }
+ } else {
+ if (oldRangeStart) {
+ // Close out any changes that have been output (or join overlapping)
+ if (lines.length <= 8 && i < diff.length-2) {
+ // Overlapping
+ curRange.push.apply(curRange, contextLines(lines));
+ } else {
+ // end the range and output
+ var contextSize = Math.min(lines.length, 4);
+ ret.push(
+ '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize)
+ + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize)
+ + ' @@');
+ ret.push.apply(ret, curRange);
+ ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
+ if (lines.length <= 4) {
+ eofNL(ret, i, current);
+ }
+
+ oldRangeStart = 0; newRangeStart = 0; curRange = [];
+ }
+ }
+ oldLine += lines.length;
+ newLine += lines.length;
+ }
+ }
+
+ return ret.join('\n') + '\n';
+ },
+
+ applyPatch: function(oldStr, uniDiff) {
+ var diffstr = uniDiff.split('\n');
+ var diff = [];
+ var remEOFNL = false,
+ addEOFNL = false;
+
+ for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
+ if(diffstr[i][0] === '@') {
+ var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
+ diff.unshift({
+ start:meh[3],
+ oldlength:meh[2],
+ oldlines:[],
+ newlength:meh[4],
+ newlines:[]
+ });
+ } else if(diffstr[i][0] === '+') {
+ diff[0].newlines.push(diffstr[i].substr(1));
+ } else if(diffstr[i][0] === '-') {
+ diff[0].oldlines.push(diffstr[i].substr(1));
+ } else if(diffstr[i][0] === ' ') {
+ diff[0].newlines.push(diffstr[i].substr(1));
+ diff[0].oldlines.push(diffstr[i].substr(1));
+ } else if(diffstr[i][0] === '\\') {
+ if (diffstr[i-1][0] === '+') {
+ remEOFNL = true;
+ } else if(diffstr[i-1][0] === '-') {
+ addEOFNL = true;
+ }
+ }
+ }
+
+ var str = oldStr.split('\n');
+ for (var i = diff.length - 1; i >= 0; i--) {
+ var d = diff[i];
+ for (var j = 0; j < d.oldlength; j++) {
+ if(str[d.start-1+j] !== d.oldlines[j]) {
+ return false;
+ }
+ }
+ Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
+ }
+
+ if (remEOFNL) {
+ while (!str[str.length-1]) {
+ str.pop();
+ }
+ } else if (addEOFNL) {
+ str.push('');
+ }
+ return str.join('\n');
+ },
+
+ convertChangesToXML: function(changes){
+ var ret = [];
+ for ( var i = 0; i < changes.length; i++) {
+ var change = changes[i];
+ if (change.added) {
+ ret.push('<ins>');
+ } else if (change.removed) {
+ ret.push('<del>');
+ }
+
+ ret.push(escapeHTML(change.value));
+
+ if (change.added) {
+ ret.push('</ins>');
+ } else if (change.removed) {
+ ret.push('</del>');
+ }
+ }
+ return ret.join('');
+ },
+
+ // See: http://code.google.com/p/google-diff-match-patch/wiki/API
+ convertChangesToDMP: function(changes){
+ var ret = [], change;
+ for ( var i = 0; i < changes.length; i++) {
+ change = changes[i];
+ ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
+ }
+ return ret;
+ }
+ };
+})();
+
+if (typeof module !== 'undefined') {
+ module.exports = JsDiff;
+}
}); // module: browser/diff.js
@@ -386,8 +739,14 @@ exports.isatty = function(){
};
exports.getWindowSize = function(){
- return [window.innerHeight, window.innerWidth];
+ if ('innerHeight' in global) {
+ return [global.innerHeight, global.innerWidth];
+ } else {
+ // In a Web Worker, the DOM Window is not available.
+ return [640, 480];
+ }
};
+
}); // module: browser/tty.js
require.register("context.js", function(module, exports, require){
@@ -407,7 +766,7 @@ module.exports = Context;
function Context(){}
/**
- * Set the context `Runnable` to `runnable`.
+ * Set or get the context `Runnable` to `runnable`.
*
* @param {Runnable} runnable
* @return {Context}
@@ -415,7 +774,8 @@ function Context(){}
*/
Context.prototype.runnable = function(runnable){
- this._runnable = runnable;
+ if (0 == arguments.length) return this._runnable;
+ this.test = this._runnable = runnable;
return this;
};
@@ -428,7 +788,20 @@ Context.prototype.runnable = function(runnable){
*/
Context.prototype.timeout = function(ms){
- this._runnable.timeout(ms);
+ this.runnable().timeout(ms);
+ return this;
+};
+
+/**
+ * Set test slowness threshold `ms`.
+ *
+ * @param {Number} ms
+ * @return {Context} self
+ * @api private
+ */
+
+Context.prototype.slow = function(ms){
+ this.runnable().slow(ms);
return this;
};
@@ -441,9 +814,9 @@ Context.prototype.timeout = function(ms){
Context.prototype.inspect = function(){
return JSON.stringify(this, function(key, val){
- return '_runnable' == key
- ? undefined
- : val;
+ if ('_runnable' == key) return;
+ if ('test' == key) return;
+ return val;
}, 2);
};
@@ -480,10 +853,30 @@ function Hook(title, fn) {
* Inherit from `Runnable.prototype`.
*/
-Hook.prototype = new Runnable;
+function F(){};
+F.prototype = Runnable.prototype;
+Hook.prototype = new F;
Hook.prototype.constructor = Hook;
+/**
+ * Get or set the test `err`.
+ *
+ * @param {Error} err
+ * @return {Error}
+ * @api public
+ */
+
+Hook.prototype.error = function(err){
+ if (0 == arguments.length) {
+ var err = this._error;
+ this._error = null;
+ return err;
+ }
+
+ this._error = err;
+};
+
}); // module: hook.js
require.register("interfaces/bdd.js", function(module, exports, require){
@@ -493,11 +886,12 @@ require.register("interfaces/bdd.js", function(module, exports, require){
*/
var Suite = require('../suite')
- , Test = require('../test');
+ , Test = require('../test')
+ , utils = require('../utils');
/**
* BDD-style interface:
- *
+ *
* describe('Array', function(){
* describe('#indexOf()', function(){
* it('should return -1 when not present', function(){
@@ -509,18 +903,13 @@ var Suite = require('../suite')
* });
* });
* });
- *
+ *
*/
module.exports = function(suite){
var suites = [suite];
- suite.on('pre-require', function(context){
-
- // noop variants
-
- context.xdescribe = function(){};
- context.xit = function(){};
+ suite.on('pre-require', function(context, file, mocha){
/**
* Execute before running tests.
@@ -559,22 +948,72 @@ module.exports = function(suite){
* and callback `fn` containing nested suites
* and/or tests.
*/
-
+
context.describe = context.context = function(title, fn){
var suite = Suite.create(suites[0], title);
suites.unshift(suite);
- fn();
+ fn.call(suite);
+ suites.shift();
+ return suite;
+ };
+
+ /**
+ * Pending describe.
+ */
+
+ context.xdescribe =
+ context.xcontext =
+ context.describe.skip = function(title, fn){
+ var suite = Suite.create(suites[0], title);
+ suite.pending = true;
+ suites.unshift(suite);
+ fn.call(suite);
suites.shift();
};
+ /**
+ * Exclusive suite.
+ */
+
+ context.describe.only = function(title, fn){
+ var suite = context.describe(title, fn);
+ mocha.grep(suite.fullTitle());
+ return suite;
+ };
+
/**
* Describe a specification or test-case
* with the given `title` and callback `fn`
* acting as a thunk.
*/
- context.it = function(title, fn){
- suites[0].addTest(new Test(title, fn));
+ context.it = context.specify = function(title, fn){
+ var suite = suites[0];
+ if (suite.pending) var fn = null;
+ var test = new Test(title, fn);
+ suite.addTest(test);
+ return test;
+ };
+
+ /**
+ * Exclusive test-case.
+ */
+
+ context.it.only = function(title, fn){
+ var test = context.it(title, fn);
+ var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
+ mocha.grep(new RegExp(reString));
+ return test;
+ };
+
+ /**
+ * Pending test case.
+ */
+
+ context.xit =
+ context.xspecify =
+ context.it.skip = function(title){
+ context.it(title);
};
});
};
@@ -592,19 +1031,19 @@ var Suite = require('../suite')
/**
* TDD-style interface:
- *
+ *
* exports.Array = {
* '#indexOf()': {
* 'should return -1 when the value is not present': function(){
- *
+ *
* },
*
* 'should return the correct index when the value is present': function(){
- *
+ *
* }
* }
* };
- *
+ *
*/
module.exports = function(suite){
@@ -642,6 +1081,7 @@ module.exports = function(suite){
}
}
};
+
}); // module: interfaces/exports.js
require.register("interfaces/index.js", function(module, exports, require){
@@ -660,37 +1100,38 @@ require.register("interfaces/qunit.js", function(module, exports, require){
*/
var Suite = require('../suite')
- , Test = require('../test');
+ , Test = require('../test')
+ , utils = require('../utils');
/**
* QUnit-style interface:
- *
+ *
* suite('Array');
- *
+ *
* test('#length', function(){
* var arr = [1,2,3];
* ok(arr.length == 3);
* });
- *
+ *
* test('#indexOf()', function(){
* var arr = [1,2,3];
* ok(arr.indexOf(1) == 0);
* ok(arr.indexOf(2) == 1);
* ok(arr.indexOf(3) == 2);
* });
- *
+ *
* suite('String');
- *
+ *
* test('#length', function(){
* ok('foo'.length == 3);
* });
- *
+ *
*/
module.exports = function(suite){
var suites = [suite];
- suite.on('pre-require', function(context){
+ suite.on('pre-require', function(context, file, mocha){
/**
* Execute before running tests.
@@ -727,11 +1168,21 @@ module.exports = function(suite){
/**
* Describe a "suite" with the given `title`.
*/
-
+
context.suite = function(title){
if (suites.length > 1) suites.shift();
var suite = Suite.create(suites[0], title);
suites.unshift(suite);
+ return suite;
+ };
+
+ /**
+ * Exclusive test-case.
+ */
+
+ context.suite.only = function(title, fn){
+ var suite = context.suite(title, fn);
+ mocha.grep(suite.fullTitle());
};
/**
@@ -741,7 +1192,27 @@ module.exports = function(suite){
*/
context.test = function(title, fn){
- suites[0].addTest(new Test(title, fn));
+ var test = new Test(title, fn);
+ suites[0].addTest(test);
+ return test;
+ };
+
+ /**
+ * Exclusive test-case.
+ */
+
+ context.test.only = function(title, fn){
+ var test = context.test(title, fn);
+ var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
+ mocha.grep(new RegExp(reString));
+ };
+
+ /**
+ * Pending test case.
+ */
+
+ context.test.skip = function(title){
+ context.test(title);
};
});
};
@@ -755,7 +1226,8 @@ require.register("interfaces/tdd.js", function(module, exports, require){
*/
var Suite = require('../suite')
- , Test = require('../test');
+ , Test = require('../test')
+ , utils = require('../utils');;
/**
* TDD-style interface:
@@ -765,7 +1237,7 @@ var Suite = require('../suite')
* suiteSetup(function(){
*
* });
- *
+ *
* test('should return -1 when not present', function(){
*
* });
@@ -785,7 +1257,7 @@ var Suite = require('../suite')
module.exports = function(suite){
var suites = [suite];
- suite.on('pre-require', function(context){
+ suite.on('pre-require', function(context, file, mocha){
/**
* Execute before each test case.
@@ -828,10 +1300,31 @@ module.exports = function(suite){
context.suite = function(title, fn){
var suite = Suite.create(suites[0], title);
suites.unshift(suite);
- fn();
+ fn.call(suite);
+ suites.shift();
+ return suite;
+ };
+
+ /**
+ * Pending suite.
+ */
+ context.suite.skip = function(title, fn) {
+ var suite = Suite.create(suites[0], title);
+ suite.pending = true;
+ suites.unshift(suite);
+ fn.call(suite);
suites.shift();
};
+ /**
+ * Exclusive test-case.
+ */
+
+ context.suite.only = function(title, fn){
+ var suite = context.suite(title, fn);
+ mocha.grep(suite.fullTitle());
+ };
+
/**
* Describe a specification or test-case
* with the given `title` and callback `fn`
@@ -839,7 +1332,29 @@ module.exports = function(suite){
*/
context.test = function(title, fn){
- suites[0].addTest(new Test(title, fn));
+ var suite = suites[0];
+ if (suite.pending) var fn = null;
+ var test = new Test(title, fn);
+ suite.addTest(test);
+ return test;
+ };
+
+ /**
+ * Exclusive test-case.
+ */
+
+ context.test.only = function(title, fn){
+ var test = context.test(title, fn);
+ var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
+ mocha.grep(new RegExp(reString));
+ };
+
+ /**
+ * Pending test case.
+ */
+
+ context.test.skip = function(title){
+ context.test(title);
};
});
};
@@ -847,7 +1362,6 @@ module.exports = function(suite){
}); // module: interfaces/tdd.js
require.register("mocha.js", function(module, exports, require){
-
/*!
* mocha
* Copyright(c) 2011 TJ Holowaychuk <[email protected]>
@@ -858,7 +1372,8 @@ require.register("mocha.js", function(module, exports, require){
* Module dependencies.
*/
-var path = require('browser/path');
+var path = require('browser/path')
+ , utils = require('./utils');
/**
* Expose `Mocha`.
@@ -866,17 +1381,11 @@ var path = require('browser/path');
exports = module.exports = Mocha;
-/**
- * Library version.
- */
-
-exports.version = '1.1.0';
-
/**
* Expose internals.
*/
-exports.utils = require('./utils');
+exports.utils = utils;
exports.interfaces = require('./interfaces');
exports.reporters = require('./reporters');
exports.Runnable = require('./runnable');
@@ -907,6 +1416,8 @@ function image(name) {
* - `reporter` reporter instance, defaults to `mocha.reporters.Dot`
* - `globals` array of accepted globals
* - `timeout` timeout in milliseconds
+ * - `bail` bail on the first test failure
+ * - `slow` milliseconds to wait before considering a test slow
* - `ignoreLeaks` ignore global leaks
* - `grep` string or regexp to filter tests with
*
@@ -921,10 +1432,25 @@ function Mocha(options) {
this.grep(options.grep);
this.suite = new exports.Suite('', new exports.Context);
this.ui(options.ui);
+ this.bail(options.bail);
this.reporter(options.reporter);
- if (options.timeout) this.suite.timeout(options.timeout);
+ if (null != options.timeout) this.timeout(options.timeout);
+ if (options.slow) this.slow(options.slow);
}
+/**
+ * Enable or disable bailing on the first failure.
+ *
+ * @param {Boolean} [bail]
+ * @api public
+ */
+
+Mocha.prototype.bail = function(bail){
+ if (0 == arguments.length) bail = true;
+ this.suite.bail(bail);
+ return this;
+};
+
/**
* Add test `file`.
*
@@ -938,16 +1464,24 @@ Mocha.prototype.addFile = function(file){
};
/**
- * Set reporter to `name`, defaults to "dot".
+ * Set reporter to `reporter`, defaults to "dot".
*
- * @param {String} name
+ * @param {String|Function} reporter name or constructor
* @api public
*/
-Mocha.prototype.reporter = function(name){
- name = name || 'dot';
- this._reporter = require('./reporters/' + name);
- if (!this._reporter) throw new Error('invalid reporter "' + name + '"');
+Mocha.prototype.reporter = function(reporter){
+ if ('function' == typeof reporter) {
+ this._reporter = reporter;
+ } else {
+ reporter = reporter || 'dot';
+ try {
+ this._reporter = require('./reporters/' + reporter);
+ } catch (err) {
+ this._reporter = require(reporter);
+ }
+ if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"');
+ }
return this;
};
@@ -972,13 +1506,16 @@ Mocha.prototype.ui = function(name){
* @api private
*/
-Mocha.prototype.loadFiles = function(){
+Mocha.prototype.loadFiles = function(fn){
+ var self = this;
var suite = this.suite;
+ var pending = this.files.length;
this.files.forEach(function(file){
file = path.resolve(file);
- suite.emit('pre-require', global, file);
- suite.emit('require', require(file), file);
- suite.emit('post-require', global, file);
+ suite.emit('pre-require', global, file, self);
+ suite.emit('require', require(file), file, self);
+ suite.emit('post-require', global, file, self);
+ --pending || (fn && fn());
});
};
@@ -988,100 +1525,325 @@ Mocha.prototype.loadFiles = function(){
* @api private
*/
-Mocha.prototype.growl = function(runner, reporter) {
+Mocha.prototype._growl = function(runner, reporter) {
var notify = require('growl');
runner.on('end', function(){
var stats = reporter.stats;
if (stats.failures) {
var msg = stats.failures + ' of ' + runner.total + ' tests failed';
- notify(msg, { title: 'Failed', image: image('fail') });
+ notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
} else {
notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
- title: 'Passed'
- , image: image('pass')
+ name: 'mocha'
+ , title: 'Passed'
+ , image: image('ok')
});
}
});
};
/**
- * Add regexp to grep for to the options object
+ * Add regexp to grep, if `re` is a string it is escaped.
*
- * @param {RegExp} or {String} re
+ * @param {RegExp|String} re
* @return {Mocha}
* @api public
*/
Mocha.prototype.grep = function(re){
this.options.grep = 'string' == typeof re
- ? new RegExp(re)
+ ? new RegExp(utils.escapeRegexp(re))
: re;
return this;
};
/**
- * Run tests and invoke `fn()` when complete.
+ * Invert `.grep()` matches.
*
- * @param {Function} fn
- * @return {Runner}
+ * @return {Mocha}
* @api public
*/
-Mocha.prototype.run = function(fn){
- this.loadFiles();
- var suite = this.suite;
- var options = this.options;
- var runner = new exports.Runner(suite);
- var reporter = new this._reporter(runner);
- runner.ignoreLeaks = options.ignoreLeaks;
- if (options.grep) runner.grep(options.grep);
- if (options.globals) runner.globals(options.globals);
- if (options.growl) this.growl(runner, reporter);
- return runner.run(fn);
+Mocha.prototype.invert = function(){
+ this.options.invert = true;
+ return this;
};
-}); // module: mocha.js
-
-require.register("reporters/base.js", function(module, exports, require){
/**
- * Module dependencies.
+ * Ignore global leaks.
+ *
+ * @param {Boolean} ignore
+ * @return {Mocha}
+ * @api public
*/
-var tty = require('browser/tty')
- , diff = require('browser/diff');
+Mocha.prototype.ignoreLeaks = function(ignore){
+ this.options.ignoreLeaks = !!ignore;
+ return this;
+};
/**
- * Save timer references to avoid Sinon interfering (see GH-237).
+ * Enable global leak checking.
+ *
+ * @return {Mocha}
+ * @api public
*/
-var Date = global.Date
- , setTimeout = global.setTimeout
- , setInterval = global.setInterval
- , clearTimeout = global.clearTimeout
- , clearInterval = global.clearInterval;
+Mocha.prototype.checkLeaks = function(){
+ this.options.ignoreLeaks = false;
+ return this;
+};
/**
- * Check if both stdio streams are associated with a tty.
+ * Enable growl support.
+ *
+ * @return {Mocha}
+ * @api public
*/
-var isatty = tty.isatty(1) && tty.isatty(2);
+Mocha.prototype.growl = function(){
+ this.options.growl = true;
+ return this;
+};
/**
- * Expose `Base`.
+ * Ignore `globals` array or string.
+ *
+ * @param {Array|String} globals
+ * @return {Mocha}
+ * @api public
*/
-exports = module.exports = Base;
+Mocha.prototype.globals = function(globals){
+ this.options.globals = (this.options.globals || []).concat(globals);
+ return this;
+};
/**
- * Enable coloring by default.
+ * Set the timeout in milliseconds.
+ *
+ * @param {Number} timeout
+ * @return {Mocha}
+ * @api public
*/
-exports.useColors = isatty;
+Mocha.prototype.timeout = function(timeout){
+ this.suite.timeout(timeout);
+ return this;
+};
/**
- * Default color map.
- */
+ * Set slowness threshold in milliseconds.
+ *
+ * @param {Number} slow
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.slow = function(slow){
+ this.suite.slow(slow);
+ return this;
+};
+
+/**
+ * Makes all tests async (accepting a callback)
+ *
+ * @return {Mocha}
+ * @api public
+ */
+
+Mocha.prototype.asyncOnly = function(){
+ this.options.asyncOnly = true;
+ return this;
+};
+
+/**
+ * Run tests and invoke `fn()` when complete.
+ *
+ * @param {Function} fn
+ * @return {Runner}
+ * @api public
+ */
+
+Mocha.prototype.run = function(fn){
+ if (this.files.length) this.loadFiles();
+ var suite = this.suite;
+ var options = this.options;
+ var runner = new exports.Runner(suite);
+ var reporter = new this._reporter(runner);
+ runner.ignoreLeaks = false !== options.ignoreLeaks;
+ runner.asyncOnly = options.asyncOnly;
+ if (options.grep) runner.grep(options.grep, options.invert);
+ if (options.globals) runner.globals(options.globals);
+ if (options.growl) this._growl(runner, reporter);
+ return runner.run(fn);
+};
+
+}); // module: mocha.js
+
+require.register("ms.js", function(module, exports, require){
+/**
+ * Helpers.
+ */
+
+var s = 1000;
+var m = s * 60;
+var h = m * 60;
+var d = h * 24;
+var y = d * 365.25;
+
+/**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ * - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} options
+ * @return {String|Number}
+ * @api public
+ */
+
+module.exports = function(val, options){
+ options = options || {};
+ if ('string' == typeof val) return parse(val);
+ return options.long
+ ? long(val)
+ : short(val);
+};
+
+/**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+function parse(str) {
+ var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
+ if (!match) return;
+ var n = parseFloat(match[1]);
+ var type = (match[2] || 'ms').toLowerCase();
+ switch (type) {
+ case 'years':
+ case 'year':
+ case 'y':
+ return n * y;
+ case 'days':
+ case 'day':
+ case 'd':
+ return n * d;
+ case 'hours':
+ case 'hour':
+ case 'h':
+ return n * h;
+ case 'minutes':
+ case 'minute':
+ case 'm':
+ return n * m;
+ case 'seconds':
+ case 'second':
+ case 's':
+ return n * s;
+ case 'ms':
+ return n;
+ }
+}
+
+/**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function short(ms) {
+ if (ms >= d) return Math.round(ms / d) + 'd';
+ if (ms >= h) return Math.round(ms / h) + 'h';
+ if (ms >= m) return Math.round(ms / m) + 'm';
+ if (ms >= s) return Math.round(ms / s) + 's';
+ return ms + 'ms';
+}
+
+/**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function long(ms) {
+ return plural(ms, d, 'day')
+ || plural(ms, h, 'hour')
+ || plural(ms, m, 'minute')
+ || plural(ms, s, 'second')
+ || ms + ' ms';
+}
+
+/**
+ * Pluralization helper.
+ */
+
+function plural(ms, n, name) {
+ if (ms < n) return;
+ if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
+ return Math.ceil(ms / n) + ' ' + name + 's';
+}
+
+}); // module: ms.js
+
+require.register("reporters/base.js", function(module, exports, require){
+
+/**
+ * Module dependencies.
+ */
+
+var tty = require('browser/tty')
+ , diff = require('browser/diff')
+ , ms = require('../ms');
+
+/**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+var Date = global.Date
+ , setTimeout = global.setTimeout
+ , setInterval = global.setInterval
+ , clearTimeout = global.clearTimeout
+ , clearInterval = global.clearInterval;
+
+/**
+ * Check if both stdio streams are associated with a tty.
+ */
+
+var isatty = tty.isatty(1) && tty.isatty(2);
+
+/**
+ * Expose `Base`.
+ */
+
+exports = module.exports = Base;
+
+/**
+ * Enable coloring by default.
+ */
+
+exports.useColors = isatty || (process.env.MOCHA_COLORS !== undefined);
+
+/**
+ * Inline diffs instead of +/-
+ */
+
+exports.inlineDiffs = false;
+
+/**
+ * Default color map.
+ */
exports.colors = {
'pass': 90
@@ -1105,6 +1867,23 @@ exports.colors = {
, 'diff removed': 41
};
+/**
+ * Default symbol map.
+ */
+
+exports.symbols = {
+ ok: '✓',
+ err: '✖',
+ dot: '․'
+};
+
+// With node.js on Windows: use symbols available in terminal default fonts
+if ('win32' == process.platform) {
+ exports.symbols.ok = '\u221A';
+ exports.symbols.err = '\u00D7';
+ exports.symbols.dot = '.';
+}
+
/**
* Color `str` with the given `type`,
* allowing colors to be disabled,
@@ -1119,7 +1898,7 @@ exports.colors = {
var color = exports.color = function(type, str) {
if (!exports.useColors) return str;
- return '\033[' + exports.colors[type] + 'm' + str + '\033[0m';
+ return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
};
/**
@@ -1142,19 +1921,19 @@ exports.window = {
exports.cursor = {
hide: function(){
- process.stdout.write('\033[?25l');
+ process.stdout.write('\u001b[?25l');
},
show: function(){
- process.stdout.write('\033[?25h');
+ process.stdout.write('\u001b[?25h');
},
deleteLine: function(){
- process.stdout.write('\033[2K');
+ process.stdout.write('\u001b[2K');
},
beginningOfLine: function(){
- process.stdout.write('\033[0G');
+ process.stdout.write('\u001b[0G');
},
CR: function(){
@@ -1163,13 +1942,6 @@ exports.cursor = {
}
};
-/**
- * A test is considered slow if it
- * exceeds the following value in milliseconds.
- */
-
-exports.slow = 75;
-
/**
* Outut the given `failures` as a list.
*
@@ -1192,38 +1964,29 @@ exports.list = function(failures){
, index = stack.indexOf(message) + message.length
, msg = stack.slice(0, index)
, actual = err.actual
- , expected = err.expected;
+ , expected = err.expected
+ , escape = true;
+
+ // uncaught
+ if (err.uncaught) {
+ msg = 'Uncaught ' + msg;
+ }
+
+ // explicitly show diff
+ if (err.showDiff && sameType(actual, expected)) {
+ escape = false;
+ err.actual = actual = stringify(actual);
+ err.expected = expected = stringify(expected);
+ }
// actual / expected diff
if ('string' == typeof actual && 'string' == typeof expected) {
- var len = Math.max(actual.length, expected.length);
-
- if (len < 20) msg = errorDiff(err, 'Chars');
- else msg = errorDiff(err, 'Words');
-
- // linenos
- var lines = msg.split('\n');
- if (lines.length > 4) {
- var width = String(lines.length).length;
- msg = lines.map(function(str, i){
- return pad(++i, width) + ' |' + ' ' + str;
- }).join('\n');
+ fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n');
+ if (exports.inlineDiffs) {
+ msg = inlineDiff(err, escape);
+ } else {
+ msg = unifiedDiff(err, escape);
}
-
- // legend
- msg = '\n'
- + color('diff removed', 'actual')
- + ' '
- + color('diff added', 'expected')
- + '\n\n'
- + msg
- + '\n';
-
- // indent
- msg = msg.replace(/^/gm, ' ');
-
- fmt = color('error title', ' %s) %s:\n%s')
- + color('error stack', '\n%s\n');
}
// indent stack trace without msg
@@ -1254,6 +2017,8 @@ function Base(runner) {
if (!runner) return;
this.runner = runner;
+ runner.stats = stats;
+
runner.on('start', function(){
stats.start = new Date;
});
@@ -1271,8 +2036,8 @@ function Base(runner) {
runner.on('pass', function(test){
stats.passes = stats.passes || 0;
- var medium = exports.slow / 2;
- test.speed = test.duration > exports.slow
+ var medium = test.slow() / 2;
+ test.speed = test.duration > test.slow()
? 'slow'
: test.duration > medium
? 'medium'
@@ -1306,48 +2071,38 @@ function Base(runner) {
*/
Base.prototype.epilogue = function(){
- var stats = this.stats
- , fmt
- , tests;
+ var stats = this.stats;
+ var tests;
+ var fmt;
console.log();
- function pluralize(n) {
- return 1 == n ? 'test' : 'tests';
+ // passes
+ fmt = color('bright pass', ' ')
+ + color('green', ' %d passing')
+ + color('light', ' (%s)');
+
+ console.log(fmt,
+ stats.passes || 0,
+ ms(stats.duration));
+
+ // pending
+ if (stats.pending) {
+ fmt = color('pending', ' ')
+ + color('pending', ' %d pending');
+
+ console.log(fmt, stats.pending);
}
- // failure
+ // failures
if (stats.failures) {
- fmt = color('bright fail', ' ✖')
- + color('fail', ' %d of %d %s failed')
- + color('light', ':')
+ fmt = color('fail', ' %d failing');
console.error(fmt,
- stats.failures,
- this.runner.total,
- pluralize(this.runner.total));
+ stats.failures);
Base.list(this.failures);
console.error();
- return;
- }
-
- // pass
- fmt = color('bright pass', ' ✔')
- + color('green', ' %d %s complete')
- + color('light', ' (%dms)');
-
- console.log(fmt,
- stats.tests || 0,
- pluralize(stats.tests),
- stats.duration);
-
- // pending
- if (stats.pending) {
- fmt = color('pending', ' •')
- + color('pending', ' %d %s pending');
-
- console.log(fmt, stats.pending, pluralize(stats.pending));
}
console.log();
@@ -1367,6 +2122,73 @@ function pad(str, len) {
return Array(len - str.length + 1).join(' ') + str;
}
+
+/**
+ * Returns an inline diff between 2 strings with coloured ANSI output
+ *
+ * @param {Error} Error with actual/expected
+ * @return {String} Diff
+ * @api private
+ */
+
+function inlineDiff(err, escape) {
+ var msg = errorDiff(err, 'WordsWithSpace', escape);
+
+ // linenos
+ var lines = msg.split('\n');
+ if (lines.length > 4) {
+ var width = String(lines.length).length;
+ msg = lines.map(function(str, i){
+ return pad(++i, width) + ' |' + ' ' + str;
+ }).join('\n');
+ }
+
+ // legend
+ msg = '\n'
+ + color('diff removed', 'actual')
+ + ' '
+ + color('diff added', 'expected')
+ + '\n\n'
+ + msg
+ + '\n';
+
+ // indent
+ msg = msg.replace(/^/gm, ' ');
+ return msg;
+}
+
+/**
+ * Returns a unified diff between 2 strings
+ *
+ * @param {Error} Error with actual/expected
+ * @return {String} Diff
+ * @api private
+ */
+
+function unifiedDiff(err, escape) {
+ var indent = ' ';
+ function cleanUp(line) {
+ if (escape) {
+ line = escapeInvisibles(line);
+ }
+ if (line[0] === '+') return indent + colorLines('diff added', line);
+ if (line[0] === '-') return indent + colorLines('diff removed', line);
+ if (line.match(/\@\@/)) return null;
+ if (line.match(/\\ No newline/)) return null;
+ else return indent + line;
+ }
+ function notBlank(line) {
+ return line != null;
+ }
+ msg = diff.createPatch('string', err.actual, err.expected);
+ var lines = msg.split('\n').splice(4);
+ return '\n '
+ + colorLines('diff added', '+ expected') + ' '
+ + colorLines('diff removed', '- actual')
+ + '\n\n'
+ + lines.map(cleanUp).filter(notBlank).join('\n');
+}
+
/**
* Return a character diff for `err`.
*
@@ -1375,15 +2197,29 @@ function pad(str, len) {
* @api private
*/
-function errorDiff(err, type) {
- return diff['diff' + type](err.actual, err.expected).map(function(str){
- if (/^(\n+)$/.test(str.value)) str.value = Array(++RegExp.$1.length).join('<newline>');
+function errorDiff(err, type, escape) {
+ var actual = escape ? escapeInvisibles(err.actual) : err.actual;
+ var expected = escape ? escapeInvisibles(err.expected) : err.expected;
+ return diff['diff' + type](actual, expected).map(function(str){
if (str.added) return colorLines('diff added', str.value);
if (str.removed) return colorLines('diff removed', str.value);
return str.value;
}).join('');
}
+/**
+ * Returns a string with all invisible characters in plain text
+ *
+ * @param {String} line
+ * @return {String}
+ * @api private
+ */
+function escapeInvisibles(line) {
+ return line.replace(/\t/g, '<tab>')
+ .replace(/\r/g, '<CR>')
+ .replace(/\n/g, '<LF>\n');
+}
+
/**
* Color lines for `str`, using the color `name`.
*
@@ -1399,6 +2235,34 @@ function colorLines(name, str) {
}).join('\n');
}
+/**
+ * Stringify `obj`.
+ *
+ * @param {Mixed} obj
+ * @return {String}
+ * @api private
+ */
+
+function stringify(obj) {
+ if (obj instanceof RegExp) return obj.toString();
+ return JSON.stringify(obj, null, 2);
+}
+
+/**
+ * Check that a / b have the same type.
+ *
+ * @param {Object} a
+ * @param {Object} b
+ * @return {Boolean}
+ * @api private
+ */
+
+function sameType(a, b) {
+ a = Object.prototype.toString.call(a);
+ b = Object.prototype.toString.call(b);
+ return a == b;
+}
+
}); // module: reporters/base.js
require.register("reporters/doc.js", function(module, exports, require){
@@ -1440,7 +2304,7 @@ function Doc(runner) {
++indents;
console.log('%s<section class="suite">', indent());
++indents;
- console.log('%s<h1>%s</h1>', indent(), suite.title);
+ console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
console.log('%s<dl>', indent());
});
@@ -1453,29 +2317,12 @@ function Doc(runner) {
});
runner.on('pass', function(test){
- console.log('%s <dt>%s</dt>', indent(), test.title);
- var code = utils.escape(clean(test.fn.toString()));
+ console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title));
+ var code = utils.escape(utils.clean(test.fn.toString()));
console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code);
});
}
-/**
- * Strip the function definition from `str`,
- * and re-indent for pre whitespace.
- */
-
-function clean(str) {
- str = str
- .replace(/^function *\(.*\) *{/, '')
- .replace(/\s+\}$/, '');
-
- var spaces = str.match(/^\n?( *)/)[1].length
- , re = new RegExp('^ {' + spaces + '}', 'gm');
-
- str = str.replace(re, '');
-
- return str;
-}
}); // module: reporters/doc.js
require.register("reporters/dot.js", function(module, exports, require){
@@ -1513,21 +2360,21 @@ function Dot(runner) {
});
runner.on('pending', function(test){
- process.stdout.write(color('pending', '.'));
+ process.stdout.write(color('pending', Base.symbols.dot));
});
runner.on('pass', function(test){
if (++n % width == 0) process.stdout.write('\n ');
if ('slow' == test.speed) {
- process.stdout.write(color('bright yellow', '.'));
+ process.stdout.write(color('bright yellow', Base.symbols.dot));
} else {
- process.stdout.write(color(test.speed, '.'));
+ process.stdout.write(color(test.speed, Base.symbols.dot));
}
});
runner.on('fail', function(test, err){
if (++n % width == 0) process.stdout.write('\n ');
- process.stdout.write(color('fail', '.'));
+ process.stdout.write(color('fail', Base.symbols.dot));
});
runner.on('end', function(){
@@ -1540,7 +2387,9 @@ function Dot(runner) {
* Inherit from `Base.prototype`.
*/
-Dot.prototype = new Base;
+function F(){};
+F.prototype = Base.prototype;
+Dot.prototype = new F;
Dot.prototype.constructor = Dot;
}); // module: reporters/dot.js
@@ -1584,6 +2433,13 @@ function HTMLCov(runner) {
});
}
+/**
+ * Return coverage class for `n`.
+ *
+ * @return {String}
+ * @api private
+ */
+
function coverageClass(n) {
if (n >= 75) return 'high';
if (n >= 50) return 'medium';
@@ -1623,10 +2479,10 @@ exports = module.exports = HTML;
* Stats template.
*/
-var statsTemplate = '<ul id="stats">'
+var statsTemplate = '<ul id="mocha-stats">'
+ '<li class="progress"><canvas width="40" height="40"></canvas></li>'
- + '<li class="passes">passes: <em>0</em></li>'
- + '<li class="failures">failures: <em>0</em></li>'
+ + '<li class="passes"><a href="#">passes:</a> <em>0</em></li>'
+ + '<li class="failures"><a href="#">failures:</a> <em>0</em></li>'
+ '<li class="duration">duration: <em>0</em>s</li>'
+ '</ul>';
@@ -1637,31 +2493,56 @@ var statsTemplate = '<ul id="stats">'
* @api public
*/
-function HTML(runner) {
+function HTML(runner, root) {
Base.call(this, runner);
var self = this
, stats = this.stats
, total = runner.total
- , root = document.getElementById('mocha')
, stat = fragment(statsTemplate)
, items = stat.getElementsByTagName('li')
, passes = items[1].getElementsByTagName('em')[0]
+ , passesLink = items[1].getElementsByTagName('a')[0]
, failures = items[2].getElementsByTagName('em')[0]
+ , failuresLink = items[2].getElementsByTagName('a')[0]
, duration = items[3].getElementsByTagName('em')[0]
, canvas = stat.getElementsByTagName('canvas')[0]
- , report = fragment('<ul id="report"></ul>')
+ , report = fragment('<ul id="mocha-report"></ul>')
, stack = [report]
, progress
, ctx
+ root = root || document.getElementById('mocha');
+
if (canvas.getContext) {
+ var ratio = window.devicePixelRatio || 1;
+ canvas.style.width = canvas.width;
+ canvas.style.height = canvas.height;
+ canvas.width *= ratio;
+ canvas.height *= ratio;
ctx = canvas.getContext('2d');
+ ctx.scale(ratio, ratio);
progress = new Progress;
}
if (!root) return error('#mocha div missing, add it to your document');
+ // pass toggle
+ on(passesLink, 'click', function(){
+ unhide();
+ var name = /pass/.test(report.className) ? '' : ' pass';
+ report.className = report.className.replace(/fail|pass/g, '') + name;
+ if (report.className.trim()) hideSuitesWithout('test pass');
+ });
+
+ // failure toggle
+ on(failuresLink, 'click', function(){
+ unhide();
+ var name = /fail/.test(report.className) ? '' : ' fail';
+ report.className = report.className.replace(/fail|pass/g, '') + name;
+ if (report.className.trim()) hideSuitesWithout('test fail');
+ });
+
root.appendChild(stat);
root.appendChild(report);
@@ -1671,8 +2552,8 @@ function HTML(runner) {
if (suite.root) return;
// suite
- var url = location.protocol + '//' + location.host + location.pathname + '?grep=^' + utils.escapeRegexp(suite.fullTitle());
- var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, suite.title);
+ var url = '?grep=' + encodeURIComponent(suite.fullTitle());
+ var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, escape(suite.title));
// container
stack[0].appendChild(el);
@@ -1686,12 +2567,12 @@ function HTML(runner) {
});
runner.on('fail', function(test, err){
- if ('hook' == test.type || err.uncaught) runner.emit('test end', test);
+ if ('hook' == test.type) runner.emit('test end', test);
});
runner.on('test end', function(test){
// TODO: add to stats
- var percent = stats.tests / total * 100 | 0;
+ var percent = stats.tests / this.total * 100 | 0;
if (progress) progress.update(percent).draw(ctx);
// update stats
@@ -1702,11 +2583,11 @@ function HTML(runner) {
// test
if ('passed' == test.state) {
- var el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span></h2></li>', test.speed, test.title, test.duration);
+ var el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span> <a href="?grep=%e" class="replay">‣</a></h2></li>', test.speed, test.title, test.duration, encodeURIComponent(test.fullTitle()));
} else if (test.pending) {
var el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title);
} else {
- var el = fragment('<li class="test fail"><h2>%e</h2></li>', test.title);
+ var el = fragment('<li class="test fail"><h2>%e <a href="?grep=%e" class="replay">‣</a></h2></li>', test.title, encodeURIComponent(test.fullTitle()));
var str = test.err.stack || test.err.toString();
// FF / Opera do not add the message
@@ -1727,23 +2608,23 @@ function HTML(runner) {
}
// toggle code
- var h2 = el.getElementsByTagName('h2')[0];
-
- on(h2, 'click', function(){
- pre.style.display = 'none' == pre.style.display
- ? 'block'
- : 'none';
- });
-
- // code
// TODO: defer
if (!test.pending) {
- var pre = fragment('<pre><code>%e</code></pre>', clean(test.fn.toString()));
+ var h2 = el.getElementsByTagName('h2')[0];
+
+ on(h2, 'click', function(){
+ pre.style.display = 'none' == pre.style.display
+ ? 'block'
+ : 'none';
+ });
+
+ var pre = fragment('<pre><code>%e</code></pre>', utils.clean(test.fn.toString()));
el.appendChild(pre);
pre.style.display = 'none';
}
- stack[0].appendChild(el);
+ // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
+ if (stack[0]) stack[0].appendChild(el);
});
}
@@ -1752,7 +2633,7 @@ function HTML(runner) {
*/
function error(msg) {
- document.body.appendChild(fragment('<div id="error">%s</div>', msg));
+ document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg));
}
/**
@@ -1774,6 +2655,30 @@ function fragment(html) {
return div.firstChild;
}
+/**
+ * Check for suites that do not have elements
+ * with `classname`, and hide them.
+ */
+
+function hideSuitesWithout(classname) {
+ var suites = document.getElementsByClassName('suite');
+ for (var i = 0; i < suites.length; i++) {
+ var els = suites[i].getElementsByClassName(classname);
+ if (0 == els.length) suites[i].className += ' hidden';
+ }
+}
+
+/**
+ * Unhide .hidden suites.
+ */
+
+function unhide() {
+ var els = document.getElementsByClassName('suite hidden');
+ for (var i = 0; i < els.length; ++i) {
+ els[i].className = els[i].className.replace('suite hidden', 'suite');
+ }
+}
+
/**
* Set `el` text to `str`.
*/
@@ -1798,26 +2703,6 @@ function on(el, event, fn) {
}
}
-/**
- * Strip the function definition from `str`,
- * and re-indent for pre whitespace.
- */
-
-function clean(str) {
- str = str
- .replace(/^function *\(.*\) *{/, '')
- .replace(/\s+\}$/, '');
-
- var spaces = str.match(/^\n?( *)/)[1].length
- , re = new RegExp('^ {' + spaces + '}', 'gm');
-
- str = str
- .replace(re, '')
- .replace(/^\s+/, '');
-
- return str;
-}
-
}); // module: reporters/html.js
require.register("reporters/index.js", function(module, exports, require){
@@ -1831,13 +2716,14 @@ exports.HTML = require('./html');
exports.List = require('./list');
exports.Min = require('./min');
exports.Spec = require('./spec');
+exports.Nyan = require('./nyan');
+exports.XUnit = require('./xunit');
+exports.Markdown = require('./markdown');
exports.Progress = require('./progress');
exports.Landing = require('./landing');
exports.JSONCov = require('./json-cov');
exports.HTMLCov = require('./html-cov');
exports.JSONStream = require('./json-stream');
-exports.XUnit = require('./xunit')
-exports.Teamcity = require('./teamcity')
}); // module: reporters/index.js
@@ -1924,6 +2810,10 @@ function map(cov) {
ret.sloc += data.sloc;
}
+ ret.files.sort(function(a, b) {
+ return a.filename.localeCompare(b.filename);
+ });
+
if (ret.sloc > 0) {
ret.coverage = (ret.hits / ret.sloc) * 100;
}
@@ -2207,14 +3097,14 @@ function Landing(runner) {
}
// render landing strip
- stream.write('\033[4F\n\n');
+ stream.write('\u001b[4F\n\n');
stream.write(runway());
stream.write('\n ');
stream.write(color('runway', Array(col).join('⋅')));
stream.write(plane)
stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
stream.write(runway());
- stream.write('\033[0m');
+ stream.write('\u001b[0m');
});
runner.on('end', function(){
@@ -2228,7 +3118,9 @@ function Landing(runner) {
* Inherit from `Base.prototype`.
*/
-Landing.prototype = new Base;
+function F(){};
+F.prototype = Base.prototype;
+Landing.prototype = new F;
Landing.prototype.constructor = Landing;
}); // module: reporters/landing.js
@@ -2278,7 +3170,7 @@ function List(runner) {
});
runner.on('pass', function(test){
- var fmt = color('checkmark', ' ✓')
+ var fmt = color('checkmark', ' '+Base.symbols.dot)
+ color('pass', ' %s: ')
+ color(test.speed, '%dms');
cursor.CR();
@@ -2297,14 +3189,15 @@ function List(runner) {
* Inherit from `Base.prototype`.
*/
-List.prototype = new Base;
+function F(){};
+F.prototype = Base.prototype;
+List.prototype = new F;
List.prototype.constructor = List;
}); // module: reporters/list.js
require.register("reporters/markdown.js", function(module, exports, require){
-
/**
* Module dependencies.
*/
@@ -2330,7 +3223,6 @@ function Markdown(runner) {
var self = this
, stats = this.stats
- , total = runner.total
, level = 0
, buf = '';
@@ -2375,7 +3267,7 @@ function Markdown(runner) {
runner.on('suite', function(suite){
++level;
var slug = utils.slug(suite.fullTitle());
- buf += '<a name="' + slug + '" />' + '\n';
+ buf += '<a name="' + slug + '"></a>' + '\n';
buf += title(suite.title) + '\n';
});
@@ -2384,9 +3276,9 @@ function Markdown(runner) {
});
runner.on('pass', function(test){
- var code = clean(test.fn.toString());
+ var code = utils.clean(test.fn.toString());
buf += test.title + '.\n';
- buf += '\n```js';
+ buf += '\n```js\n';
buf += code + '\n';
buf += '```\n\n';
});
@@ -2397,27 +3289,10 @@ function Markdown(runner) {
process.stdout.write(buf);
});
}
-
-/**
- * Strip the function definition from `str`,
- * and re-indent for pre whitespace.
- */
-
-function clean(str) {
- str = str
- .replace(/^function *\(.*\) *{/, '')
- .replace(/\s+\}$/, '');
-
- var spaces = str.match(/^\n?( *)/)[1].length
- , re = new RegExp('^ {' + spaces + '}', 'gm');
-
- str = str.replace(re, '');
-
- return str;
-}
}); // module: reporters/markdown.js
require.register("reporters/min.js", function(module, exports, require){
+
/**
* Module dependencies.
*/
@@ -2439,12 +3314,12 @@ exports = module.exports = Min;
function Min(runner) {
Base.call(this, runner);
-
+
runner.on('start', function(){
// clear screen
- process.stdout.write('\033[2J');
+ process.stdout.write('\u001b[2J');
// set cursor position
- process.stdout.write('\033[1;3H');
+ process.stdout.write('\u001b[1;3H');
});
runner.on('end', this.epilogue.bind(this));
@@ -2454,11 +3329,282 @@ function Min(runner) {
* Inherit from `Base.prototype`.
*/
-Min.prototype = new Base;
+function F(){};
+F.prototype = Base.prototype;
+Min.prototype = new F;
Min.prototype.constructor = Min;
+
}); // module: reporters/min.js
+require.register("reporters/nyan.js", function(module, exports, require){
+/**
+ * Module dependencies.
+ */
+
+var Base = require('./base')
+ , color = Base.color;
+
+/**
+ * Expose `Dot`.
+ */
+
+exports = module.exports = NyanCat;
+
+/**
+ * Initialize a new `Dot` matrix test reporter.
+ *
+ * @param {Runner} runner
+ * @api public
+ */
+
+function NyanCat(runner) {
+ Base.call(this, runner);
+ var self = this
+ , stats = this.stats
+ , width = Base.window.width * .75 | 0
+ , rainbowColors = this.rainbowColors = self.generateColors()
+ , colorIndex = this.colorIndex = 0
+ , numerOfLines = this.numberOfLines = 4
+ , trajectories = this.trajectories = [[], [], [], []]
+ , nyanCatWidth = this.nyanCatWidth = 11
+ , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth)
+ , scoreboardWidth = this.scoreboardWidth = 5
+ , tick = this.tick = 0
+ , n = 0;
+
+ runner.on('start', function(){
+ Base.cursor.hide();
+ self.draw();
+ });
+
+ runner.on('pending', function(test){
+ self.draw();
+ });
+
+ runner.on('pass', function(test){
+ self.draw();
+ });
+
+ runner.on('fail', function(test, err){
+ self.draw();
+ });
+
+ runner.on('end', function(){
+ Base.cursor.show();
+ for (var i = 0; i < self.numberOfLines; i++) write('\n');
+ self.epilogue();
+ });
+}
+
+/**
+ * Draw the nyan cat
+ *
+ * @api private
+ */
+
+NyanCat.prototype.draw = function(){
+ this.appendRainbow();
+ this.drawScoreboard();
+ this.drawRainbow();
+ this.drawNyanCat();
+ this.tick = !this.tick;
+};
+
+/**
+ * Draw the "scoreboard" showing the number
+ * of passes, failures and pending tests.
+ *
+ * @api private
+ */
+
+NyanCat.prototype.drawScoreboard = function(){
+ var stats = this.stats;
+ var colors = Base.colors;
+
+ function draw(color, n) {
+ write(' ');
+ write('\u001b[' + color + 'm' + n + '\u001b[0m');
+ write('\n');
+ }
+
+ draw(colors.green, stats.passes);
+ draw(colors.fail, stats.failures);
+ draw(colors.pending, stats.pending);
+ write('\n');
+
+ this.cursorUp(this.numberOfLines);
+};
+
+/**
+ * Append the rainbow.
+ *
+ * @api private
+ */
+
+NyanCat.prototype.appendRainbow = function(){
+ var segment = this.tick ? '_' : '-';
+ var rainbowified = this.rainbowify(segment);
+
+ for (var index = 0; index < this.numberOfLines; index++) {
+ var trajectory = this.trajectories[index];
+ if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift();
+ trajectory.push(rainbowified);
+ }
+};
+
+/**
+ * Draw the rainbow.
+ *
+ * @api private
+ */
+
+NyanCat.prototype.drawRainbow = function(){
+ var self = this;
+
+ this.trajectories.forEach(function(line, index) {
+ write('\u001b[' + self.scoreboardWidth + 'C');
+ write(line.join(''));
+ write('\n');
+ });
+
+ this.cursorUp(this.numberOfLines);
+};
+
+/**
+ * Draw the nyan cat
+ *
+ * @api private
+ */
+
+NyanCat.prototype.drawNyanCat = function() {
+ var self = this;
+ var startWidth = this.scoreboardWidth + this.trajectories[0].length;
+ var color = '\u001b[' + startWidth + 'C';
+ var padding = '';
+
+ write(color);
+ write('_,------,');
+ write('\n');
+
+ write(color);
+ padding = self.tick ? ' ' : ' ';
+ write('_|' + padding + '/\\_/\\ ');
+ write('\n');
+
+ write(color);
+ padding = self.tick ? '_' : '__';
+ var tail = self.tick ? '~' : '^';
+ var face;
+ write(tail + '|' + padding + this.face() + ' ');
+ write('\n');
+
+ write(color);
+ padding = self.tick ? ' ' : ' ';
+ write(padding + '"" "" ');
+ write('\n');
+
+ this.cursorUp(this.numberOfLines);
+};
+
+/**
+ * Draw nyan cat face.
+ *
+ * @return {String}
+ * @api private
+ */
+
+NyanCat.prototype.face = function() {
+ var stats = this.stats;
+ if (stats.failures) {
+ return '( x .x)';
+ } else if (stats.pending) {
+ return '( o .o)';
+ } else if(stats.passes) {
+ return '( ^ .^)';
+ } else {
+ return '( - .-)';
+ }
+}
+
+/**
+ * Move cursor up `n`.
+ *
+ * @param {Number} n
+ * @api private
+ */
+
+NyanCat.prototype.cursorUp = function(n) {
+ write('\u001b[' + n + 'A');
+};
+
+/**
+ * Move cursor down `n`.
+ *
+ * @param {Number} n
+ * @api private
+ */
+
+NyanCat.prototype.cursorDown = function(n) {
+ write('\u001b[' + n + 'B');
+};
+
+/**
+ * Generate rainbow colors.
+ *
+ * @return {Array}
+ * @api private
+ */
+
+NyanCat.prototype.generateColors = function(){
+ var colors = [];
+
+ for (var i = 0; i < (6 * 7); i++) {
+ var pi3 = Math.floor(Math.PI / 3);
+ var n = (i * (1.0 / 6));
+ var r = Math.floor(3 * Math.sin(n) + 3);
+ var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
+ var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
+ colors.push(36 * r + 6 * g + b + 16);
+ }
+
+ return colors;
+};
+
+/**
+ * Apply rainbow to the given `str`.
+ *
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+
+NyanCat.prototype.rainbowify = function(str){
+ var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
+ this.colorIndex += 1;
+ return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
+};
+
+/**
+ * Stdout helper.
+ */
+
+function write(string) {
+ process.stdout.write(string);
+}
+
+/**
+ * Inherit from `Base.prototype`.
+ */
+
+function F(){};
+F.prototype = Base.prototype;
+NyanCat.prototype = new F;
+NyanCat.prototype.constructor = NyanCat;
+
+
+}); // module: reporters/nyan.js
+
require.register("reporters/progress.js", function(module, exports, require){
/**
@@ -2503,7 +3649,7 @@ function Progress(runner, options) {
// default chars
options.open = options.open || '[';
options.complete = options.complete || '▬';
- options.incomplete = options.incomplete || '⋅';
+ options.incomplete = options.incomplete || Base.symbols.dot;
options.close = options.close || ']';
options.verbose = false;
@@ -2522,7 +3668,7 @@ function Progress(runner, options) {
, i = width - n;
cursor.CR();
- process.stdout.write('\033[J');
+ process.stdout.write('\u001b[J');
process.stdout.write(color('progress', ' ' + options.open));
process.stdout.write(Array(n).join(options.complete));
process.stdout.write(Array(i).join(options.incomplete));
@@ -2545,7 +3691,9 @@ function Progress(runner, options) {
* Inherit from `Base.prototype`.
*/
-Progress.prototype = new Base;
+function F(){};
+F.prototype = Base.prototype;
+Progress.prototype = new F;
Progress.prototype.constructor = Progress;
@@ -2612,13 +3760,13 @@ function Spec(runner) {
runner.on('pass', function(test){
if ('fast' == test.speed) {
var fmt = indent()
- + color('checkmark', ' ✓')
+ + color('checkmark', ' ' + Base.symbols.ok)
+ color('pass', ' %s ');
cursor.CR();
console.log(fmt, test.title);
} else {
var fmt = indent()
- + color('checkmark', ' ✓')
+ + color('checkmark', ' ' + Base.symbols.ok)
+ color('pass', ' %s ')
+ color(test.speed, '(%dms)');
cursor.CR();
@@ -2634,151 +3782,94 @@ function Spec(runner) {
runner.on('end', self.epilogue.bind(self));
}
-/**
- * Inherit from `Base.prototype`.
- */
-
-Spec.prototype = new Base;
-Spec.prototype.constructor = Spec;
-
-
-}); // module: reporters/spec.js
-
-require.register("reporters/tap.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , cursor = Base.cursor
- , color = Base.color;
-
-/**
- * Expose `TAP`.
- */
-
-exports = module.exports = TAP;
-
-/**
- * Initialize a new `TAP` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function TAP(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , total = runner.total
- , n = 1;
-
- runner.on('start', function(){
- console.log('%d..%d', 1, total);
- });
-
- runner.on('test end', function(){
- ++n;
- });
-
- runner.on('pending', function(test){
- console.log('ok %d %s # SKIP -', n, title(test));
- });
-
- runner.on('pass', function(test){
- console.log('ok %d %s', n, title(test));
- });
-
- runner.on('fail', function(test, err){
- console.log('not ok %d %s', n, title(test));
- console.log(err.stack.replace(/^/gm, ' '));
- });
-}
-
-/**
- * Return a TAP-safe title of `test`
- *
- * @param {Object} test
- * @return {String}
- * @api private
+/**
+ * Inherit from `Base.prototype`.
*/
-function title(test) {
- return test.fullTitle().replace(/#/g, '');
-}
+function F(){};
+F.prototype = Base.prototype;
+Spec.prototype = new F;
+Spec.prototype.constructor = Spec;
-}); // module: reporters/tap.js
-require.register("reporters/teamcity.js", function(module, exports, require){
+}); // module: reporters/spec.js
+
+require.register("reporters/tap.js", function(module, exports, require){
/**
* Module dependencies.
*/
-var Base = require('./base');
+var Base = require('./base')
+ , cursor = Base.cursor
+ , color = Base.color;
/**
- * Expose `Teamcity`.
+ * Expose `TAP`.
*/
-exports = module.exports = Teamcity;
+exports = module.exports = TAP;
/**
- * Initialize a new `Teamcity` reporter.
+ * Initialize a new `TAP` reporter.
*
* @param {Runner} runner
* @api public
*/
-function Teamcity(runner) {
+function TAP(runner) {
Base.call(this, runner);
- var stats = this.stats;
- runner.on('start', function() {
- console.log("##teamcity[testSuiteStarted name='mocha.suite']");
+ var self = this
+ , stats = this.stats
+ , n = 1
+ , passes = 0
+ , failures = 0;
+
+ runner.on('start', function(){
+ var total = runner.grepTotal(runner.suite);
+ console.log('%d..%d', 1, total);
});
- runner.on('test', function(test) {
- console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']");
+ runner.on('test end', function(){
+ ++n;
});
- runner.on('fail', function(test, err) {
- console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']");
+ runner.on('pending', function(test){
+ console.log('ok %d %s # SKIP -', n, title(test));
});
- runner.on('pending', function(test) {
- console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']");
+ runner.on('pass', function(test){
+ passes++;
+ console.log('ok %d %s', n, title(test));
});
- runner.on('test end', function(test) {
- console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']");
+ runner.on('fail', function(test, err){
+ failures++;
+ console.log('not ok %d %s', n, title(test));
+ if (err.stack) console.log(err.stack.replace(/^/gm, ' '));
});
- runner.on('end', function() {
- console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']");
+ runner.on('end', function(){
+ console.log('# tests ' + (passes + failures));
+ console.log('# pass ' + passes);
+ console.log('# fail ' + failures);
});
}
/**
- * Escape the given `str`.
+ * Return a TAP-safe title of `test`
+ *
+ * @param {Object} test
+ * @return {String}
+ * @api private
*/
-function escape(str) {
- return str
- .replace(/\|/g, "||")
- .replace(/\n/g, "|n")
- .replace(/\r/g, "|r")
- .replace(/\[/g, "|[")
- .replace(/\]/g, "|]")
- .replace(/\u0085/g, "|x")
- .replace(/\u2028/g, "|l")
- .replace(/\u2029/g, "|p")
- .replace(/'/g, "|'");
+function title(test) {
+ return test.fullTitle().replace(/#/g, '');
}
-}); // module: reporters/teamcity.js
+}); // module: reporters/tap.js
require.register("reporters/xunit.js", function(module, exports, require){
@@ -2819,7 +3910,11 @@ function XUnit(runner) {
, tests = []
, self = this;
- runner.on('test end', function(test){
+ runner.on('pass', function(test){
+ tests.push(test);
+ });
+
+ runner.on('fail', function(test){
tests.push(test);
});
@@ -2829,13 +3924,13 @@ function XUnit(runner) {
, tests: stats.tests
, failures: stats.failures
, errors: stats.failures
- , skip: stats.tests - stats.failures - stats.passes
+ , skipped: stats.tests - stats.failures - stats.passes
, timestamp: (new Date).toUTCString()
- , time: stats.duration / 1000
+ , time: (stats.duration / 1000) || 0
}, false));
tests.forEach(test);
- console.log('</testsuite>');
+ console.log('</testsuite>');
});
}
@@ -2843,7 +3938,9 @@ function XUnit(runner) {
* Inherit from `Base.prototype`.
*/
-XUnit.prototype = new Base;
+function F(){};
+F.prototype = Base.prototype;
+XUnit.prototype = new F;
XUnit.prototype.constructor = XUnit;
@@ -2904,7 +4001,8 @@ require.register("runnable.js", function(module, exports, require){
*/
var EventEmitter = require('browser/events').EventEmitter
- , debug = require('browser/debug')('runnable');
+ , debug = require('browser/debug')('mocha:runnable')
+ , milliseconds = require('./ms');
/**
* Save timer references to avoid Sinon interfering (see GH-237).
@@ -2916,6 +4014,12 @@ var Date = global.Date
, clearTimeout = global.clearTimeout
, clearInterval = global.clearInterval;
+/**
+ * Object#toString().
+ */
+
+var toString = Object.prototype.toString;
+
/**
* Expose `Runnable`.
*/
@@ -2936,6 +4040,7 @@ function Runnable(title, fn) {
this.async = fn && fn.length;
this.sync = ! this.async;
this._timeout = 2000;
+ this._slow = 75;
this.timedOut = false;
}
@@ -2943,26 +4048,45 @@ function Runnable(title, fn) {
* Inherit from `EventEmitter.prototype`.
*/
-Runnable.prototype = new EventEmitter;
+function F(){};
+F.prototype = EventEmitter.prototype;
+Runnable.prototype = new F;
Runnable.prototype.constructor = Runnable;
/**
* Set & get timeout `ms`.
*
- * @param {Number} ms
+ * @param {Number|String} ms
* @return {Runnable|Number} ms or self
* @api private
*/
Runnable.prototype.timeout = function(ms){
if (0 == arguments.length) return this._timeout;
+ if ('string' == typeof ms) ms = milliseconds(ms);
debug('timeout %d', ms);
this._timeout = ms;
if (this.timer) this.resetTimeout();
return this;
};
+/**
+ * Set & get slow `ms`.
+ *
+ * @param {Number|String} ms
+ * @return {Runnable|Number} ms or self
+ * @api private
+ */
+
+Runnable.prototype.slow = function(ms){
+ if (0 === arguments.length) return this._slow;
+ if ('string' == typeof ms) ms = milliseconds(ms);
+ debug('timeout %d', ms);
+ this._slow = ms;
+ return this;
+};
+
/**
* Return the full title generated by recursively
* concatenating the parent's full title.
@@ -2985,6 +4109,22 @@ Runnable.prototype.clearTimeout = function(){
clearTimeout(this.timer);
};
+/**
+ * Inspect the runnable void of private properties.
+ *
+ * @return {String}
+ * @api private
+ */
+
+Runnable.prototype.inspect = function(){
+ return JSON.stringify(this, function(key, val){
+ if ('_' == key[0]) return;
+ if ('parent' == key) return '#<Suite>';
+ if ('ctx' == key) return '#<Context>';
+ return val;
+ }, 2);
+};
+
/**
* Reset the timeout.
*
@@ -2992,16 +4132,14 @@ Runnable.prototype.clearTimeout = function(){
*/
Runnable.prototype.resetTimeout = function(){
- var self = this
- , ms = this.timeout();
+ var self = this;
+ var ms = this.timeout() || 1e9;
this.clearTimeout();
- if (ms) {
- this.timer = setTimeout(function(){
- self.callback(new Error('timeout of ' + ms + 'ms exceeded'));
- self.timedOut = true;
- }, ms);
- }
+ this.timer = setTimeout(function(){
+ self.callback(new Error('timeout of ' + ms + 'ms exceeded'));
+ self.timedOut = true;
+ }, ms);
};
/**
@@ -3032,16 +4170,16 @@ Runnable.prototype.run = function(fn){
}
// called multiple times
- function multiple() {
+ function multiple(err) {
if (emitted) return;
emitted = true;
- self.emit('error', new Error('done() called multiple times'));
+ self.emit('error', err || new Error('done() called multiple times'));
}
// finished
function done(err) {
if (self.timedOut) return;
- if (finished) return multiple();
+ if (finished) return multiple(err);
self.clearTimeout();
self.duration = new Date - start;
finished = true;
@@ -3055,7 +4193,7 @@ Runnable.prototype.run = function(fn){
if (this.async) {
try {
this.fn.call(ctx, function(err){
- if (err instanceof Error) return done(err);
+ if (err instanceof Error || toString.call(err) === "[object Error]") return done(err);
if (null != err) return done(new Error('done() invoked with non-Error: ' + err));
done();
});
@@ -3064,7 +4202,11 @@ Runnable.prototype.run = function(fn){
}
return;
}
-
+
+ if (this.asyncOnly) {
+ return done(new Error('--async-only option in use without declaring `done()`'));
+ }
+
// sync
try {
if (!this.pending) this.fn.call(ctx);
@@ -3078,16 +4220,29 @@ Runnable.prototype.run = function(fn){
}); // module: runnable.js
require.register("runner.js", function(module, exports, require){
-
/**
* Module dependencies.
*/
var EventEmitter = require('browser/events').EventEmitter
- , debug = require('browser/debug')('runner')
+ , debug = require('browser/debug')('mocha:runner')
, Test = require('./test')
, utils = require('./utils')
- , noop = function(){};
+ , filter = utils.filter
+ , keys = utils.keys;
+
+/**
+ * Non-enumerable globals.
+ */
+
+var globals = [
+ 'setTimeout',
+ 'clearTimeout',
+ 'setInterval',
+ 'clearInterval',
+ 'XMLHttpRequest',
+ 'Date'
+];
/**
* Expose `Runner`.
@@ -3110,6 +4265,7 @@ module.exports = Runner;
* - `hook end` (hook) hook complete
* - `pass` (test) test passed
* - `fail` (test, err) test failed
+ * - `pending` (test) test pending
*
* @api public
*/
@@ -3123,14 +4279,25 @@ function Runner(suite) {
this.on('test end', function(test){ self.checkGlobals(test); });
this.on('hook end', function(hook){ self.checkGlobals(hook); });
this.grep(/.*/);
- this.globals(utils.keys(global).concat(['errno']));
+ this.globals(this.globalProps().concat(['errno']));
}
+/**
+ * Wrapper for setImmediate, process.nextTick, or browser polyfill.
+ *
+ * @param {Function} fn
+ * @api private
+ */
+
+Runner.immediately = global.setImmediate || process.nextTick;
+
/**
* Inherit from `EventEmitter.prototype`.
*/
-Runner.prototype = new EventEmitter;
+function F(){};
+F.prototype = EventEmitter.prototype;
+Runner.prototype = new F;
Runner.prototype.constructor = Runner;
@@ -3139,13 +4306,15 @@ Runner.prototype.constructor = Runner;
* with number of tests matched.
*
* @param {RegExp} re
+ * @param {Boolean} invert
* @return {Runner} for chaining
* @api public
*/
-Runner.prototype.grep = function(re){
+Runner.prototype.grep = function(re, invert){
debug('grep %s', re);
this._grep = re;
+ this._invert = invert;
this.total = this.grepTotal(this.suite);
return this;
};
@@ -3164,12 +4333,33 @@ Runner.prototype.grepTotal = function(suite) {
var total = 0;
suite.eachTest(function(test){
- if (self._grep.test(test.fullTitle())) total++;
+ var match = self._grep.test(test.fullTitle());
+ if (self._invert) match = !match;
+ if (match) total++;
});
return total;
};
+/**
+ * Return a list of global properties.
+ *
+ * @return {Array}
+ * @api private
+ */
+
+Runner.prototype.globalProps = function() {
+ var props = utils.keys(global);
+
+ // non-enumerables
+ for (var i = 0; i < globals.length; ++i) {
+ if (~utils.indexOf(props, globals[i])) continue;
+ props.push(globals[i]);
+ }
+
+ return props;
+};
+
/**
* Allow the given `arr` of globals.
*
@@ -3195,13 +4385,19 @@ Runner.prototype.globals = function(arr){
Runner.prototype.checkGlobals = function(test){
if (this.ignoreLeaks) return;
- var leaks = utils.filter(utils.keys(global), function(key){
- var matched = utils.filter(this._globals, function(allowed){
- return allowed == key || key.lastIndexOf(allowed.split('*')[0], 0) == 0;
- });
- return matched.length == 0 && (!global.navigator || 'onerror' !== key);
- }, this);
+ var ok = this._globals;
+ var globals = this.globalProps();
+ var isNode = process.kill;
+ var leaks;
+
+ // check length - 2 ('errno' and 'location' globals)
+ if (isNode && 1 == ok.length - globals.length) return;
+ else if (2 == ok.length - globals.length) return;
+ if(this.prevGlobalsLength == globals.length) return;
+ this.prevGlobalsLength = globals.length;
+
+ leaks = filterLeaks(ok, globals);
this._globals = this._globals.concat(leaks);
if (leaks.length > 1) {
@@ -3222,9 +4418,11 @@ Runner.prototype.checkGlobals = function(test){
Runner.prototype.fail = function(test, err){
++this.failures;
test.state = 'failed';
+
if ('string' == typeof err) {
err = new Error('the string "' + err + '" was thrown, throw an Error :)');
}
+
this.emit('fail', test, err);
};
@@ -3257,15 +4455,17 @@ Runner.prototype.failHook = function(hook, err){
Runner.prototype.hook = function(name, fn){
var suite = this.suite
, hooks = suite['_' + name]
- , ms = suite._timeout
, self = this
, timer;
function next(i) {
var hook = hooks[i];
if (!hook) return fn();
+ if (self.failures && suite.bail()) return fn();
self.currentRunnable = hook;
+ hook.ctx.currentTest = self.test;
+
self.emit('hook', hook);
hook.on('error', function(err){
@@ -3274,13 +4474,16 @@ Runner.prototype.hook = function(name, fn){
hook.run(function(err){
hook.removeAllListeners('error');
+ var testError = hook.error();
+ if (testError) self.fail(self.test, testError);
if (err) return self.failHook(hook, err);
self.emit('hook end', hook);
+ delete hook.ctx.currentTest;
next(++i);
});
}
- process.nextTick(function(){
+ Runner.immediately(function(){
next(0);
});
};
@@ -3372,6 +4575,8 @@ Runner.prototype.runTest = function(fn){
var test = this.test
, self = this;
+ if (this.asyncOnly) test.asyncOnly = true;
+
try {
test.on('error', function(err){
self.fail(test, err);
@@ -3393,7 +4598,7 @@ Runner.prototype.runTest = function(fn){
Runner.prototype.runTests = function(suite, fn){
var self = this
- , tests = suite.tests
+ , tests = suite.tests.slice()
, test;
function next(err) {
@@ -3407,7 +4612,9 @@ Runner.prototype.runTests = function(suite, fn){
if (!test) return fn();
// grep
- if (!self._grep.test(test.fullTitle())) return next();
+ var match = self._grep.test(test.fullTitle());
+ if (self._invert) match = !match;
+ if (!match) return next();
// pending
if (test.pending) {
@@ -3488,9 +4695,9 @@ Runner.prototype.runSuite = function(suite, fn){
*/
Runner.prototype.uncaught = function(err){
- debug('uncaught exception');
+ debug('uncaught exception %s', err.message);
var runnable = this.currentRunnable;
- if ('failed' == runnable.state) return;
+ if (!runnable || 'failed' == runnable.state) return;
runnable.clearTimeout();
err.uncaught = true;
this.fail(runnable, err);
@@ -3519,12 +4726,16 @@ Runner.prototype.run = function(fn){
var self = this
, fn = fn || function(){};
+ function uncaught(err){
+ self.uncaught(err);
+ }
+
debug('start');
// callback
this.on('end', function(){
debug('end');
- process.removeListener('uncaughtException', this.uncaught);
+ process.removeListener('uncaughtException', uncaught);
fn(self.failures);
});
@@ -3536,13 +4747,45 @@ Runner.prototype.run = function(fn){
});
// uncaught exception
- process.on('uncaughtException', function(err){
- self.uncaught(err);
- });
+ process.on('uncaughtException', uncaught);
return this;
};
+/**
+ * Filter leaks with the given globals flagged as `ok`.
+ *
+ * @param {Array} ok
+ * @param {Array} globals
+ * @return {Array}
+ * @api private
+ */
+
+function filterLeaks(ok, globals) {
+ return filter(globals, function(key){
+ // Firefox and Chrome exposes iframes as index inside the window object
+ if (/^d+/.test(key)) return false;
+
+ // in firefox
+ // if runner runs in an iframe, this iframe's window.getInterface method not init at first
+ // it is assigned in some seconds
+ if (global.navigator && /^getInterface/.test(key)) return false;
+
+ // an iframe could be approached by window[iframeIndex]
+ // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak
+ if (global.navigator && /^\d+/.test(key)) return false;
+
+ // Opera and IE expose global variables for HTML element IDs (issue #243)
+ if (/^mocha-/.test(key)) return false;
+
+ var matched = filter(ok, function(ok){
+ if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]);
+ return key == ok;
+ });
+ return matched.length == 0 && (!global.navigator || 'onerror' !== key);
+ });
+}
+
}); // module: runner.js
require.register("suite.js", function(module, exports, require){
@@ -3552,7 +4795,8 @@ require.register("suite.js", function(module, exports, require){
*/
var EventEmitter = require('browser/events').EventEmitter
- , debug = require('browser/debug')('suite')
+ , debug = require('browser/debug')('mocha:suite')
+ , milliseconds = require('./ms')
, utils = require('./utils')
, Hook = require('./hook');
@@ -3578,6 +4822,7 @@ exports = module.exports = Suite;
exports.create = function(parent, title){
var suite = new Suite(title, parent.ctx);
suite.parent = parent;
+ if (parent.pending) suite.pending = true;
title = suite.fullTitle();
parent.addSuite(suite);
return suite;
@@ -3597,12 +4842,14 @@ function Suite(title, ctx) {
this.ctx = ctx;
this.suites = [];
this.tests = [];
+ this.pending = false;
this._beforeEach = [];
this._beforeAll = [];
this._afterEach = [];
this._afterAll = [];
this.root = !title;
this._timeout = 2000;
+ this._slow = 75;
this._bail = false;
}
@@ -3610,7 +4857,9 @@ function Suite(title, ctx) {
* Inherit from `EventEmitter.prototype`.
*/
-Suite.prototype = new EventEmitter;
+function F(){};
+F.prototype = EventEmitter.prototype;
+Suite.prototype = new F;
Suite.prototype.constructor = Suite;
@@ -3626,6 +4875,7 @@ Suite.prototype.clone = function(){
debug('clone');
suite.ctx = this.ctx;
suite.timeout(this.timeout());
+ suite.slow(this.slow());
suite.bail(this.bail());
return suite;
};
@@ -3640,12 +4890,28 @@ Suite.prototype.clone = function(){
Suite.prototype.timeout = function(ms){
if (0 == arguments.length) return this._timeout;
- if (String(ms).match(/s$/)) ms = parseFloat(ms) * 1000;
+ if ('string' == typeof ms) ms = milliseconds(ms);
debug('timeout %d', ms);
this._timeout = parseInt(ms, 10);
return this;
};
+/**
+ * Set slow `ms` or short-hand such as "2s".
+ *
+ * @param {Number|String} ms
+ * @return {Suite|Number} for chaining
+ * @api private
+ */
+
+Suite.prototype.slow = function(ms){
+ if (0 === arguments.length) return this._slow;
+ if ('string' == typeof ms) ms = milliseconds(ms);
+ debug('slow %d', ms);
+ this._slow = ms;
+ return this;
+};
+
/**
* Sets whether to bail after first error.
*
@@ -3670,9 +4936,11 @@ Suite.prototype.bail = function(bail){
*/
Suite.prototype.beforeAll = function(fn){
+ if (this.pending) return this;
var hook = new Hook('"before all" hook', fn);
hook.parent = this;
hook.timeout(this.timeout());
+ hook.slow(this.slow());
hook.ctx = this.ctx;
this._beforeAll.push(hook);
this.emit('beforeAll', hook);
@@ -3688,9 +4956,11 @@ Suite.prototype.beforeAll = function(fn){
*/
Suite.prototype.afterAll = function(fn){
+ if (this.pending) return this;
var hook = new Hook('"after all" hook', fn);
hook.parent = this;
hook.timeout(this.timeout());
+ hook.slow(this.slow());
hook.ctx = this.ctx;
this._afterAll.push(hook);
this.emit('afterAll', hook);
@@ -3706,9 +4976,11 @@ Suite.prototype.afterAll = function(fn){
*/
Suite.prototype.beforeEach = function(fn){
+ if (this.pending) return this;
var hook = new Hook('"before each" hook', fn);
hook.parent = this;
hook.timeout(this.timeout());
+ hook.slow(this.slow());
hook.ctx = this.ctx;
this._beforeEach.push(hook);
this.emit('beforeEach', hook);
@@ -3724,9 +4996,11 @@ Suite.prototype.beforeEach = function(fn){
*/
Suite.prototype.afterEach = function(fn){
+ if (this.pending) return this;
var hook = new Hook('"after each" hook', fn);
hook.parent = this;
hook.timeout(this.timeout());
+ hook.slow(this.slow());
hook.ctx = this.ctx;
this._afterEach.push(hook);
this.emit('afterEach', hook);
@@ -3744,6 +5018,7 @@ Suite.prototype.afterEach = function(fn){
Suite.prototype.addSuite = function(suite){
suite.parent = this;
suite.timeout(this.timeout());
+ suite.slow(this.slow());
suite.bail(this.bail());
this.suites.push(suite);
this.emit('suite', suite);
@@ -3761,6 +5036,7 @@ Suite.prototype.addSuite = function(suite){
Suite.prototype.addTest = function(test){
test.parent = this;
test.timeout(this.timeout());
+ test.slow(this.slow());
test.ctx = this.ctx;
this.tests.push(test);
this.emit('test', test);
@@ -3848,30 +5124,15 @@ function Test(title, fn) {
* Inherit from `Runnable.prototype`.
*/
-Test.prototype = new Runnable;
+function F(){};
+F.prototype = Runnable.prototype;
+Test.prototype = new F;
Test.prototype.constructor = Test;
-/**
- * Inspect the context void of private properties.
- *
- * @return {String}
- * @api private
- */
-
-Test.prototype.inspect = function(){
- return JSON.stringify(this, function(key, val){
- return '_' == key[0]
- ? undefined
- : 'parent' == key
- ? '#<Suite>'
- : val;
- }, 2);
-};
}); // module: test.js
require.register("utils.js", function(module, exports, require){
-
/**
* Module dependencies.
*/
@@ -3879,7 +5140,7 @@ require.register("utils.js", function(module, exports, require){
var fs = require('browser/fs')
, path = require('browser/path')
, join = path.join
- , debug = require('browser/debug')('watch');
+ , debug = require('browser/debug')('mocha:watch');
/**
* Ignored directories.
@@ -3895,7 +5156,7 @@ var ignore = ['node_modules', '.git'];
* @api private
*/
-exports.escape = function(html) {
+exports.escape = function(html){
return String(html)
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
@@ -3912,7 +5173,7 @@ exports.escape = function(html) {
* @api private
*/
-exports.forEach = function(arr, fn, scope) {
+exports.forEach = function(arr, fn, scope){
for (var i = 0, l = arr.length; i < l; i++)
fn.call(scope, arr[i], i);
};
@@ -3926,7 +5187,7 @@ exports.forEach = function(arr, fn, scope) {
* @api private
*/
-exports.indexOf = function (arr, obj, start) {
+exports.indexOf = function(arr, obj, start){
for (var i = start || 0, l = arr.length; i < l; i++) {
if (arr[i] === obj)
return i;
@@ -3936,19 +5197,18 @@ exports.indexOf = function (arr, obj, start) {
/**
* Array#reduce (<=IE8)
- *
+ *
* @param {Array} array
* @param {Function} fn
* @param {Object} initial value
- * @param {Object} scope
* @api private
*/
-exports.reduce = function(arr, fn, val, scope) {
+exports.reduce = function(arr, fn, val){
var rval = val;
for (var i = 0, l = arr.length; i < l; i++) {
- rval = fn.call(scope, rval, arr[i], i, arr);
+ rval = fn(rval, arr[i], i, arr);
}
return rval;
@@ -3959,17 +5219,15 @@ exports.reduce = function(arr, fn, val, scope) {
*
* @param {Array} array
* @param {Function} fn
- * @param {Object} scope
* @api private
*/
-exports.filter = function(arr, fn, scope) {
+exports.filter = function(arr, fn){
var ret = [];
for (var i = 0, l = arr.length; i < l; i++) {
var val = arr[i];
- if (fn.call(scope, val, i, arr))
- ret.push(val);
+ if (fn(val, i, arr)) ret.push(val);
}
return ret;
@@ -4039,7 +5297,7 @@ exports.files = function(dir, ret){
path = join(dir, path);
if (fs.statSync(path).isDirectory()) {
exports.files(path, ret);
- } else if (path.match(/\.(js|coffee)$/)) {
+ } else if (path.match(/\.(js|coffee|litcoffee|coffee.md)$/)) {
ret.push(path);
}
});
@@ -4062,6 +5320,24 @@ exports.slug = function(str){
.replace(/[^-\w]/g, '');
};
+/**
+ * Strip the function definition from `str`,
+ * and re-indent for pre whitespace.
+ */
+
+exports.clean = function(str) {
+ str = str
+ .replace(/^function *\(.*\) *{/, '')
+ .replace(/\s+\}$/, '');
+
+ var whitespace = str.match(/^\n?(\s*)/)[1]
+ , re = new RegExp('^' + whitespace, 'gm');
+
+ str = str.replace(re, '');
+
+ return exports.trim(str);
+};
+
/**
* Escape regular expression characters in `str`.
*
@@ -4073,48 +5349,98 @@ exports.slug = function(str){
exports.escapeRegexp = function(str){
return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
};
-}); // module: utils.js
+
/**
- * Node shims.
+ * Trim the given `str`.
*
- * These are meant only to allow
- * mocha.js to run untouched, not
- * to allow running node code in
- * the browser.
+ * @param {String} str
+ * @return {String}
+ * @api private
*/
-process = {};
-process.exit = function(status){};
-process.stdout = {};
-global = window;
+exports.trim = function(str){
+ return str.replace(/^\s+|\s+$/g, '');
+};
/**
- * next tick implementation.
+ * Parse the given `qs`.
+ *
+ * @param {String} qs
+ * @return {Object}
+ * @api private
*/
-process.nextTick = (function(){
- // postMessage behaves badly on IE8
- if (window.ActiveXObject || !window.postMessage) {
- return function(fn){ fn() };
- }
+exports.parseQuery = function(qs){
+ return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){
+ var i = pair.indexOf('=')
+ , key = pair.slice(0, i)
+ , val = pair.slice(++i);
- // based on setZeroTimeout by David Baron
- // - http://dbaron.org/log/20100309-faster-timeouts
- var timeouts = []
- , name = 'mocha-zero-timeout'
+ obj[key] = decodeURIComponent(val);
+ return obj;
+ }, {});
+};
- window.addEventListener('message', function(e){
- if (e.source == window && e.data == name) {
- if (e.stopPropagation) e.stopPropagation();
- if (timeouts.length) timeouts.shift()();
- }
- }, true);
+/**
+ * Highlight the given string of `js`.
+ *
+ * @param {String} js
+ * @return {String}
+ * @api private
+ */
+
+function highlight(js) {
+ return js
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
+ .replace(/('.*?')/gm, '<span class="string">$1</span>')
+ .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
+ .replace(/(\d+)/gm, '<span class="number">$1</span>')
+ .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
+ .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
+}
+
+/**
+ * Highlight the contents of tag `name`.
+ *
+ * @param {String} name
+ * @api private
+ */
- return function(fn){
- timeouts.push(fn);
- window.postMessage(name, '*');
+exports.highlightTags = function(name) {
+ var code = document.getElementsByTagName(name);
+ for (var i = 0, len = code.length; i < len; ++i) {
+ code[i].innerHTML = highlight(code[i].innerHTML);
}
-})();
+};
+
+}); // module: utils.js
+// The global object is "self" in Web Workers.
+global = (function() { return this; })();
+
+/**
+ * Save timer references to avoid Sinon interfering (see GH-237).
+ */
+
+var Date = global.Date;
+var setTimeout = global.setTimeout;
+var setInterval = global.setInterval;
+var clearTimeout = global.clearTimeout;
+var clearInterval = global.clearInterval;
+
+/**
+ * Node shims.
+ *
+ * These are meant only to allow
+ * mocha.js to run untouched, not
+ * to allow running node code in
+ * the browser.
+ */
+
+var process = {};
+process.exit = function(status){};
+process.stdout = {};
/**
* Remove uncaughtException listener.
@@ -4122,7 +5448,7 @@ process.nextTick = (function(){
process.removeListener = function(e){
if ('uncaughtException' == e) {
- window.onerror = null;
+ global.onerror = function() {};
}
};
@@ -4132,7 +5458,9 @@ process.removeListener = function(e){
process.on = function(e, fn){
if ('uncaughtException' == e) {
- window.onerror = fn;
+ global.onerror = function(err, url, line){
+ fn(new Error(err + ' (' + url + ':' + line + ')'));
+ };
}
};
@@ -4140,87 +5468,80 @@ process.on = function(e, fn){
* Expose mocha.
*/
-window.mocha = require('mocha');
+var Mocha = global.Mocha = require('mocha'),
+ mocha = global.mocha = new Mocha({ reporter: 'html' });
-// boot
-;(function(){
- var suite = new mocha.Suite('', new mocha.Context)
- , utils = mocha.utils
- , options = {}
-
- /**
- * Highlight the given string of `js`.
- */
-
- function highlight(js) {
- return js
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
- .replace(/('.*?')/gm, '<span class="string">$1</span>')
- .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
- .replace(/(\d+)/gm, '<span class="number">$1</span>')
- .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
- .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
+var immediateQueue = []
+ , immediateTimeout;
+
+function timeslice() {
+ var immediateStart = new Date().getTime();
+ while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) {
+ immediateQueue.shift()();
+ }
+ if (immediateQueue.length) {
+ immediateTimeout = setTimeout(timeslice, 0);
+ } else {
+ immediateTimeout = null;
}
+}
- /**
- * Highlight code contents.
- */
+/**
+ * High-performance override of Runner.immediately.
+ */
- function highlightCode() {
- var code = document.getElementsByTagName('code');
- for (var i = 0, len = code.length; i < len; ++i) {
- code[i].innerHTML = highlight(code[i].innerHTML);
- }
+Mocha.Runner.immediately = function(callback) {
+ immediateQueue.push(callback);
+ if (!immediateTimeout) {
+ immediateTimeout = setTimeout(timeslice, 0);
}
+};
- /**
- * Parse the given `qs`.
- */
+/**
+ * Override ui to ensure that the ui functions are initialized.
+ * Normally this would happen in Mocha.prototype.loadFiles.
+ */
- function parse(qs) {
- return utils.reduce(qs.replace('?', '').split('&'), function(obj, pair){
- var i = pair.indexOf('=')
- , key = pair.slice(0, i)
- , val = pair.slice(++i);
+mocha.ui = function(ui){
+ Mocha.prototype.ui.call(this, ui);
+ this.suite.emit('pre-require', global, null, this);
+ return this;
+};
- obj[key] = decodeURIComponent(val);
- return obj;
- }, {});
- }
+/**
+ * Setup mocha with the given setting options.
+ */
- /**
- * Setup mocha with the given setting options.
- */
+mocha.setup = function(opts){
+ if ('string' == typeof opts) opts = { ui: opts };
+ for (var opt in opts) this[opt](opts[opt]);
+ return this;
+};
- mocha.setup = function(opts){
- if ('string' === typeof opts) options.ui = opts;
- else options = opts;
+/**
+ * Run mocha, returning the Runner.
+ */
- ui = mocha.interfaces[options.ui];
- if (!ui) throw new Error('invalid mocha interface "' + ui + '"');
- if (options.timeout) suite.timeout(options.timeout);
- ui(suite);
- suite.emit('pre-require', window);
- };
+mocha.run = function(fn){
+ var options = mocha.options;
+ mocha.globals('location');
- /**
- * Run mocha, returning the Runner.
- */
-
- mocha.run = function(fn){
- suite.emit('run');
- var runner = new mocha.Runner(suite);
- var Reporter = options.reporter || mocha.reporters.HTML;
- var reporter = new Reporter(runner);
- var query = parse(window.location.search || "");
- if (query.grep) runner.grep(new RegExp(query.grep));
- if (options.ignoreLeaks) runner.ignoreLeaks = true;
- if (options.globals) runner.globals(options.globals);
- runner.globals(['location']);
- runner.on('end', highlightCode);
- return runner.run(fn);
- };
-})();
+ var query = Mocha.utils.parseQuery(global.location.search || '');
+ if (query.grep) mocha.grep(query.grep);
+ if (query.invert) mocha.invert();
+
+ return Mocha.prototype.run.call(mocha, function(){
+ // The DOM Document is not available in Web Workers.
+ if (global.document) {
+ Mocha.utils.highlightTags('code');
+ }
+ if (fn) fn();
+ });
+};
+
+/**
+ * Expose the process shim.
+ */
+
+Mocha.process = process;
})();
\ No newline at end of file