6 var path = require.resolve(p)
7 , mod = require.modules[path];
8 if (!mod) throw new Error('failed to require "' + p + '"');
11 mod.call(mod.exports, mod, mod.exports, require.relative(path));
18 require.resolve = function (path){
21 , index = path + '/index.js';
22 return require.modules[reg] && reg
23 || require.modules[index] && index
27 require.register = function (path, fn){
28 require.modules[path] = fn;
31 require.relative = function (parent) {
33 if ('.' != p.charAt(0)) return require(p);
35 var path = parent.split('/')
36 , segs = p.split('/');
39 for (var i = 0; i < segs.length; i++) {
41 if ('..' == seg) path.pop();
42 else if ('.' != seg) path.push(seg);
45 return require(path.join('/'));
50 require.register("browser/debug.js", function(module, exports, require){
52 module.exports = function(type){
57 }); // module: browser/debug.js
59 require.register("browser/diff.js", function(module, exports, require){
60 /* See LICENSE file for terms of use */
63 * Text diff implementation.
65 * This library supports the following APIS:
66 * JsDiff.diffChars: Character by character diff
67 * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
68 * JsDiff.diffLines: Line based diff
70 * JsDiff.diffCss: Diff targeted at CSS content
72 * These methods are based on the implementation proposed in
73 * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
74 * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
76 var JsDiff = (function() {
77 /*jshint maxparams: 5*/
78 function clonePath(path) {
79 return { newPos: path.newPos, components: path.components.slice(0) };
81 function removeEmpty(array) {
83 for (var i = 0; i < array.length; i++) {
90 function escapeHTML(s) {
92 n = n.replace(/&/g, '&');
93 n = n.replace(/</g, '<');
94 n = n.replace(/>/g, '>');
95 n = n.replace(/"/g, '"');
100 var Diff = function(ignoreWhitespace) {
101 this.ignoreWhitespace = ignoreWhitespace;
104 diff: function(oldString, newString) {
105 // Handle the identity case (this is due to unrolling editLength == 0
106 if (newString === oldString) {
107 return [{ value: newString }];
110 return [{ value: oldString, removed: true }];
113 return [{ value: newString, added: true }];
116 newString = this.tokenize(newString);
117 oldString = this.tokenize(oldString);
119 var newLen = newString.length, oldLen = oldString.length;
120 var maxEditLength = newLen + oldLen;
121 var bestPath = [{ newPos: -1, components: [] }];
123 // Seed editLength = 0
124 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
125 if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
126 return bestPath[0].components;
129 for (var editLength = 1; editLength <= maxEditLength; editLength++) {
130 for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
132 var addPath = bestPath[diagonalPath-1],
133 removePath = bestPath[diagonalPath+1];
134 oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
136 // No one else is going to attempt to use this value, clear it
137 bestPath[diagonalPath-1] = undefined;
140 var canAdd = addPath && addPath.newPos+1 < newLen;
141 var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
142 if (!canAdd && !canRemove) {
143 bestPath[diagonalPath] = undefined;
147 // Select the diagonal that we want to branch from. We select the prior
148 // path whose position in the new string is the farthest from the origin
149 // and does not pass the bounds of the diff graph
150 if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
151 basePath = clonePath(removePath);
152 this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
154 basePath = clonePath(addPath);
156 this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
159 var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
161 if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
162 return basePath.components;
164 bestPath[diagonalPath] = basePath;
170 pushComponent: function(components, value, added, removed) {
171 var last = components[components.length-1];
172 if (last && last.added === added && last.removed === removed) {
173 // We need to clone here as the component clone operation is just
174 // as shallow array clone
175 components[components.length-1] =
176 {value: this.join(last.value, value), added: added, removed: removed };
178 components.push({value: value, added: added, removed: removed });
181 extractCommon: function(basePath, newString, oldString, diagonalPath) {
182 var newLen = newString.length,
183 oldLen = oldString.length,
184 newPos = basePath.newPos,
185 oldPos = newPos - diagonalPath;
186 while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
190 this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
192 basePath.newPos = newPos;
196 equals: function(left, right) {
197 var reWhitespace = /\S/;
198 if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
201 return left === right;
204 join: function(left, right) {
207 tokenize: function(value) {
212 var CharDiff = new Diff();
214 var WordDiff = new Diff(true);
215 var WordWithSpaceDiff = new Diff();
216 WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
217 return removeEmpty(value.split(/(\s+|\b)/));
220 var CssDiff = new Diff(true);
221 CssDiff.tokenize = function(value) {
222 return removeEmpty(value.split(/([{}:;,]|\s+)/));
225 var LineDiff = new Diff();
226 LineDiff.tokenize = function(value) {
227 return value.split(/^/m);
233 diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
234 diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
235 diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); },
236 diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
238 diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
240 createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
243 ret.push('Index: ' + fileName);
244 ret.push('===================================================================');
245 ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
246 ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
248 var diff = LineDiff.diff(oldStr, newStr);
249 if (!diff[diff.length-1].value) {
250 diff.pop(); // Remove trailing newline add
252 diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
254 function contextLines(lines) {
255 return lines.map(function(entry) { return ' ' + entry; });
257 function eofNL(curRange, i, current) {
258 var last = diff[diff.length-2],
259 isLast = i === diff.length-2,
260 isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);
262 // Figure out if this is the last line for the given file and missing NL
263 if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
264 curRange.push('\\ No newline at end of file');
268 var oldRangeStart = 0, newRangeStart = 0, curRange = [],
269 oldLine = 1, newLine = 1;
270 for (var i = 0; i < diff.length; i++) {
271 var current = diff[i],
272 lines = current.lines || current.value.replace(/\n$/, '').split('\n');
273 current.lines = lines;
275 if (current.added || current.removed) {
276 if (!oldRangeStart) {
277 var prev = diff[i-1];
278 oldRangeStart = oldLine;
279 newRangeStart = newLine;
282 curRange = contextLines(prev.lines.slice(-4));
283 oldRangeStart -= curRange.length;
284 newRangeStart -= curRange.length;
287 curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; }));
288 eofNL(curRange, i, current);
291 newLine += lines.length;
293 oldLine += lines.length;
297 // Close out any changes that have been output (or join overlapping)
298 if (lines.length <= 8 && i < diff.length-2) {
300 curRange.push.apply(curRange, contextLines(lines));
302 // end the range and output
303 var contextSize = Math.min(lines.length, 4);
305 '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize)
306 + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize)
308 ret.push.apply(ret, curRange);
309 ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
310 if (lines.length <= 4) {
311 eofNL(ret, i, current);
314 oldRangeStart = 0; newRangeStart = 0; curRange = [];
317 oldLine += lines.length;
318 newLine += lines.length;
322 return ret.join('\n') + '\n';
325 applyPatch: function(oldStr, uniDiff) {
326 var diffstr = uniDiff.split('\n');
328 var remEOFNL = false,
331 for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
332 if(diffstr[i][0] === '@') {
333 var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
341 } else if(diffstr[i][0] === '+') {
342 diff[0].newlines.push(diffstr[i].substr(1));
343 } else if(diffstr[i][0] === '-') {
344 diff[0].oldlines.push(diffstr[i].substr(1));
345 } else if(diffstr[i][0] === ' ') {
346 diff[0].newlines.push(diffstr[i].substr(1));
347 diff[0].oldlines.push(diffstr[i].substr(1));
348 } else if(diffstr[i][0] === '\\') {
349 if (diffstr[i-1][0] === '+') {
351 } else if(diffstr[i-1][0] === '-') {
357 var str = oldStr.split('\n');
358 for (var i = diff.length - 1; i >= 0; i--) {
360 for (var j = 0; j < d.oldlength; j++) {
361 if(str[d.start-1+j] !== d.oldlines[j]) {
365 Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
369 while (!str[str.length-1]) {
372 } else if (addEOFNL) {
375 return str.join('\n');
378 convertChangesToXML: function(changes){
380 for ( var i = 0; i < changes.length; i++) {
381 var change = changes[i];
384 } else if (change.removed) {
388 ret.push(escapeHTML(change.value));
392 } else if (change.removed) {
399 // See: http://code.google.com/p/google-diff-match-patch/wiki/API
400 convertChangesToDMP: function(changes){
401 var ret = [], change;
402 for ( var i = 0; i < changes.length; i++) {
404 ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
411 if (typeof module !== 'undefined') {
412 module.exports = JsDiff;
415 }); // module: browser/diff.js
417 require.register("browser/events.js", function(module, exports, require){
423 exports.EventEmitter = EventEmitter;
426 * Check if `obj` is an array.
429 function isArray(obj) {
430 return '[object Array]' == {}.toString.call(obj);
434 * Event emitter constructor.
439 function EventEmitter(){};
447 EventEmitter.prototype.on = function (name, fn) {
452 if (!this.$events[name]) {
453 this.$events[name] = fn;
454 } else if (isArray(this.$events[name])) {
455 this.$events[name].push(fn);
457 this.$events[name] = [this.$events[name], fn];
463 EventEmitter.prototype.addListener = EventEmitter.prototype.on;
466 * Adds a volatile listener.
471 EventEmitter.prototype.once = function (name, fn) {
475 self.removeListener(name, on);
476 fn.apply(this, arguments);
486 * Removes a listener.
491 EventEmitter.prototype.removeListener = function (name, fn) {
492 if (this.$events && this.$events[name]) {
493 var list = this.$events[name];
498 for (var i = 0, l = list.length; i < l; i++) {
499 if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
512 delete this.$events[name];
514 } else if (list === fn || (list.listener && list.listener === fn)) {
515 delete this.$events[name];
523 * Removes all listeners for an event.
528 EventEmitter.prototype.removeAllListeners = function (name) {
529 if (name === undefined) {
534 if (this.$events && this.$events[name]) {
535 this.$events[name] = null;
542 * Gets all listeners for a certain event.
547 EventEmitter.prototype.listeners = function (name) {
552 if (!this.$events[name]) {
553 this.$events[name] = [];
556 if (!isArray(this.$events[name])) {
557 this.$events[name] = [this.$events[name]];
560 return this.$events[name];
569 EventEmitter.prototype.emit = function (name) {
574 var handler = this.$events[name];
580 var args = [].slice.call(arguments, 1);
582 if ('function' == typeof handler) {
583 handler.apply(this, args);
584 } else if (isArray(handler)) {
585 var listeners = handler.slice();
587 for (var i = 0, l = listeners.length; i < l; i++) {
588 listeners[i].apply(this, args);
596 }); // module: browser/events.js
598 require.register("browser/fs.js", function(module, exports, require){
600 }); // module: browser/fs.js
602 require.register("browser/path.js", function(module, exports, require){
604 }); // module: browser/path.js
606 require.register("browser/progress.js", function(module, exports, require){
612 module.exports = Progress;
615 * Initialize a new `Progress` indicator.
618 function Progress() {
622 this.font('helvetica, arial, sans-serif');
626 * Set progress size to `n`.
629 * @return {Progress} for chaining
633 Progress.prototype.size = function(n){
641 * @param {String} str
642 * @return {Progress} for chaining
646 Progress.prototype.text = function(str){
652 * Set font size to `n`.
655 * @return {Progress} for chaining
659 Progress.prototype.fontSize = function(n){
667 * @param {String} family
668 * @return {Progress} for chaining
671 Progress.prototype.font = function(family){
677 * Update percentage to `n`.
680 * @return {Progress} for chaining
683 Progress.prototype.update = function(n){
691 * @param {CanvasRenderingContext2d} ctx
692 * @return {Progress} for chaining
695 Progress.prototype.draw = function(ctx){
696 var percent = Math.min(this.percent, 100)
702 , fontSize = this._fontSize;
704 ctx.font = fontSize + 'px ' + this._font;
706 var angle = Math.PI * 2 * (percent / 100);
707 ctx.clearRect(0, 0, size, size);
710 ctx.strokeStyle = '#9f9f9f';
712 ctx.arc(x, y, rad, 0, angle, false);
716 ctx.strokeStyle = '#eee';
718 ctx.arc(x, y, rad - 1, 0, angle, true);
722 var text = this._text || (percent | 0) + '%'
723 , w = ctx.measureText(text).width;
728 , y + fontSize / 2 - 1);
733 }); // module: browser/progress.js
735 require.register("browser/tty.js", function(module, exports, require){
737 exports.isatty = function(){
741 exports.getWindowSize = function(){
742 if ('innerHeight' in global) {
743 return [global.innerHeight, global.innerWidth];
745 // In a Web Worker, the DOM Window is not available.
750 }); // module: browser/tty.js
752 require.register("context.js", function(module, exports, require){
758 module.exports = Context;
761 * Initialize a new `Context`.
769 * Set or get the context `Runnable` to `runnable`.
771 * @param {Runnable} runnable
776 Context.prototype.runnable = function(runnable){
777 if (0 == arguments.length) return this._runnable;
778 this.test = this._runnable = runnable;
783 * Set test timeout `ms`.
786 * @return {Context} self
790 Context.prototype.timeout = function(ms){
791 this.runnable().timeout(ms);
796 * Set test slowness threshold `ms`.
799 * @return {Context} self
803 Context.prototype.slow = function(ms){
804 this.runnable().slow(ms);
809 * Inspect the context void of `._runnable`.
815 Context.prototype.inspect = function(){
816 return JSON.stringify(this, function(key, val){
817 if ('_runnable' == key) return;
818 if ('test' == key) return;
823 }); // module: context.js
825 require.register("hook.js", function(module, exports, require){
828 * Module dependencies.
831 var Runnable = require('./runnable');
837 module.exports = Hook;
840 * Initialize a new `Hook` with the given `title` and callback `fn`.
842 * @param {String} title
843 * @param {Function} fn
847 function Hook(title, fn) {
848 Runnable.call(this, title, fn);
853 * Inherit from `Runnable.prototype`.
857 F.prototype = Runnable.prototype;
858 Hook.prototype = new F;
859 Hook.prototype.constructor = Hook;
863 * Get or set the test `err`.
870 Hook.prototype.error = function(err){
871 if (0 == arguments.length) {
872 var err = this._error;
880 }); // module: hook.js
882 require.register("interfaces/bdd.js", function(module, exports, require){
885 * Module dependencies.
888 var Suite = require('../suite')
889 , Test = require('../test')
890 , utils = require('../utils');
893 * BDD-style interface:
895 * describe('Array', function(){
896 * describe('#indexOf()', function(){
897 * it('should return -1 when not present', function(){
901 * it('should return the index when present', function(){
909 module.exports = function(suite){
910 var suites = [suite];
912 suite.on('pre-require', function(context, file, mocha){
915 * Execute before running tests.
918 context.before = function(fn){
919 suites[0].beforeAll(fn);
923 * Execute after running tests.
926 context.after = function(fn){
927 suites[0].afterAll(fn);
931 * Execute before each test case.
934 context.beforeEach = function(fn){
935 suites[0].beforeEach(fn);
939 * Execute after each test case.
942 context.afterEach = function(fn){
943 suites[0].afterEach(fn);
947 * Describe a "suite" with the given `title`
948 * and callback `fn` containing nested suites
952 context.describe = context.context = function(title, fn){
953 var suite = Suite.create(suites[0], title);
954 suites.unshift(suite);
966 context.describe.skip = function(title, fn){
967 var suite = Suite.create(suites[0], title);
968 suite.pending = true;
969 suites.unshift(suite);
978 context.describe.only = function(title, fn){
979 var suite = context.describe(title, fn);
980 mocha.grep(suite.fullTitle());
985 * Describe a specification or test-case
986 * with the given `title` and callback `fn`
990 context.it = context.specify = function(title, fn){
991 var suite = suites[0];
992 if (suite.pending) var fn = null;
993 var test = new Test(title, fn);
999 * Exclusive test-case.
1002 context.it.only = function(title, fn){
1003 var test = context.it(title, fn);
1004 var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
1005 mocha.grep(new RegExp(reString));
1010 * Pending test case.
1015 context.it.skip = function(title){
1021 }); // module: interfaces/bdd.js
1023 require.register("interfaces/exports.js", function(module, exports, require){
1026 * Module dependencies.
1029 var Suite = require('../suite')
1030 , Test = require('../test');
1033 * TDD-style interface:
1037 * 'should return -1 when the value is not present': function(){
1041 * 'should return the correct index when the value is present': function(){
1049 module.exports = function(suite){
1050 var suites = [suite];
1052 suite.on('require', visit);
1054 function visit(obj) {
1056 for (var key in obj) {
1057 if ('function' == typeof obj[key]) {
1061 suites[0].beforeAll(fn);
1064 suites[0].afterAll(fn);
1067 suites[0].beforeEach(fn);
1070 suites[0].afterEach(fn);
1073 suites[0].addTest(new Test(key, fn));
1076 var suite = Suite.create(suites[0], key);
1077 suites.unshift(suite);
1085 }); // module: interfaces/exports.js
1087 require.register("interfaces/index.js", function(module, exports, require){
1089 exports.bdd = require('./bdd');
1090 exports.tdd = require('./tdd');
1091 exports.qunit = require('./qunit');
1092 exports.exports = require('./exports');
1094 }); // module: interfaces/index.js
1096 require.register("interfaces/qunit.js", function(module, exports, require){
1099 * Module dependencies.
1102 var Suite = require('../suite')
1103 , Test = require('../test')
1104 , utils = require('../utils');
1107 * QUnit-style interface:
1111 * test('#length', function(){
1112 * var arr = [1,2,3];
1113 * ok(arr.length == 3);
1116 * test('#indexOf()', function(){
1117 * var arr = [1,2,3];
1118 * ok(arr.indexOf(1) == 0);
1119 * ok(arr.indexOf(2) == 1);
1120 * ok(arr.indexOf(3) == 2);
1125 * test('#length', function(){
1126 * ok('foo'.length == 3);
1131 module.exports = function(suite){
1132 var suites = [suite];
1134 suite.on('pre-require', function(context, file, mocha){
1137 * Execute before running tests.
1140 context.before = function(fn){
1141 suites[0].beforeAll(fn);
1145 * Execute after running tests.
1148 context.after = function(fn){
1149 suites[0].afterAll(fn);
1153 * Execute before each test case.
1156 context.beforeEach = function(fn){
1157 suites[0].beforeEach(fn);
1161 * Execute after each test case.
1164 context.afterEach = function(fn){
1165 suites[0].afterEach(fn);
1169 * Describe a "suite" with the given `title`.
1172 context.suite = function(title){
1173 if (suites.length > 1) suites.shift();
1174 var suite = Suite.create(suites[0], title);
1175 suites.unshift(suite);
1180 * Exclusive test-case.
1183 context.suite.only = function(title, fn){
1184 var suite = context.suite(title, fn);
1185 mocha.grep(suite.fullTitle());
1189 * Describe a specification or test-case
1190 * with the given `title` and callback `fn`
1191 * acting as a thunk.
1194 context.test = function(title, fn){
1195 var test = new Test(title, fn);
1196 suites[0].addTest(test);
1201 * Exclusive test-case.
1204 context.test.only = function(title, fn){
1205 var test = context.test(title, fn);
1206 var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
1207 mocha.grep(new RegExp(reString));
1211 * Pending test case.
1214 context.test.skip = function(title){
1215 context.test(title);
1220 }); // module: interfaces/qunit.js
1222 require.register("interfaces/tdd.js", function(module, exports, require){
1225 * Module dependencies.
1228 var Suite = require('../suite')
1229 , Test = require('../test')
1230 , utils = require('../utils');;
1233 * TDD-style interface:
1235 * suite('Array', function(){
1236 * suite('#indexOf()', function(){
1237 * suiteSetup(function(){
1241 * test('should return -1 when not present', function(){
1245 * test('should return the index when present', function(){
1249 * suiteTeardown(function(){
1257 module.exports = function(suite){
1258 var suites = [suite];
1260 suite.on('pre-require', function(context, file, mocha){
1263 * Execute before each test case.
1266 context.setup = function(fn){
1267 suites[0].beforeEach(fn);
1271 * Execute after each test case.
1274 context.teardown = function(fn){
1275 suites[0].afterEach(fn);
1279 * Execute before the suite.
1282 context.suiteSetup = function(fn){
1283 suites[0].beforeAll(fn);
1287 * Execute after the suite.
1290 context.suiteTeardown = function(fn){
1291 suites[0].afterAll(fn);
1295 * Describe a "suite" with the given `title`
1296 * and callback `fn` containing nested suites
1300 context.suite = function(title, fn){
1301 var suite = Suite.create(suites[0], title);
1302 suites.unshift(suite);
1311 context.suite.skip = function(title, fn) {
1312 var suite = Suite.create(suites[0], title);
1313 suite.pending = true;
1314 suites.unshift(suite);
1320 * Exclusive test-case.
1323 context.suite.only = function(title, fn){
1324 var suite = context.suite(title, fn);
1325 mocha.grep(suite.fullTitle());
1329 * Describe a specification or test-case
1330 * with the given `title` and callback `fn`
1331 * acting as a thunk.
1334 context.test = function(title, fn){
1335 var suite = suites[0];
1336 if (suite.pending) var fn = null;
1337 var test = new Test(title, fn);
1338 suite.addTest(test);
1343 * Exclusive test-case.
1346 context.test.only = function(title, fn){
1347 var test = context.test(title, fn);
1348 var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
1349 mocha.grep(new RegExp(reString));
1353 * Pending test case.
1356 context.test.skip = function(title){
1357 context.test(title);
1362 }); // module: interfaces/tdd.js
1364 require.register("mocha.js", function(module, exports, require){
1367 * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
1372 * Module dependencies.
1375 var path = require('browser/path')
1376 , utils = require('./utils');
1382 exports = module.exports = Mocha;
1388 exports.utils = utils;
1389 exports.interfaces = require('./interfaces');
1390 exports.reporters = require('./reporters');
1391 exports.Runnable = require('./runnable');
1392 exports.Context = require('./context');
1393 exports.Runner = require('./runner');
1394 exports.Suite = require('./suite');
1395 exports.Hook = require('./hook');
1396 exports.Test = require('./test');
1399 * Return image `name` path.
1401 * @param {String} name
1406 function image(name) {
1407 return __dirname + '/../images/' + name + '.png';
1411 * Setup mocha with `options`.
1415 * - `ui` name "bdd", "tdd", "exports" etc
1416 * - `reporter` reporter instance, defaults to `mocha.reporters.Dot`
1417 * - `globals` array of accepted globals
1418 * - `timeout` timeout in milliseconds
1419 * - `bail` bail on the first test failure
1420 * - `slow` milliseconds to wait before considering a test slow
1421 * - `ignoreLeaks` ignore global leaks
1422 * - `grep` string or regexp to filter tests with
1424 * @param {Object} options
1428 function Mocha(options) {
1429 options = options || {};
1431 this.options = options;
1432 this.grep(options.grep);
1433 this.suite = new exports.Suite('', new exports.Context);
1434 this.ui(options.ui);
1435 this.bail(options.bail);
1436 this.reporter(options.reporter);
1437 if (null != options.timeout) this.timeout(options.timeout);
1438 this.useColors(options.useColors)
1439 if (options.slow) this.slow(options.slow);
1443 * Enable or disable bailing on the first failure.
1445 * @param {Boolean} [bail]
1449 Mocha.prototype.bail = function(bail){
1450 if (0 == arguments.length) bail = true;
1451 this.suite.bail(bail);
1458 * @param {String} file
1462 Mocha.prototype.addFile = function(file){
1463 this.files.push(file);
1468 * Set reporter to `reporter`, defaults to "dot".
1470 * @param {String|Function} reporter name or constructor
1474 Mocha.prototype.reporter = function(reporter){
1475 if ('function' == typeof reporter) {
1476 this._reporter = reporter;
1478 reporter = reporter || 'dot';
1480 try { _reporter = require('./reporters/' + reporter); } catch (err) {};
1481 if (!_reporter) try { _reporter = require(reporter); } catch (err) {};
1482 if (!_reporter && reporter === 'teamcity')
1483 console.warn('The Teamcity reporter was moved to a package named ' +
1484 'mocha-teamcity-reporter ' +
1485 '(https://npmjs.org/package/mocha-teamcity-reporter).');
1486 if (!_reporter) throw new Error('invalid reporter "' + reporter + '"');
1487 this._reporter = _reporter;
1493 * Set test UI `name`, defaults to "bdd".
1495 * @param {String} bdd
1499 Mocha.prototype.ui = function(name){
1500 name = name || 'bdd';
1501 this._ui = exports.interfaces[name];
1502 if (!this._ui) try { this._ui = require(name); } catch (err) {};
1503 if (!this._ui) throw new Error('invalid interface "' + name + '"');
1504 this._ui = this._ui(this.suite);
1509 * Load registered files.
1514 Mocha.prototype.loadFiles = function(fn){
1516 var suite = this.suite;
1517 var pending = this.files.length;
1518 this.files.forEach(function(file){
1519 file = path.resolve(file);
1520 suite.emit('pre-require', global, file, self);
1521 suite.emit('require', require(file), file, self);
1522 suite.emit('post-require', global, file, self);
1523 --pending || (fn && fn());
1528 * Enable growl support.
1533 Mocha.prototype._growl = function(runner, reporter) {
1534 var notify = require('growl');
1536 runner.on('end', function(){
1537 var stats = reporter.stats;
1538 if (stats.failures) {
1539 var msg = stats.failures + ' of ' + runner.total + ' tests failed';
1540 notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
1542 notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
1545 , image: image('ok')
1552 * Add regexp to grep, if `re` is a string it is escaped.
1554 * @param {RegExp|String} re
1559 Mocha.prototype.grep = function(re){
1560 this.options.grep = 'string' == typeof re
1561 ? new RegExp(utils.escapeRegexp(re))
1567 * Invert `.grep()` matches.
1573 Mocha.prototype.invert = function(){
1574 this.options.invert = true;
1579 * Ignore global leaks.
1581 * @param {Boolean} ignore
1586 Mocha.prototype.ignoreLeaks = function(ignore){
1587 this.options.ignoreLeaks = !!ignore;
1592 * Enable global leak checking.
1598 Mocha.prototype.checkLeaks = function(){
1599 this.options.ignoreLeaks = false;
1604 * Enable growl support.
1610 Mocha.prototype.growl = function(){
1611 this.options.growl = true;
1616 * Ignore `globals` array or string.
1618 * @param {Array|String} globals
1623 Mocha.prototype.globals = function(globals){
1624 this.options.globals = (this.options.globals || []).concat(globals);
1629 * Emit color output.
1631 * @param {Boolean} colors
1636 Mocha.prototype.useColors = function(colors){
1637 this.options.useColors = arguments.length && colors != undefined
1644 * Set the timeout in milliseconds.
1646 * @param {Number} timeout
1651 Mocha.prototype.timeout = function(timeout){
1652 this.suite.timeout(timeout);
1657 * Set slowness threshold in milliseconds.
1659 * @param {Number} slow
1664 Mocha.prototype.slow = function(slow){
1665 this.suite.slow(slow);
1670 * Makes all tests async (accepting a callback)
1676 Mocha.prototype.asyncOnly = function(){
1677 this.options.asyncOnly = true;
1682 * Run tests and invoke `fn()` when complete.
1684 * @param {Function} fn
1689 Mocha.prototype.run = function(fn){
1690 if (this.files.length) this.loadFiles();
1691 var suite = this.suite;
1692 var options = this.options;
1693 var runner = new exports.Runner(suite);
1694 var reporter = new this._reporter(runner);
1695 runner.ignoreLeaks = false !== options.ignoreLeaks;
1696 runner.asyncOnly = options.asyncOnly;
1697 if (options.grep) runner.grep(options.grep, options.invert);
1698 if (options.globals) runner.globals(options.globals);
1699 if (options.growl) this._growl(runner, reporter);
1700 exports.reporters.Base.useColors = options.useColors;
1701 return runner.run(fn);
1704 }); // module: mocha.js
1706 require.register("ms.js", function(module, exports, require){
1718 * Parse or format the given `val`.
1722 * - `long` verbose formatting [false]
1724 * @param {String|Number} val
1725 * @param {Object} options
1726 * @return {String|Number}
1730 module.exports = function(val, options){
1731 options = options || {};
1732 if ('string' == typeof val) return parse(val);
1739 * Parse the given `str` and return milliseconds.
1741 * @param {String} str
1746 function parse(str) {
1747 var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
1749 var n = parseFloat(match[1]);
1750 var type = (match[2] || 'ms').toLowerCase();
1778 * Short format for `ms`.
1780 * @param {Number} ms
1785 function short(ms) {
1786 if (ms >= d) return Math.round(ms / d) + 'd';
1787 if (ms >= h) return Math.round(ms / h) + 'h';
1788 if (ms >= m) return Math.round(ms / m) + 'm';
1789 if (ms >= s) return Math.round(ms / s) + 's';
1794 * Long format for `ms`.
1796 * @param {Number} ms
1802 return plural(ms, d, 'day')
1803 || plural(ms, h, 'hour')
1804 || plural(ms, m, 'minute')
1805 || plural(ms, s, 'second')
1810 * Pluralization helper.
1813 function plural(ms, n, name) {
1815 if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
1816 return Math.ceil(ms / n) + ' ' + name + 's';
1819 }); // module: ms.js
1821 require.register("reporters/base.js", function(module, exports, require){
1824 * Module dependencies.
1827 var tty = require('browser/tty')
1828 , diff = require('browser/diff')
1829 , ms = require('../ms');
1832 * Save timer references to avoid Sinon interfering (see GH-237).
1835 var Date = global.Date
1836 , setTimeout = global.setTimeout
1837 , setInterval = global.setInterval
1838 , clearTimeout = global.clearTimeout
1839 , clearInterval = global.clearInterval;
1842 * Check if both stdio streams are associated with a tty.
1845 var isatty = tty.isatty(1) && tty.isatty(2);
1851 exports = module.exports = Base;
1854 * Enable coloring by default.
1857 exports.useColors = isatty || (process.env.MOCHA_COLORS !== undefined);
1860 * Inline diffs instead of +/-
1863 exports.inlineDiffs = false;
1866 * Default color map.
1874 , 'bright yellow': 93
1878 , 'error message': 31
1888 , 'diff removed': 41
1892 * Default symbol map.
1901 // With node.js on Windows: use symbols available in terminal default fonts
1902 if ('win32' == process.platform) {
1903 exports.symbols.ok = '\u221A';
1904 exports.symbols.err = '\u00D7';
1905 exports.symbols.dot = '.';
1909 * Color `str` with the given `type`,
1910 * allowing colors to be disabled,
1911 * as well as user-defined color
1914 * @param {String} type
1915 * @param {String} str
1920 var color = exports.color = function(type, str) {
1921 if (!exports.useColors) return str;
1922 return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
1926 * Expose term window size, with some
1927 * defaults for when stderr is not a tty.
1932 ? process.stdout.getWindowSize
1933 ? process.stdout.getWindowSize(1)[0]
1934 : tty.getWindowSize()[1]
1939 * Expose some basic cursor interactions
1940 * that are common among reporters.
1945 isatty && process.stdout.write('\u001b[?25l');
1949 isatty && process.stdout.write('\u001b[?25h');
1952 deleteLine: function(){
1953 isatty && process.stdout.write('\u001b[2K');
1956 beginningOfLine: function(){
1957 isatty && process.stdout.write('\u001b[0G');
1962 exports.cursor.deleteLine();
1963 exports.cursor.beginningOfLine();
1965 process.stdout.write('\n');
1971 * Outut the given `failures` as a list.
1973 * @param {Array} failures
1977 exports.list = function(failures){
1979 failures.forEach(function(test, i){
1981 var fmt = color('error title', ' %s) %s:\n')
1982 + color('error message', ' %s')
1983 + color('error stack', '\n%s\n');
1987 , message = err.message || ''
1988 , stack = err.stack || message
1989 , index = stack.indexOf(message) + message.length
1990 , msg = stack.slice(0, index)
1991 , actual = err.actual
1992 , expected = err.expected
1997 msg = 'Uncaught ' + msg;
2000 // explicitly show diff
2001 if (err.showDiff && sameType(actual, expected)) {
2003 err.actual = actual = stringify(actual);
2004 err.expected = expected = stringify(expected);
2007 // actual / expected diff
2008 if ('string' == typeof actual && 'string' == typeof expected) {
2009 fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n');
2010 var match = message.match(/^([^:]+): expected/);
2011 msg = match ? '\n ' + color('error message', match[1]) : '';
2013 if (exports.inlineDiffs) {
2014 msg += inlineDiff(err, escape);
2016 msg += unifiedDiff(err, escape);
2020 // indent stack trace without msg
2021 stack = stack.slice(index ? index + 1 : index)
2022 .replace(/^/gm, ' ');
2024 console.error(fmt, (i + 1), test.fullTitle(), msg, stack);
2029 * Initialize a new `Base` reporter.
2031 * All other reporters generally
2032 * inherit from this reporter, providing
2033 * stats such as test duration, number
2034 * of tests passed / failed etc.
2036 * @param {Runner} runner
2040 function Base(runner) {
2042 , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 }
2043 , failures = this.failures = [];
2045 if (!runner) return;
2046 this.runner = runner;
2048 runner.stats = stats;
2050 runner.on('start', function(){
2051 stats.start = new Date;
2054 runner.on('suite', function(suite){
2055 stats.suites = stats.suites || 0;
2056 suite.root || stats.suites++;
2059 runner.on('test end', function(test){
2060 stats.tests = stats.tests || 0;
2064 runner.on('pass', function(test){
2065 stats.passes = stats.passes || 0;
2067 var medium = test.slow() / 2;
2068 test.speed = test.duration > test.slow()
2070 : test.duration > medium
2077 runner.on('fail', function(test, err){
2078 stats.failures = stats.failures || 0;
2081 failures.push(test);
2084 runner.on('end', function(){
2085 stats.end = new Date;
2086 stats.duration = new Date - stats.start;
2089 runner.on('pending', function(){
2095 * Output common epilogue used by many of
2096 * the bundled reporters.
2101 Base.prototype.epilogue = function(){
2102 var stats = this.stats;
2109 fmt = color('bright pass', ' ')
2110 + color('green', ' %d passing')
2111 + color('light', ' (%s)');
2115 ms(stats.duration));
2118 if (stats.pending) {
2119 fmt = color('pending', ' ')
2120 + color('pending', ' %d pending');
2122 console.log(fmt, stats.pending);
2126 if (stats.failures) {
2127 fmt = color('fail', ' %d failing');
2132 Base.list(this.failures);
2140 * Pad the given `str` to `len`.
2142 * @param {String} str
2143 * @param {String} len
2148 function pad(str, len) {
2150 return Array(len - str.length + 1).join(' ') + str;
2155 * Returns an inline diff between 2 strings with coloured ANSI output
2157 * @param {Error} Error with actual/expected
2158 * @return {String} Diff
2162 function inlineDiff(err, escape) {
2163 var msg = errorDiff(err, 'WordsWithSpace', escape);
2166 var lines = msg.split('\n');
2167 if (lines.length > 4) {
2168 var width = String(lines.length).length;
2169 msg = lines.map(function(str, i){
2170 return pad(++i, width) + ' |' + ' ' + str;
2176 + color('diff removed', 'actual')
2178 + color('diff added', 'expected')
2184 msg = msg.replace(/^/gm, ' ');
2189 * Returns a unified diff between 2 strings
2191 * @param {Error} Error with actual/expected
2192 * @return {String} Diff
2196 function unifiedDiff(err, escape) {
2198 function cleanUp(line) {
2200 line = escapeInvisibles(line);
2202 if (line[0] === '+') return indent + colorLines('diff added', line);
2203 if (line[0] === '-') return indent + colorLines('diff removed', line);
2204 if (line.match(/\@\@/)) return null;
2205 if (line.match(/\\ No newline/)) return null;
2206 else return indent + line;
2208 function notBlank(line) {
2209 return line != null;
2211 msg = diff.createPatch('string', err.actual, err.expected);
2212 var lines = msg.split('\n').splice(4);
2214 + colorLines('diff added', '+ expected') + ' '
2215 + colorLines('diff removed', '- actual')
2217 + lines.map(cleanUp).filter(notBlank).join('\n');
2221 * Return a character diff for `err`.
2223 * @param {Error} err
2228 function errorDiff(err, type, escape) {
2229 var actual = escape ? escapeInvisibles(err.actual) : err.actual;
2230 var expected = escape ? escapeInvisibles(err.expected) : err.expected;
2231 return diff['diff' + type](actual, expected).map(function(str){
2232 if (str.added) return colorLines('diff added', str.value);
2233 if (str.removed) return colorLines('diff removed', str.value);
2239 * Returns a string with all invisible characters in plain text
2241 * @param {String} line
2245 function escapeInvisibles(line) {
2246 return line.replace(/\t/g, '<tab>')
2247 .replace(/\r/g, '<CR>')
2248 .replace(/\n/g, '<LF>\n');
2252 * Color lines for `str`, using the color `name`.
2254 * @param {String} name
2255 * @param {String} str
2260 function colorLines(name, str) {
2261 return str.split('\n').map(function(str){
2262 return color(name, str);
2269 * @param {Mixed} obj
2274 function stringify(obj) {
2275 if (obj instanceof RegExp) return obj.toString();
2276 return JSON.stringify(obj, null, 2);
2280 * Check that a / b have the same type.
2288 function sameType(a, b) {
2289 a = Object.prototype.toString.call(a);
2290 b = Object.prototype.toString.call(b);
2296 }); // module: reporters/base.js
2298 require.register("reporters/doc.js", function(module, exports, require){
2301 * Module dependencies.
2304 var Base = require('./base')
2305 , utils = require('../utils');
2311 exports = module.exports = Doc;
2314 * Initialize a new `Doc` reporter.
2316 * @param {Runner} runner
2320 function Doc(runner) {
2321 Base.call(this, runner);
2324 , stats = this.stats
2325 , total = runner.total
2329 return Array(indents).join(' ');
2332 runner.on('suite', function(suite){
2333 if (suite.root) return;
2335 console.log('%s<section class="suite">', indent());
2337 console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
2338 console.log('%s<dl>', indent());
2341 runner.on('suite end', function(suite){
2342 if (suite.root) return;
2343 console.log('%s</dl>', indent());
2345 console.log('%s</section>', indent());
2349 runner.on('pass', function(test){
2350 console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title));
2351 var code = utils.escape(utils.clean(test.fn.toString()));
2352 console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code);
2356 }); // module: reporters/doc.js
2358 require.register("reporters/dot.js", function(module, exports, require){
2361 * Module dependencies.
2364 var Base = require('./base')
2365 , color = Base.color;
2371 exports = module.exports = Dot;
2374 * Initialize a new `Dot` matrix test reporter.
2376 * @param {Runner} runner
2380 function Dot(runner) {
2381 Base.call(this, runner);
2384 , stats = this.stats
2385 , width = Base.window.width * .75 | 0
2388 runner.on('start', function(){
2389 process.stdout.write('\n ');
2392 runner.on('pending', function(test){
2393 process.stdout.write(color('pending', Base.symbols.dot));
2396 runner.on('pass', function(test){
2397 if (++n % width == 0) process.stdout.write('\n ');
2398 if ('slow' == test.speed) {
2399 process.stdout.write(color('bright yellow', Base.symbols.dot));
2401 process.stdout.write(color(test.speed, Base.symbols.dot));
2405 runner.on('fail', function(test, err){
2406 if (++n % width == 0) process.stdout.write('\n ');
2407 process.stdout.write(color('fail', Base.symbols.dot));
2410 runner.on('end', function(){
2417 * Inherit from `Base.prototype`.
2421 F.prototype = Base.prototype;
2422 Dot.prototype = new F;
2423 Dot.prototype.constructor = Dot;
2425 }); // module: reporters/dot.js
2427 require.register("reporters/html-cov.js", function(module, exports, require){
2430 * Module dependencies.
2433 var JSONCov = require('./json-cov')
2434 , fs = require('browser/fs');
2440 exports = module.exports = HTMLCov;
2443 * Initialize a new `JsCoverage` reporter.
2445 * @param {Runner} runner
2449 function HTMLCov(runner) {
2450 var jade = require('jade')
2451 , file = __dirname + '/templates/coverage.jade'
2452 , str = fs.readFileSync(file, 'utf8')
2453 , fn = jade.compile(str, { filename: file })
2456 JSONCov.call(this, runner, false);
2458 runner.on('end', function(){
2459 process.stdout.write(fn({
2461 , coverageClass: coverageClass
2467 * Return coverage class for `n`.
2473 function coverageClass(n) {
2474 if (n >= 75) return 'high';
2475 if (n >= 50) return 'medium';
2476 if (n >= 25) return 'low';
2479 }); // module: reporters/html-cov.js
2481 require.register("reporters/html.js", function(module, exports, require){
2484 * Module dependencies.
2487 var Base = require('./base')
2488 , utils = require('../utils')
2489 , Progress = require('../browser/progress')
2490 , escape = utils.escape;
2493 * Save timer references to avoid Sinon interfering (see GH-237).
2496 var Date = global.Date
2497 , setTimeout = global.setTimeout
2498 , setInterval = global.setInterval
2499 , clearTimeout = global.clearTimeout
2500 , clearInterval = global.clearInterval;
2506 exports = module.exports = HTML;
2512 var statsTemplate = '<ul id="mocha-stats">'
2513 + '<li class="progress"><canvas width="40" height="40"></canvas></li>'
2514 + '<li class="passes"><a href="#">passes:</a> <em>0</em></li>'
2515 + '<li class="failures"><a href="#">failures:</a> <em>0</em></li>'
2516 + '<li class="duration">duration: <em>0</em>s</li>'
2520 * Initialize a new `HTML` reporter.
2522 * @param {Runner} runner
2526 function HTML(runner, root) {
2527 Base.call(this, runner);
2530 , stats = this.stats
2531 , total = runner.total
2532 , stat = fragment(statsTemplate)
2533 , items = stat.getElementsByTagName('li')
2534 , passes = items[1].getElementsByTagName('em')[0]
2535 , passesLink = items[1].getElementsByTagName('a')[0]
2536 , failures = items[2].getElementsByTagName('em')[0]
2537 , failuresLink = items[2].getElementsByTagName('a')[0]
2538 , duration = items[3].getElementsByTagName('em')[0]
2539 , canvas = stat.getElementsByTagName('canvas')[0]
2540 , report = fragment('<ul id="mocha-report"></ul>')
2545 root = root || document.getElementById('mocha');
2547 if (canvas.getContext) {
2548 var ratio = window.devicePixelRatio || 1;
2549 canvas.style.width = canvas.width;
2550 canvas.style.height = canvas.height;
2551 canvas.width *= ratio;
2552 canvas.height *= ratio;
2553 ctx = canvas.getContext('2d');
2554 ctx.scale(ratio, ratio);
2555 progress = new Progress;
2558 if (!root) return error('#mocha div missing, add it to your document');
2561 on(passesLink, 'click', function(){
2563 var name = /pass/.test(report.className) ? '' : ' pass';
2564 report.className = report.className.replace(/fail|pass/g, '') + name;
2565 if (report.className.trim()) hideSuitesWithout('test pass');
2569 on(failuresLink, 'click', function(){
2571 var name = /fail/.test(report.className) ? '' : ' fail';
2572 report.className = report.className.replace(/fail|pass/g, '') + name;
2573 if (report.className.trim()) hideSuitesWithout('test fail');
2576 root.appendChild(stat);
2577 root.appendChild(report);
2579 if (progress) progress.size(40);
2581 runner.on('suite', function(suite){
2582 if (suite.root) return;
2585 var url = self.suiteURL(suite);
2586 var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, escape(suite.title));
2589 stack[0].appendChild(el);
2590 stack.unshift(document.createElement('ul'));
2591 el.appendChild(stack[0]);
2594 runner.on('suite end', function(suite){
2595 if (suite.root) return;
2599 runner.on('fail', function(test, err){
2600 if ('hook' == test.type) runner.emit('test end', test);
2603 runner.on('test end', function(test){
2604 // TODO: add to stats
2605 var percent = stats.tests / this.total * 100 | 0;
2606 if (progress) progress.update(percent).draw(ctx);
2609 var ms = new Date - stats.start;
2610 text(passes, stats.passes);
2611 text(failures, stats.failures);
2612 text(duration, (ms / 1000).toFixed(2));
2615 if ('passed' == test.state) {
2616 var url = self.testURL(test);
2617 var el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span> <a href="%s" class="replay">‣</a></h2></li>', test.speed, test.title, test.duration, url);
2618 } else if (test.pending) {
2619 var el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title);
2621 var el = fragment('<li class="test fail"><h2>%e <a href="?grep=%e" class="replay">‣</a></h2></li>', test.title, encodeURIComponent(test.fullTitle()));
2622 var str = test.err.stack || test.err.toString();
2624 // FF / Opera do not add the message
2625 if (!~str.indexOf(test.err.message)) {
2626 str = test.err.message + '\n' + str;
2629 // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
2630 // check for the result of the stringifying.
2631 if ('[object Error]' == str) str = test.err.message;
2633 // Safari doesn't give you a stack. Let's at least provide a source line.
2634 if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) {
2635 str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")";
2638 el.appendChild(fragment('<pre class="error">%e</pre>', str));
2643 if (!test.pending) {
2644 var h2 = el.getElementsByTagName('h2')[0];
2646 on(h2, 'click', function(){
2647 pre.style.display = 'none' == pre.style.display
2652 var pre = fragment('<pre><code>%e</code></pre>', utils.clean(test.fn.toString()));
2653 el.appendChild(pre);
2654 pre.style.display = 'none';
2657 // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
2658 if (stack[0]) stack[0].appendChild(el);
2665 * @param {Object} [suite]
2668 HTML.prototype.suiteURL = function(suite){
2669 return '?grep=' + encodeURIComponent(suite.fullTitle());
2675 * @param {Object} [test]
2678 HTML.prototype.testURL = function(test){
2679 return '?grep=' + encodeURIComponent(test.fullTitle());
2683 * Display error `msg`.
2686 function error(msg) {
2687 document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg));
2691 * Return a DOM fragment from `html`.
2694 function fragment(html) {
2695 var args = arguments
2696 , div = document.createElement('div')
2699 div.innerHTML = html.replace(/%([se])/g, function(_, type){
2701 case 's': return String(args[i++]);
2702 case 'e': return escape(args[i++]);
2706 return div.firstChild;
2710 * Check for suites that do not have elements
2711 * with `classname`, and hide them.
2714 function hideSuitesWithout(classname) {
2715 var suites = document.getElementsByClassName('suite');
2716 for (var i = 0; i < suites.length; i++) {
2717 var els = suites[i].getElementsByClassName(classname);
2718 if (0 == els.length) suites[i].className += ' hidden';
2723 * Unhide .hidden suites.
2727 var els = document.getElementsByClassName('suite hidden');
2728 for (var i = 0; i < els.length; ++i) {
2729 els[i].className = els[i].className.replace('suite hidden', 'suite');
2734 * Set `el` text to `str`.
2737 function text(el, str) {
2738 if (el.textContent) {
2739 el.textContent = str;
2746 * Listen on `event` with callback `fn`.
2749 function on(el, event, fn) {
2750 if (el.addEventListener) {
2751 el.addEventListener(event, fn, false);
2753 el.attachEvent('on' + event, fn);
2757 }); // module: reporters/html.js
2759 require.register("reporters/index.js", function(module, exports, require){
2761 exports.Base = require('./base');
2762 exports.Dot = require('./dot');
2763 exports.Doc = require('./doc');
2764 exports.TAP = require('./tap');
2765 exports.JSON = require('./json');
2766 exports.HTML = require('./html');
2767 exports.List = require('./list');
2768 exports.Min = require('./min');
2769 exports.Spec = require('./spec');
2770 exports.Nyan = require('./nyan');
2771 exports.XUnit = require('./xunit');
2772 exports.Markdown = require('./markdown');
2773 exports.Progress = require('./progress');
2774 exports.Landing = require('./landing');
2775 exports.JSONCov = require('./json-cov');
2776 exports.HTMLCov = require('./html-cov');
2777 exports.JSONStream = require('./json-stream');
2779 }); // module: reporters/index.js
2781 require.register("reporters/json-cov.js", function(module, exports, require){
2784 * Module dependencies.
2787 var Base = require('./base');
2793 exports = module.exports = JSONCov;
2796 * Initialize a new `JsCoverage` reporter.
2798 * @param {Runner} runner
2799 * @param {Boolean} output
2803 function JSONCov(runner, output) {
2805 , output = 1 == arguments.length ? true : output;
2807 Base.call(this, runner);
2813 runner.on('test end', function(test){
2817 runner.on('pass', function(test){
2821 runner.on('fail', function(test){
2822 failures.push(test);
2825 runner.on('end', function(){
2826 var cov = global._$jscoverage || {};
2827 var result = self.cov = map(cov);
2828 result.stats = self.stats;
2829 result.tests = tests.map(clean);
2830 result.failures = failures.map(clean);
2831 result.passes = passes.map(clean);
2832 if (!output) return;
2833 process.stdout.write(JSON.stringify(result, null, 2 ));
2838 * Map jscoverage data to a JSON structure
2839 * suitable for reporting.
2841 * @param {Object} cov
2848 instrumentation: 'node-jscoverage'
2856 for (var filename in cov) {
2857 var data = coverage(filename, cov[filename]);
2858 ret.files.push(data);
2859 ret.hits += data.hits;
2860 ret.misses += data.misses;
2861 ret.sloc += data.sloc;
2864 ret.files.sort(function(a, b) {
2865 return a.filename.localeCompare(b.filename);
2869 ret.coverage = (ret.hits / ret.sloc) * 100;
2876 * Map jscoverage data for a single source file
2877 * to a JSON structure suitable for reporting.
2879 * @param {String} filename name of the source file
2880 * @param {Object} data jscoverage coverage data
2885 function coverage(filename, data) {
2895 data.source.forEach(function(line, num){
2898 if (data[num] === 0) {
2901 } else if (data[num] !== undefined) {
2908 , coverage: data[num] === undefined
2914 ret.coverage = ret.hits / ret.sloc * 100;
2920 * Return a plain-object representation of `test`
2921 * free of cyclic properties etc.
2923 * @param {Object} test
2928 function clean(test) {
2931 , fullTitle: test.fullTitle()
2932 , duration: test.duration
2936 }); // module: reporters/json-cov.js
2938 require.register("reporters/json-stream.js", function(module, exports, require){
2941 * Module dependencies.
2944 var Base = require('./base')
2945 , color = Base.color;
2951 exports = module.exports = List;
2954 * Initialize a new `List` test reporter.
2956 * @param {Runner} runner
2960 function List(runner) {
2961 Base.call(this, runner);
2964 , stats = this.stats
2965 , total = runner.total;
2967 runner.on('start', function(){
2968 console.log(JSON.stringify(['start', { total: total }]));
2971 runner.on('pass', function(test){
2972 console.log(JSON.stringify(['pass', clean(test)]));
2975 runner.on('fail', function(test, err){
2976 console.log(JSON.stringify(['fail', clean(test)]));
2979 runner.on('end', function(){
2980 process.stdout.write(JSON.stringify(['end', self.stats]));
2985 * Return a plain-object representation of `test`
2986 * free of cyclic properties etc.
2988 * @param {Object} test
2993 function clean(test) {
2996 , fullTitle: test.fullTitle()
2997 , duration: test.duration
3000 }); // module: reporters/json-stream.js
3002 require.register("reporters/json.js", function(module, exports, require){
3005 * Module dependencies.
3008 var Base = require('./base')
3009 , cursor = Base.cursor
3010 , color = Base.color;
3016 exports = module.exports = JSONReporter;
3019 * Initialize a new `JSON` reporter.
3021 * @param {Runner} runner
3025 function JSONReporter(runner) {
3027 Base.call(this, runner);
3033 runner.on('test end', function(test){
3037 runner.on('pass', function(test){
3041 runner.on('fail', function(test){
3042 failures.push(test);
3045 runner.on('end', function(){
3048 , tests: tests.map(clean)
3049 , failures: failures.map(clean)
3050 , passes: passes.map(clean)
3053 process.stdout.write(JSON.stringify(obj, null, 2));
3058 * Return a plain-object representation of `test`
3059 * free of cyclic properties etc.
3061 * @param {Object} test
3066 function clean(test) {
3069 , fullTitle: test.fullTitle()
3070 , duration: test.duration
3073 }); // module: reporters/json.js
3075 require.register("reporters/landing.js", function(module, exports, require){
3078 * Module dependencies.
3081 var Base = require('./base')
3082 , cursor = Base.cursor
3083 , color = Base.color;
3089 exports = module.exports = Landing;
3095 Base.colors.plane = 0;
3098 * Airplane crash color.
3101 Base.colors['plane crash'] = 31;
3107 Base.colors.runway = 90;
3110 * Initialize a new `Landing` reporter.
3112 * @param {Runner} runner
3116 function Landing(runner) {
3117 Base.call(this, runner);
3120 , stats = this.stats
3121 , width = Base.window.width * .75 | 0
3122 , total = runner.total
3123 , stream = process.stdout
3124 , plane = color('plane', '✈')
3129 var buf = Array(width).join('-');
3130 return ' ' + color('runway', buf);
3133 runner.on('start', function(){
3134 stream.write('\n ');
3138 runner.on('test end', function(test){
3139 // check if the plane crashed
3140 var col = -1 == crashed
3141 ? width * ++n / total | 0
3145 if ('failed' == test.state) {
3146 plane = color('plane crash', '✈');
3150 // render landing strip
3151 stream.write('\u001b[4F\n\n');
3152 stream.write(runway());
3153 stream.write('\n ');
3154 stream.write(color('runway', Array(col).join('â‹…')));
3156 stream.write(color('runway', Array(width - col).join('â‹…') + '\n'));
3157 stream.write(runway());
3158 stream.write('\u001b[0m');
3161 runner.on('end', function(){
3169 * Inherit from `Base.prototype`.
3173 F.prototype = Base.prototype;
3174 Landing.prototype = new F;
3175 Landing.prototype.constructor = Landing;
3177 }); // module: reporters/landing.js
3179 require.register("reporters/list.js", function(module, exports, require){
3182 * Module dependencies.
3185 var Base = require('./base')
3186 , cursor = Base.cursor
3187 , color = Base.color;
3193 exports = module.exports = List;
3196 * Initialize a new `List` test reporter.
3198 * @param {Runner} runner
3202 function List(runner) {
3203 Base.call(this, runner);
3206 , stats = this.stats
3209 runner.on('start', function(){
3213 runner.on('test', function(test){
3214 process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));
3217 runner.on('pending', function(test){
3218 var fmt = color('checkmark', ' -')
3219 + color('pending', ' %s');
3220 console.log(fmt, test.fullTitle());
3223 runner.on('pass', function(test){
3224 var fmt = color('checkmark', ' '+Base.symbols.dot)
3225 + color('pass', ' %s: ')
3226 + color(test.speed, '%dms');
3228 console.log(fmt, test.fullTitle(), test.duration);
3231 runner.on('fail', function(test, err){
3233 console.log(color('fail', ' %d) %s'), ++n, test.fullTitle());
3236 runner.on('end', self.epilogue.bind(self));
3240 * Inherit from `Base.prototype`.
3244 F.prototype = Base.prototype;
3245 List.prototype = new F;
3246 List.prototype.constructor = List;
3249 }); // module: reporters/list.js
3251 require.register("reporters/markdown.js", function(module, exports, require){
3253 * Module dependencies.
3256 var Base = require('./base')
3257 , utils = require('../utils');
3260 * Expose `Markdown`.
3263 exports = module.exports = Markdown;
3266 * Initialize a new `Markdown` reporter.
3268 * @param {Runner} runner
3272 function Markdown(runner) {
3273 Base.call(this, runner);
3276 , stats = this.stats
3280 function title(str) {
3281 return Array(level).join('#') + ' ' + str;
3285 return Array(level).join(' ');
3288 function mapTOC(suite, obj) {
3290 obj = obj[suite.title] = obj[suite.title] || { suite: suite };
3291 suite.suites.forEach(function(suite){
3297 function stringifyTOC(obj, level) {
3301 for (var key in obj) {
3302 if ('suite' == key) continue;
3303 if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
3304 if (key) buf += Array(level).join(' ') + link;
3305 buf += stringifyTOC(obj[key], level);
3311 function generateTOC(suite) {
3312 var obj = mapTOC(suite, {});
3313 return stringifyTOC(obj, 0);
3316 generateTOC(runner.suite);
3318 runner.on('suite', function(suite){
3320 var slug = utils.slug(suite.fullTitle());
3321 buf += '<a name="' + slug + '"></a>' + '\n';
3322 buf += title(suite.title) + '\n';
3325 runner.on('suite end', function(suite){
3329 runner.on('pass', function(test){
3330 var code = utils.clean(test.fn.toString());
3331 buf += test.title + '.\n';
3337 runner.on('end', function(){
3338 process.stdout.write('# TOC\n');
3339 process.stdout.write(generateTOC(runner.suite));
3340 process.stdout.write(buf);
3343 }); // module: reporters/markdown.js
3345 require.register("reporters/min.js", function(module, exports, require){
3348 * Module dependencies.
3351 var Base = require('./base');
3357 exports = module.exports = Min;
3360 * Initialize a new `Min` minimal test reporter (best used with --watch).
3362 * @param {Runner} runner
3366 function Min(runner) {
3367 Base.call(this, runner);
3369 runner.on('start', function(){
3371 process.stdout.write('\u001b[2J');
3372 // set cursor position
3373 process.stdout.write('\u001b[1;3H');
3376 runner.on('end', this.epilogue.bind(this));
3380 * Inherit from `Base.prototype`.
3384 F.prototype = Base.prototype;
3385 Min.prototype = new F;
3386 Min.prototype.constructor = Min;
3389 }); // module: reporters/min.js
3391 require.register("reporters/nyan.js", function(module, exports, require){
3393 * Module dependencies.
3396 var Base = require('./base')
3397 , color = Base.color;
3403 exports = module.exports = NyanCat;
3406 * Initialize a new `Dot` matrix test reporter.
3408 * @param {Runner} runner
3412 function NyanCat(runner) {
3413 Base.call(this, runner);
3415 , stats = this.stats
3416 , width = Base.window.width * .75 | 0
3417 , rainbowColors = this.rainbowColors = self.generateColors()
3418 , colorIndex = this.colorIndex = 0
3419 , numerOfLines = this.numberOfLines = 4
3420 , trajectories = this.trajectories = [[], [], [], []]
3421 , nyanCatWidth = this.nyanCatWidth = 11
3422 , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth)
3423 , scoreboardWidth = this.scoreboardWidth = 5
3424 , tick = this.tick = 0
3427 runner.on('start', function(){
3432 runner.on('pending', function(test){
3436 runner.on('pass', function(test){
3440 runner.on('fail', function(test, err){
3444 runner.on('end', function(){
3446 for (var i = 0; i < self.numberOfLines; i++) write('\n');
3457 NyanCat.prototype.draw = function(){
3458 this.appendRainbow();
3459 this.drawScoreboard();
3462 this.tick = !this.tick;
3466 * Draw the "scoreboard" showing the number
3467 * of passes, failures and pending tests.
3472 NyanCat.prototype.drawScoreboard = function(){
3473 var stats = this.stats;
3474 var colors = Base.colors;
3476 function draw(color, n) {
3478 write('\u001b[' + color + 'm' + n + '\u001b[0m');
3482 draw(colors.green, stats.passes);
3483 draw(colors.fail, stats.failures);
3484 draw(colors.pending, stats.pending);
3487 this.cursorUp(this.numberOfLines);
3491 * Append the rainbow.
3496 NyanCat.prototype.appendRainbow = function(){
3497 var segment = this.tick ? '_' : '-';
3498 var rainbowified = this.rainbowify(segment);
3500 for (var index = 0; index < this.numberOfLines; index++) {
3501 var trajectory = this.trajectories[index];
3502 if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift();
3503 trajectory.push(rainbowified);
3513 NyanCat.prototype.drawRainbow = function(){
3516 this.trajectories.forEach(function(line, index) {
3517 write('\u001b[' + self.scoreboardWidth + 'C');
3518 write(line.join(''));
3522 this.cursorUp(this.numberOfLines);
3531 NyanCat.prototype.drawNyanCat = function() {
3533 var startWidth = this.scoreboardWidth + this.trajectories[0].length;
3534 var color = '\u001b[' + startWidth + 'C';
3542 padding = self.tick ? ' ' : ' ';
3543 write('_|' + padding + '/\\_/\\ ');
3547 padding = self.tick ? '_' : '__';
3548 var tail = self.tick ? '~' : '^';
3550 write(tail + '|' + padding + this.face() + ' ');
3554 padding = self.tick ? ' ' : ' ';
3555 write(padding + '"" "" ');
3558 this.cursorUp(this.numberOfLines);
3562 * Draw nyan cat face.
3568 NyanCat.prototype.face = function() {
3569 var stats = this.stats;
3570 if (stats.failures) {
3572 } else if (stats.pending) {
3574 } else if(stats.passes) {
3582 * Move cursor up `n`.
3588 NyanCat.prototype.cursorUp = function(n) {
3589 write('\u001b[' + n + 'A');
3593 * Move cursor down `n`.
3599 NyanCat.prototype.cursorDown = function(n) {
3600 write('\u001b[' + n + 'B');
3604 * Generate rainbow colors.
3610 NyanCat.prototype.generateColors = function(){
3613 for (var i = 0; i < (6 * 7); i++) {
3614 var pi3 = Math.floor(Math.PI / 3);
3615 var n = (i * (1.0 / 6));
3616 var r = Math.floor(3 * Math.sin(n) + 3);
3617 var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
3618 var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
3619 colors.push(36 * r + 6 * g + b + 16);
3626 * Apply rainbow to the given `str`.
3628 * @param {String} str
3633 NyanCat.prototype.rainbowify = function(str){
3634 var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
3635 this.colorIndex += 1;
3636 return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
3643 function write(string) {
3644 process.stdout.write(string);
3648 * Inherit from `Base.prototype`.
3652 F.prototype = Base.prototype;
3653 NyanCat.prototype = new F;
3654 NyanCat.prototype.constructor = NyanCat;
3657 }); // module: reporters/nyan.js
3659 require.register("reporters/progress.js", function(module, exports, require){
3662 * Module dependencies.
3665 var Base = require('./base')
3666 , cursor = Base.cursor
3667 , color = Base.color;
3670 * Expose `Progress`.
3673 exports = module.exports = Progress;
3676 * General progress bar color.
3679 Base.colors.progress = 90;
3682 * Initialize a new `Progress` bar test reporter.
3684 * @param {Runner} runner
3685 * @param {Object} options
3689 function Progress(runner, options) {
3690 Base.call(this, runner);
3693 , options = options || {}
3694 , stats = this.stats
3695 , width = Base.window.width * .50 | 0
3696 , total = runner.total
3701 options.open = options.open || '[';
3702 options.complete = options.complete || 'â–¬';
3703 options.incomplete = options.incomplete || Base.symbols.dot;
3704 options.close = options.close || ']';
3705 options.verbose = false;
3708 runner.on('start', function(){
3714 runner.on('test end', function(){
3716 var incomplete = total - complete
3717 , percent = complete / total
3718 , n = width * percent | 0
3722 process.stdout.write('\u001b[J');
3723 process.stdout.write(color('progress', ' ' + options.open));
3724 process.stdout.write(Array(n).join(options.complete));
3725 process.stdout.write(Array(i).join(options.incomplete));
3726 process.stdout.write(color('progress', options.close));
3727 if (options.verbose) {
3728 process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
3732 // tests are complete, output some stats
3733 // and the failures if any
3734 runner.on('end', function(){
3742 * Inherit from `Base.prototype`.
3746 F.prototype = Base.prototype;
3747 Progress.prototype = new F;
3748 Progress.prototype.constructor = Progress;
3751 }); // module: reporters/progress.js
3753 require.register("reporters/spec.js", function(module, exports, require){
3756 * Module dependencies.
3759 var Base = require('./base')
3760 , cursor = Base.cursor
3761 , color = Base.color;
3767 exports = module.exports = Spec;
3770 * Initialize a new `Spec` test reporter.
3772 * @param {Runner} runner
3776 function Spec(runner) {
3777 Base.call(this, runner);
3780 , stats = this.stats
3785 return Array(indents).join(' ')
3788 runner.on('start', function(){
3792 runner.on('suite', function(suite){
3794 console.log(color('suite', '%s%s'), indent(), suite.title);
3797 runner.on('suite end', function(suite){
3799 if (1 == indents) console.log();
3802 runner.on('test', function(test){
3803 process.stdout.write(indent() + color('pass', ' â—¦ ' + test.title + ': '));
3806 runner.on('pending', function(test){
3807 var fmt = indent() + color('pending', ' - %s');
3808 console.log(fmt, test.title);
3811 runner.on('pass', function(test){
3812 if ('fast' == test.speed) {
3814 + color('checkmark', ' ' + Base.symbols.ok)
3815 + color('pass', ' %s ');
3817 console.log(fmt, test.title);
3820 + color('checkmark', ' ' + Base.symbols.ok)
3821 + color('pass', ' %s ')
3822 + color(test.speed, '(%dms)');
3824 console.log(fmt, test.title, test.duration);
3828 runner.on('fail', function(test, err){
3830 console.log(indent() + color('fail', ' %d) %s'), ++n, test.title);
3833 runner.on('end', self.epilogue.bind(self));
3837 * Inherit from `Base.prototype`.
3841 F.prototype = Base.prototype;
3842 Spec.prototype = new F;
3843 Spec.prototype.constructor = Spec;
3846 }); // module: reporters/spec.js
3848 require.register("reporters/tap.js", function(module, exports, require){
3851 * Module dependencies.
3854 var Base = require('./base')
3855 , cursor = Base.cursor
3856 , color = Base.color;
3862 exports = module.exports = TAP;
3865 * Initialize a new `TAP` reporter.
3867 * @param {Runner} runner
3871 function TAP(runner) {
3872 Base.call(this, runner);
3875 , stats = this.stats
3880 runner.on('start', function(){
3881 var total = runner.grepTotal(runner.suite);
3882 console.log('%d..%d', 1, total);
3885 runner.on('test end', function(){
3889 runner.on('pending', function(test){
3890 console.log('ok %d %s # SKIP -', n, title(test));
3893 runner.on('pass', function(test){
3895 console.log('ok %d %s', n, title(test));
3898 runner.on('fail', function(test, err){
3900 console.log('not ok %d %s', n, title(test));
3901 if (err.stack) console.log(err.stack.replace(/^/gm, ' '));
3904 runner.on('end', function(){
3905 console.log('# tests ' + (passes + failures));
3906 console.log('# pass ' + passes);
3907 console.log('# fail ' + failures);
3912 * Return a TAP-safe title of `test`
3914 * @param {Object} test
3919 function title(test) {
3920 return test.fullTitle().replace(/#/g, '');
3923 }); // module: reporters/tap.js
3925 require.register("reporters/xunit.js", function(module, exports, require){
3928 * Module dependencies.
3931 var Base = require('./base')
3932 , utils = require('../utils')
3933 , escape = utils.escape;
3936 * Save timer references to avoid Sinon interfering (see GH-237).
3939 var Date = global.Date
3940 , setTimeout = global.setTimeout
3941 , setInterval = global.setInterval
3942 , clearTimeout = global.clearTimeout
3943 , clearInterval = global.clearInterval;
3949 exports = module.exports = XUnit;
3952 * Initialize a new `XUnit` reporter.
3954 * @param {Runner} runner
3958 function XUnit(runner) {
3959 Base.call(this, runner);
3960 var stats = this.stats
3964 runner.on('pass', function(test){
3968 runner.on('fail', function(test){
3972 runner.on('end', function(){
3973 console.log(tag('testsuite', {
3975 , tests: stats.tests
3976 , failures: stats.failures
3977 , errors: stats.failures
3978 , skipped: stats.tests - stats.failures - stats.passes
3979 , timestamp: (new Date).toUTCString()
3980 , time: (stats.duration / 1000) || 0
3983 tests.forEach(test);
3984 console.log('</testsuite>');
3989 * Inherit from `Base.prototype`.
3993 F.prototype = Base.prototype;
3994 XUnit.prototype = new F;
3995 XUnit.prototype.constructor = XUnit;
3999 * Output tag for the given `test.`
4002 function test(test) {
4004 classname: test.parent.fullTitle()
4006 , time: test.duration / 1000
4009 if ('failed' == test.state) {
4011 attrs.message = escape(err.message);
4012 console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack))));
4013 } else if (test.pending) {
4014 console.log(tag('testcase', attrs, false, tag('skipped', {}, true)));
4016 console.log(tag('testcase', attrs, true) );
4024 function tag(name, attrs, close, content) {
4025 var end = close ? '/>' : '>'
4029 for (var key in attrs) {
4030 pairs.push(key + '="' + escape(attrs[key]) + '"');
4033 tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
4034 if (content) tag += content + '</' + name + end;
4039 * Return cdata escaped CDATA `str`.
4042 function cdata(str) {
4043 return '<![CDATA[' + escape(str) + ']]>';
4046 }); // module: reporters/xunit.js
4048 require.register("runnable.js", function(module, exports, require){
4051 * Module dependencies.
4054 var EventEmitter = require('browser/events').EventEmitter
4055 , debug = require('browser/debug')('mocha:runnable')
4056 , milliseconds = require('./ms');
4059 * Save timer references to avoid Sinon interfering (see GH-237).
4062 var Date = global.Date
4063 , setTimeout = global.setTimeout
4064 , setInterval = global.setInterval
4065 , clearTimeout = global.clearTimeout
4066 , clearInterval = global.clearInterval;
4069 * Object#toString().
4072 var toString = Object.prototype.toString;
4075 * Expose `Runnable`.
4078 module.exports = Runnable;
4081 * Initialize a new `Runnable` with the given `title` and callback `fn`.
4083 * @param {String} title
4084 * @param {Function} fn
4088 function Runnable(title, fn) {
4091 this.async = fn && fn.length;
4092 this.sync = ! this.async;
4093 this._timeout = 2000;
4095 this.timedOut = false;
4099 * Inherit from `EventEmitter.prototype`.
4103 F.prototype = EventEmitter.prototype;
4104 Runnable.prototype = new F;
4105 Runnable.prototype.constructor = Runnable;
4109 * Set & get timeout `ms`.
4111 * @param {Number|String} ms
4112 * @return {Runnable|Number} ms or self
4116 Runnable.prototype.timeout = function(ms){
4117 if (0 == arguments.length) return this._timeout;
4118 if ('string' == typeof ms) ms = milliseconds(ms);
4119 debug('timeout %d', ms);
4121 if (this.timer) this.resetTimeout();
4126 * Set & get slow `ms`.
4128 * @param {Number|String} ms
4129 * @return {Runnable|Number} ms or self
4133 Runnable.prototype.slow = function(ms){
4134 if (0 === arguments.length) return this._slow;
4135 if ('string' == typeof ms) ms = milliseconds(ms);
4136 debug('timeout %d', ms);
4142 * Return the full title generated by recursively
4143 * concatenating the parent's full title.
4149 Runnable.prototype.fullTitle = function(){
4150 return this.parent.fullTitle() + ' ' + this.title;
4154 * Clear the timeout.
4159 Runnable.prototype.clearTimeout = function(){
4160 clearTimeout(this.timer);
4164 * Inspect the runnable void of private properties.
4170 Runnable.prototype.inspect = function(){
4171 return JSON.stringify(this, function(key, val){
4172 if ('_' == key[0]) return;
4173 if ('parent' == key) return '#<Suite>';
4174 if ('ctx' == key) return '#<Context>';
4180 * Reset the timeout.
4185 Runnable.prototype.resetTimeout = function(){
4187 var ms = this.timeout() || 1e9;
4189 this.clearTimeout();
4190 this.timer = setTimeout(function(){
4191 self.callback(new Error('timeout of ' + ms + 'ms exceeded'));
4192 self.timedOut = true;
4197 * Run the test and invoke `fn(err)`.
4199 * @param {Function} fn
4203 Runnable.prototype.run = function(fn){
4205 , ms = this.timeout()
4211 if (ctx) ctx.runnable(this);
4216 this.timer = setTimeout(function(){
4217 done(new Error('timeout of ' + ms + 'ms exceeded'));
4218 self.timedOut = true;
4223 // called multiple times
4224 function multiple(err) {
4225 if (emitted) return;
4227 self.emit('error', err || new Error('done() called multiple times'));
4231 function done(err) {
4232 if (self.timedOut) return;
4233 if (finished) return multiple(err);
4234 self.clearTimeout();
4235 self.duration = new Date - start;
4240 // for .resetTimeout()
4241 this.callback = done;
4246 this.fn.call(ctx, function(err){
4247 if (err instanceof Error || toString.call(err) === "[object Error]") return done(err);
4248 if (null != err) return done(new Error('done() invoked with non-Error: ' + err));
4257 if (this.asyncOnly) {
4258 return done(new Error('--async-only option in use without declaring `done()`'));
4263 if (!this.pending) this.fn.call(ctx);
4264 this.duration = new Date - start;
4271 }); // module: runnable.js
4273 require.register("runner.js", function(module, exports, require){
4275 * Module dependencies.
4278 var EventEmitter = require('browser/events').EventEmitter
4279 , debug = require('browser/debug')('mocha:runner')
4280 , Test = require('./test')
4281 , utils = require('./utils')
4282 , filter = utils.filter
4283 , keys = utils.keys;
4286 * Non-enumerable globals.
4302 module.exports = Runner;
4305 * Initialize a `Runner` for the given `suite`.
4309 * - `start` execution started
4310 * - `end` execution complete
4311 * - `suite` (suite) test suite execution started
4312 * - `suite end` (suite) all tests (and sub-suites) have finished
4313 * - `test` (test) test execution started
4314 * - `test end` (test) test completed
4315 * - `hook` (hook) hook execution started
4316 * - `hook end` (hook) hook complete
4317 * - `pass` (test) test passed
4318 * - `fail` (test, err) test failed
4319 * - `pending` (test) test pending
4324 function Runner(suite) {
4328 this.total = suite.total();
4330 this.on('test end', function(test){ self.checkGlobals(test); });
4331 this.on('hook end', function(hook){ self.checkGlobals(hook); });
4333 this.globals(this.globalProps().concat(['errno']));
4337 * Wrapper for setImmediate, process.nextTick, or browser polyfill.
4339 * @param {Function} fn
4343 Runner.immediately = global.setImmediate || process.nextTick;
4346 * Inherit from `EventEmitter.prototype`.
4350 F.prototype = EventEmitter.prototype;
4351 Runner.prototype = new F;
4352 Runner.prototype.constructor = Runner;
4356 * Run tests with full titles matching `re`. Updates runner.total
4357 * with number of tests matched.
4359 * @param {RegExp} re
4360 * @param {Boolean} invert
4361 * @return {Runner} for chaining
4365 Runner.prototype.grep = function(re, invert){
4366 debug('grep %s', re);
4368 this._invert = invert;
4369 this.total = this.grepTotal(this.suite);
4374 * Returns the number of tests matching the grep search for the
4377 * @param {Suite} suite
4382 Runner.prototype.grepTotal = function(suite) {
4386 suite.eachTest(function(test){
4387 var match = self._grep.test(test.fullTitle());
4388 if (self._invert) match = !match;
4396 * Return a list of global properties.
4402 Runner.prototype.globalProps = function() {
4403 var props = utils.keys(global);
4406 for (var i = 0; i < globals.length; ++i) {
4407 if (~utils.indexOf(props, globals[i])) continue;
4408 props.push(globals[i]);
4415 * Allow the given `arr` of globals.
4417 * @param {Array} arr
4418 * @return {Runner} for chaining
4422 Runner.prototype.globals = function(arr){
4423 if (0 == arguments.length) return this._globals;
4424 debug('globals %j', arr);
4425 utils.forEach(arr, function(arr){
4426 this._globals.push(arr);
4432 * Check for global variable leaks.
4437 Runner.prototype.checkGlobals = function(test){
4438 if (this.ignoreLeaks) return;
4439 var ok = this._globals;
4440 var globals = this.globalProps();
4441 var isNode = process.kill;
4444 // check length - 2 ('errno' and 'location' globals)
4445 if (isNode && 1 == ok.length - globals.length) return;
4446 else if (2 == ok.length - globals.length) return;
4448 if(this.prevGlobalsLength == globals.length) return;
4449 this.prevGlobalsLength = globals.length;
4451 leaks = filterLeaks(ok, globals);
4452 this._globals = this._globals.concat(leaks);
4454 if (leaks.length > 1) {
4455 this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + ''));
4456 } else if (leaks.length) {
4457 this.fail(test, new Error('global leak detected: ' + leaks[0]));
4462 * Fail the given `test`.
4464 * @param {Test} test
4465 * @param {Error} err
4469 Runner.prototype.fail = function(test, err){
4471 test.state = 'failed';
4473 if ('string' == typeof err) {
4474 err = new Error('the string "' + err + '" was thrown, throw an Error :)');
4477 this.emit('fail', test, err);
4481 * Fail the given `hook` with `err`.
4483 * Hook failures (currently) hard-end due
4484 * to that fact that a failing hook will
4485 * surely cause subsequent tests to fail,
4486 * causing jumbled reporting.
4488 * @param {Hook} hook
4489 * @param {Error} err
4493 Runner.prototype.failHook = function(hook, err){
4494 this.fail(hook, err);
4499 * Run hook `name` callbacks and then invoke `fn()`.
4501 * @param {String} name
4502 * @param {Function} function
4506 Runner.prototype.hook = function(name, fn){
4507 var suite = this.suite
4508 , hooks = suite['_' + name]
4513 var hook = hooks[i];
4514 if (!hook) return fn();
4515 if (self.failures && suite.bail()) return fn();
4516 self.currentRunnable = hook;
4518 hook.ctx.currentTest = self.test;
4520 self.emit('hook', hook);
4522 hook.on('error', function(err){
4523 self.failHook(hook, err);
4526 hook.run(function(err){
4527 hook.removeAllListeners('error');
4528 var testError = hook.error();
4529 if (testError) self.fail(self.test, testError);
4530 if (err) return self.failHook(hook, err);
4531 self.emit('hook end', hook);
4532 delete hook.ctx.currentTest;
4537 Runner.immediately(function(){
4543 * Run hook `name` for the given array of `suites`
4544 * in order, and callback `fn(err)`.
4546 * @param {String} name
4547 * @param {Array} suites
4548 * @param {Function} fn
4552 Runner.prototype.hooks = function(name, suites, fn){
4554 , orig = this.suite;
4556 function next(suite) {
4564 self.hook(name, function(err){
4578 * Run hooks from the top level down.
4580 * @param {String} name
4581 * @param {Function} fn
4585 Runner.prototype.hookUp = function(name, fn){
4586 var suites = [this.suite].concat(this.parents()).reverse();
4587 this.hooks(name, suites, fn);
4591 * Run hooks from the bottom up.
4593 * @param {String} name
4594 * @param {Function} fn
4598 Runner.prototype.hookDown = function(name, fn){
4599 var suites = [this.suite].concat(this.parents());
4600 this.hooks(name, suites, fn);
4604 * Return an array of parent Suites from
4605 * closest to furthest.
4611 Runner.prototype.parents = function(){
4612 var suite = this.suite
4614 while (suite = suite.parent) suites.push(suite);
4619 * Run the current test and callback `fn(err)`.
4621 * @param {Function} fn
4625 Runner.prototype.runTest = function(fn){
4626 var test = this.test
4629 if (this.asyncOnly) test.asyncOnly = true;
4632 test.on('error', function(err){
4633 self.fail(test, err);
4642 * Run tests in the given `suite` and invoke
4643 * the callback `fn()` when complete.
4645 * @param {Suite} suite
4646 * @param {Function} fn
4650 Runner.prototype.runTests = function(suite, fn){
4652 , tests = suite.tests.slice()
4655 function next(err) {
4656 // if we bail after first err
4657 if (self.failures && suite._bail) return fn();
4660 test = tests.shift();
4663 if (!test) return fn();
4666 var match = self._grep.test(test.fullTitle());
4667 if (self._invert) match = !match;
4668 if (!match) return next();
4672 self.emit('pending', test);
4673 self.emit('test end', test);
4677 // execute test and hook(s)
4678 self.emit('test', self.test = test);
4679 self.hookDown('beforeEach', function(){
4680 self.currentRunnable = self.test;
4681 self.runTest(function(err){
4685 self.fail(test, err);
4686 self.emit('test end', test);
4687 return self.hookUp('afterEach', next);
4690 test.state = 'passed';
4691 self.emit('pass', test);
4692 self.emit('test end', test);
4693 self.hookUp('afterEach', next);
4703 * Run the given `suite` and invoke the
4704 * callback `fn()` when complete.
4706 * @param {Suite} suite
4707 * @param {Function} fn
4711 Runner.prototype.runSuite = function(suite, fn){
4712 var total = this.grepTotal(suite)
4716 debug('run suite %s', suite.fullTitle());
4718 if (!total) return fn();
4720 this.emit('suite', this.suite = suite);
4723 var curr = suite.suites[i++];
4724 if (!curr) return done();
4725 self.runSuite(curr, next);
4730 self.hook('afterAll', function(){
4731 self.emit('suite end', suite);
4736 this.hook('beforeAll', function(){
4737 self.runTests(suite, next);
4742 * Handle uncaught exceptions.
4744 * @param {Error} err
4748 Runner.prototype.uncaught = function(err){
4749 debug('uncaught exception %s', err.message);
4750 var runnable = this.currentRunnable;
4751 if (!runnable || 'failed' == runnable.state) return;
4752 runnable.clearTimeout();
4753 err.uncaught = true;
4754 this.fail(runnable, err);
4756 // recover from test
4757 if ('test' == runnable.type) {
4758 this.emit('test end', runnable);
4759 this.hookUp('afterEach', this.next);
4768 * Run the root suite and invoke `fn(failures)`
4771 * @param {Function} fn
4772 * @return {Runner} for chaining
4776 Runner.prototype.run = function(fn){
4778 , fn = fn || function(){};
4780 function uncaught(err){
4787 this.on('end', function(){
4789 process.removeListener('uncaughtException', uncaught);
4795 this.runSuite(this.suite, function(){
4796 debug('finished running');
4800 // uncaught exception
4801 process.on('uncaughtException', uncaught);
4807 * Filter leaks with the given globals flagged as `ok`.
4810 * @param {Array} globals
4815 function filterLeaks(ok, globals) {
4816 return filter(globals, function(key){
4817 // Firefox and Chrome exposes iframes as index inside the window object
4818 if (/^d+/.test(key)) return false;
4821 // if runner runs in an iframe, this iframe's window.getInterface method not init at first
4822 // it is assigned in some seconds
4823 if (global.navigator && /^getInterface/.test(key)) return false;
4825 // an iframe could be approached by window[iframeIndex]
4826 // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak
4827 if (global.navigator && /^\d+/.test(key)) return false;
4829 // Opera and IE expose global variables for HTML element IDs (issue #243)
4830 if (/^mocha-/.test(key)) return false;
4832 var matched = filter(ok, function(ok){
4833 if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]);
4836 return matched.length == 0 && (!global.navigator || 'onerror' !== key);
4840 }); // module: runner.js
4842 require.register("suite.js", function(module, exports, require){
4845 * Module dependencies.
4848 var EventEmitter = require('browser/events').EventEmitter
4849 , debug = require('browser/debug')('mocha:suite')
4850 , milliseconds = require('./ms')
4851 , utils = require('./utils')
4852 , Hook = require('./hook');
4858 exports = module.exports = Suite;
4861 * Create a new `Suite` with the given `title`
4862 * and parent `Suite`. When a suite with the
4863 * same title is already present, that suite
4864 * is returned to provide nicer reporter
4865 * and more flexible meta-testing.
4867 * @param {Suite} parent
4868 * @param {String} title
4873 exports.create = function(parent, title){
4874 var suite = new Suite(title, parent.ctx);
4875 suite.parent = parent;
4876 if (parent.pending) suite.pending = true;
4877 title = suite.fullTitle();
4878 parent.addSuite(suite);
4883 * Initialize a new `Suite` with the given
4884 * `title` and `ctx`.
4886 * @param {String} title
4887 * @param {Context} ctx
4891 function Suite(title, ctx) {
4896 this.pending = false;
4897 this._beforeEach = [];
4898 this._beforeAll = [];
4899 this._afterEach = [];
4900 this._afterAll = [];
4902 this._timeout = 2000;
4908 * Inherit from `EventEmitter.prototype`.
4912 F.prototype = EventEmitter.prototype;
4913 Suite.prototype = new F;
4914 Suite.prototype.constructor = Suite;
4918 * Return a clone of this `Suite`.
4924 Suite.prototype.clone = function(){
4925 var suite = new Suite(this.title);
4927 suite.ctx = this.ctx;
4928 suite.timeout(this.timeout());
4929 suite.slow(this.slow());
4930 suite.bail(this.bail());
4935 * Set timeout `ms` or short-hand such as "2s".
4937 * @param {Number|String} ms
4938 * @return {Suite|Number} for chaining
4942 Suite.prototype.timeout = function(ms){
4943 if (0 == arguments.length) return this._timeout;
4944 if ('string' == typeof ms) ms = milliseconds(ms);
4945 debug('timeout %d', ms);
4946 this._timeout = parseInt(ms, 10);
4951 * Set slow `ms` or short-hand such as "2s".
4953 * @param {Number|String} ms
4954 * @return {Suite|Number} for chaining
4958 Suite.prototype.slow = function(ms){
4959 if (0 === arguments.length) return this._slow;
4960 if ('string' == typeof ms) ms = milliseconds(ms);
4961 debug('slow %d', ms);
4967 * Sets whether to bail after first error.
4969 * @parma {Boolean} bail
4970 * @return {Suite|Number} for chaining
4974 Suite.prototype.bail = function(bail){
4975 if (0 == arguments.length) return this._bail;
4976 debug('bail %s', bail);
4982 * Run `fn(test[, done])` before running tests.
4984 * @param {Function} fn
4985 * @return {Suite} for chaining
4989 Suite.prototype.beforeAll = function(fn){
4990 if (this.pending) return this;
4991 var hook = new Hook('"before all" hook', fn);
4993 hook.timeout(this.timeout());
4994 hook.slow(this.slow());
4995 hook.ctx = this.ctx;
4996 this._beforeAll.push(hook);
4997 this.emit('beforeAll', hook);
5002 * Run `fn(test[, done])` after running tests.
5004 * @param {Function} fn
5005 * @return {Suite} for chaining
5009 Suite.prototype.afterAll = function(fn){
5010 if (this.pending) return this;
5011 var hook = new Hook('"after all" hook', fn);
5013 hook.timeout(this.timeout());
5014 hook.slow(this.slow());
5015 hook.ctx = this.ctx;
5016 this._afterAll.push(hook);
5017 this.emit('afterAll', hook);
5022 * Run `fn(test[, done])` before each test case.
5024 * @param {Function} fn
5025 * @return {Suite} for chaining
5029 Suite.prototype.beforeEach = function(fn){
5030 if (this.pending) return this;
5031 var hook = new Hook('"before each" hook', fn);
5033 hook.timeout(this.timeout());
5034 hook.slow(this.slow());
5035 hook.ctx = this.ctx;
5036 this._beforeEach.push(hook);
5037 this.emit('beforeEach', hook);
5042 * Run `fn(test[, done])` after each test case.
5044 * @param {Function} fn
5045 * @return {Suite} for chaining
5049 Suite.prototype.afterEach = function(fn){
5050 if (this.pending) return this;
5051 var hook = new Hook('"after each" hook', fn);
5053 hook.timeout(this.timeout());
5054 hook.slow(this.slow());
5055 hook.ctx = this.ctx;
5056 this._afterEach.push(hook);
5057 this.emit('afterEach', hook);
5062 * Add a test `suite`.
5064 * @param {Suite} suite
5065 * @return {Suite} for chaining
5069 Suite.prototype.addSuite = function(suite){
5070 suite.parent = this;
5071 suite.timeout(this.timeout());
5072 suite.slow(this.slow());
5073 suite.bail(this.bail());
5074 this.suites.push(suite);
5075 this.emit('suite', suite);
5080 * Add a `test` to this suite.
5082 * @param {Test} test
5083 * @return {Suite} for chaining
5087 Suite.prototype.addTest = function(test){
5089 test.timeout(this.timeout());
5090 test.slow(this.slow());
5091 test.ctx = this.ctx;
5092 this.tests.push(test);
5093 this.emit('test', test);
5098 * Return the full title generated by recursively
5099 * concatenating the parent's full title.
5105 Suite.prototype.fullTitle = function(){
5107 var full = this.parent.fullTitle();
5108 if (full) return full + ' ' + this.title;
5114 * Return the total number of tests.
5120 Suite.prototype.total = function(){
5121 return utils.reduce(this.suites, function(sum, suite){
5122 return sum + suite.total();
5123 }, 0) + this.tests.length;
5127 * Iterates through each suite recursively to find
5128 * all tests. Applies a function in the format
5131 * @param {Function} fn
5136 Suite.prototype.eachTest = function(fn){
5137 utils.forEach(this.tests, fn);
5138 utils.forEach(this.suites, function(suite){
5144 }); // module: suite.js
5146 require.register("test.js", function(module, exports, require){
5149 * Module dependencies.
5152 var Runnable = require('./runnable');
5158 module.exports = Test;
5161 * Initialize a new `Test` with the given `title` and callback `fn`.
5163 * @param {String} title
5164 * @param {Function} fn
5168 function Test(title, fn) {
5169 Runnable.call(this, title, fn);
5175 * Inherit from `Runnable.prototype`.
5179 F.prototype = Runnable.prototype;
5180 Test.prototype = new F;
5181 Test.prototype.constructor = Test;
5184 }); // module: test.js
5186 require.register("utils.js", function(module, exports, require){
5188 * Module dependencies.
5191 var fs = require('browser/fs')
5192 , path = require('browser/path')
5194 , debug = require('browser/debug')('mocha:watch');
5197 * Ignored directories.
5200 var ignore = ['node_modules', '.git'];
5203 * Escape special characters in the given string of html.
5205 * @param {String} html
5210 exports.escape = function(html){
5212 .replace(/&/g, '&')
5213 .replace(/"/g, '"')
5214 .replace(/</g, '<')
5215 .replace(/>/g, '>');
5219 * Array#forEach (<=IE8)
5221 * @param {Array} array
5222 * @param {Function} fn
5223 * @param {Object} scope
5227 exports.forEach = function(arr, fn, scope){
5228 for (var i = 0, l = arr.length; i < l; i++)
5229 fn.call(scope, arr[i], i);
5233 * Array#indexOf (<=IE8)
5235 * @parma {Array} arr
5236 * @param {Object} obj to find index of
5237 * @param {Number} start
5241 exports.indexOf = function(arr, obj, start){
5242 for (var i = start || 0, l = arr.length; i < l; i++) {
5250 * Array#reduce (<=IE8)
5252 * @param {Array} array
5253 * @param {Function} fn
5254 * @param {Object} initial value
5258 exports.reduce = function(arr, fn, val){
5261 for (var i = 0, l = arr.length; i < l; i++) {
5262 rval = fn(rval, arr[i], i, arr);
5269 * Array#filter (<=IE8)
5271 * @param {Array} array
5272 * @param {Function} fn
5276 exports.filter = function(arr, fn){
5279 for (var i = 0, l = arr.length; i < l; i++) {
5281 if (fn(val, i, arr)) ret.push(val);
5288 * Object.keys (<=IE8)
5290 * @param {Object} obj
5291 * @return {Array} keys
5295 exports.keys = Object.keys || function(obj) {
5297 , has = Object.prototype.hasOwnProperty // for `window` on <=IE8
5299 for (var key in obj) {
5300 if (has.call(obj, key)) {
5309 * Watch the given `files` for changes
5310 * and invoke `fn(file)` on modification.
5312 * @param {Array} files
5313 * @param {Function} fn
5317 exports.watch = function(files, fn){
5318 var options = { interval: 100 };
5319 files.forEach(function(file){
5320 debug('file %s', file);
5321 fs.watchFile(file, options, function(curr, prev){
5322 if (prev.mtime < curr.mtime) fn(file);
5331 function ignored(path){
5332 return !~ignore.indexOf(path);
5336 * Lookup files in the given `dir`.
5342 exports.files = function(dir, ret){
5347 .forEach(function(path){
5348 path = join(dir, path);
5349 if (fs.statSync(path).isDirectory()) {
5350 exports.files(path, ret);
5351 } else if (path.match(/\.(js|coffee|litcoffee|coffee.md)$/)) {
5360 * Compute a slug from the given `str`.
5362 * @param {String} str
5367 exports.slug = function(str){
5370 .replace(/ +/g, '-')
5371 .replace(/[^-\w]/g, '');
5375 * Strip the function definition from `str`,
5376 * and re-indent for pre whitespace.
5379 exports.clean = function(str) {
5381 .replace(/^function *\(.*\) *{/, '')
5382 .replace(/\s+\}$/, '');
5384 var whitespace = str.match(/^\n?(\s*)/)[1]
5385 , re = new RegExp('^' + whitespace, 'gm');
5387 str = str.replace(re, '');
5389 return exports.trim(str);
5393 * Escape regular expression characters in `str`.
5395 * @param {String} str
5400 exports.escapeRegexp = function(str){
5401 return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
5405 * Trim the given `str`.
5407 * @param {String} str
5412 exports.trim = function(str){
5413 return str.replace(/^\s+|\s+$/g, '');
5417 * Parse the given `qs`.
5419 * @param {String} qs
5424 exports.parseQuery = function(qs){
5425 return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){
5426 var i = pair.indexOf('=')
5427 , key = pair.slice(0, i)
5428 , val = pair.slice(++i);
5430 obj[key] = decodeURIComponent(val);
5436 * Highlight the given string of `js`.
5438 * @param {String} js
5443 function highlight(js) {
5445 .replace(/</g, '<')
5446 .replace(/>/g, '>')
5447 .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
5448 .replace(/('.*?')/gm, '<span class="string">$1</span>')
5449 .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
5450 .replace(/(\d+)/gm, '<span class="number">$1</span>')
5451 .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
5452 .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
5456 * Highlight the contents of tag `name`.
5458 * @param {String} name
5462 exports.highlightTags = function(name) {
5463 var code = document.getElementsByTagName(name);
5464 for (var i = 0, len = code.length; i < len; ++i) {
5465 code[i].innerHTML = highlight(code[i].innerHTML);
5469 }); // module: utils.js
5470 // The global object is "self" in Web Workers.
5471 global = (function() { return this; })();
5474 * Save timer references to avoid Sinon interfering (see GH-237).
5477 var Date = global.Date;
5478 var setTimeout = global.setTimeout;
5479 var setInterval = global.setInterval;
5480 var clearTimeout = global.clearTimeout;
5481 var clearInterval = global.clearInterval;
5486 * These are meant only to allow
5487 * mocha.js to run untouched, not
5488 * to allow running node code in
5493 process.exit = function(status){};
5494 process.stdout = {};
5497 * Remove uncaughtException listener.
5500 process.removeListener = function(e){
5501 if ('uncaughtException' == e) {
5502 global.onerror = function() {};
5507 * Implements uncaughtException listener.
5510 process.on = function(e, fn){
5511 if ('uncaughtException' == e) {
5512 global.onerror = function(err, url, line){
5513 fn(new Error(err + ' (' + url + ':' + line + ')'));
5522 var Mocha = global.Mocha = require('mocha'),
5523 mocha = global.mocha = new Mocha({ reporter: 'html' });
5525 var immediateQueue = []
5528 function timeslice() {
5529 var immediateStart = new Date().getTime();
5530 while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) {
5531 immediateQueue.shift()();
5533 if (immediateQueue.length) {
5534 immediateTimeout = setTimeout(timeslice, 0);
5536 immediateTimeout = null;
5541 * High-performance override of Runner.immediately.
5544 Mocha.Runner.immediately = function(callback) {
5545 immediateQueue.push(callback);
5546 if (!immediateTimeout) {
5547 immediateTimeout = setTimeout(timeslice, 0);
5552 * Override ui to ensure that the ui functions are initialized.
5553 * Normally this would happen in Mocha.prototype.loadFiles.
5556 mocha.ui = function(ui){
5557 Mocha.prototype.ui.call(this, ui);
5558 this.suite.emit('pre-require', global, null, this);
5563 * Setup mocha with the given setting options.
5566 mocha.setup = function(opts){
5567 if ('string' == typeof opts) opts = { ui: opts };
5568 for (var opt in opts) this[opt](opts[opt]);
5573 * Run mocha, returning the Runner.
5576 mocha.run = function(fn){
5577 var options = mocha.options;
5578 mocha.globals('location');
5580 var query = Mocha.utils.parseQuery(global.location.search || '');
5581 if (query.grep) mocha.grep(query.grep);
5582 if (query.invert) mocha.invert();
5584 return Mocha.prototype.run.call(mocha, function(){
5585 // The DOM Document is not available in Web Workers.
5586 if (global.document) {
5587 Mocha.utils.highlightTags('code');
5594 * Expose the process shim.
5597 Mocha.process = process;