7 var path = require.resolve(p)
8 , mod = require.modules[path];
9 if (!mod) throw new Error('failed to require "' + p + '"');
12 mod.call(mod.exports, mod, mod.exports, require.relative(path));
19 require.resolve = function (path){
22 , index = path + '/index.js';
23 return require.modules[reg] && reg
24 || require.modules[index] && index
28 require.register = function (path, fn){
29 require.modules[path] = fn;
32 require.relative = function (parent) {
34 if ('.' != p.charAt(0)) return require(p);
36 var path = parent.split('/')
37 , segs = p.split('/');
40 for (var i = 0; i < segs.length; i++) {
42 if ('..' == seg) path.pop();
43 else if ('.' != seg) path.push(seg);
46 return require(path.join('/'));
51 require.register("browser/debug.js", function(module, exports, require){
53 module.exports = function(type){
58 }); // module: browser/debug.js
60 require.register("browser/diff.js", function(module, exports, require){
62 }); // module: browser/diff.js
64 require.register("browser/events.js", function(module, exports, require){
70 exports.EventEmitter = EventEmitter;
73 * Check if `obj` is an array.
76 function isArray(obj) {
77 return '[object Array]' == {}.toString.call(obj);
81 * Event emitter constructor.
86 function EventEmitter(){};
94 EventEmitter.prototype.on = function (name, fn) {
99 if (!this.$events[name]) {
100 this.$events[name] = fn;
101 } else if (isArray(this.$events[name])) {
102 this.$events[name].push(fn);
104 this.$events[name] = [this.$events[name], fn];
110 EventEmitter.prototype.addListener = EventEmitter.prototype.on;
113 * Adds a volatile listener.
118 EventEmitter.prototype.once = function (name, fn) {
122 self.removeListener(name, on);
123 fn.apply(this, arguments);
133 * Removes a listener.
138 EventEmitter.prototype.removeListener = function (name, fn) {
139 if (this.$events && this.$events[name]) {
140 var list = this.$events[name];
145 for (var i = 0, l = list.length; i < l; i++) {
146 if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
159 delete this.$events[name];
161 } else if (list === fn || (list.listener && list.listener === fn)) {
162 delete this.$events[name];
170 * Removes all listeners for an event.
175 EventEmitter.prototype.removeAllListeners = function (name) {
176 if (name === undefined) {
181 if (this.$events && this.$events[name]) {
182 this.$events[name] = null;
189 * Gets all listeners for a certain event.
194 EventEmitter.prototype.listeners = function (name) {
199 if (!this.$events[name]) {
200 this.$events[name] = [];
203 if (!isArray(this.$events[name])) {
204 this.$events[name] = [this.$events[name]];
207 return this.$events[name];
216 EventEmitter.prototype.emit = function (name) {
221 var handler = this.$events[name];
227 var args = [].slice.call(arguments, 1);
229 if ('function' == typeof handler) {
230 handler.apply(this, args);
231 } else if (isArray(handler)) {
232 var listeners = handler.slice();
234 for (var i = 0, l = listeners.length; i < l; i++) {
235 listeners[i].apply(this, args);
243 }); // module: browser/events.js
245 require.register("browser/fs.js", function(module, exports, require){
247 }); // module: browser/fs.js
249 require.register("browser/path.js", function(module, exports, require){
251 }); // module: browser/path.js
253 require.register("browser/progress.js", function(module, exports, require){
259 module.exports = Progress;
262 * Initialize a new `Progress` indicator.
265 function Progress() {
269 this.font('helvetica, arial, sans-serif');
273 * Set progress size to `n`.
276 * @return {Progress} for chaining
280 Progress.prototype.size = function(n){
288 * @param {String} str
289 * @return {Progress} for chaining
293 Progress.prototype.text = function(str){
299 * Set font size to `n`.
302 * @return {Progress} for chaining
306 Progress.prototype.fontSize = function(n){
314 * @param {String} family
315 * @return {Progress} for chaining
318 Progress.prototype.font = function(family){
324 * Update percentage to `n`.
327 * @return {Progress} for chaining
330 Progress.prototype.update = function(n){
338 * @param {CanvasRenderingContext2d} ctx
339 * @return {Progress} for chaining
342 Progress.prototype.draw = function(ctx){
343 var percent = Math.min(this.percent, 100)
349 , fontSize = this._fontSize;
351 ctx.font = fontSize + 'px ' + this._font;
353 var angle = Math.PI * 2 * (percent / 100);
354 ctx.clearRect(0, 0, size, size);
357 ctx.strokeStyle = '#9f9f9f';
359 ctx.arc(x, y, rad, 0, angle, false);
363 ctx.strokeStyle = '#eee';
365 ctx.arc(x, y, rad - 1, 0, angle, true);
369 var text = this._text || (percent | 0) + '%'
370 , w = ctx.measureText(text).width;
375 , y + fontSize / 2 - 1);
380 }); // module: browser/progress.js
382 require.register("browser/tty.js", function(module, exports, require){
384 exports.isatty = function(){
388 exports.getWindowSize = function(){
389 return [window.innerHeight, window.innerWidth];
391 }); // module: browser/tty.js
393 require.register("context.js", function(module, exports, require){
399 module.exports = Context;
402 * Initialize a new `Context`.
410 * Set the context `Runnable` to `runnable`.
412 * @param {Runnable} runnable
417 Context.prototype.runnable = function(runnable){
418 this._runnable = runnable;
423 * Set test timeout `ms`.
426 * @return {Context} self
430 Context.prototype.timeout = function(ms){
431 this._runnable.timeout(ms);
436 * Inspect the context void of `._runnable`.
442 Context.prototype.inspect = function(){
443 return JSON.stringify(this, function(key, val){
444 return '_runnable' == key
450 }); // module: context.js
452 require.register("hook.js", function(module, exports, require){
455 * Module dependencies.
458 var Runnable = require('./runnable');
464 module.exports = Hook;
467 * Initialize a new `Hook` with the given `title` and callback `fn`.
469 * @param {String} title
470 * @param {Function} fn
474 function Hook(title, fn) {
475 Runnable.call(this, title, fn);
480 * Inherit from `Runnable.prototype`.
483 Hook.prototype = new Runnable;
484 Hook.prototype.constructor = Hook;
487 }); // module: hook.js
489 require.register("interfaces/bdd.js", function(module, exports, require){
492 * Module dependencies.
495 var Suite = require('../suite')
496 , Test = require('../test');
499 * BDD-style interface:
501 * describe('Array', function(){
502 * describe('#indexOf()', function(){
503 * it('should return -1 when not present', function(){
507 * it('should return the index when present', function(){
515 module.exports = function(suite){
516 var suites = [suite];
518 suite.on('pre-require', function(context){
522 context.xdescribe = function(){};
523 context.xit = function(){};
526 * Execute before running tests.
529 context.before = function(fn){
530 suites[0].beforeAll(fn);
534 * Execute after running tests.
537 context.after = function(fn){
538 suites[0].afterAll(fn);
542 * Execute before each test case.
545 context.beforeEach = function(fn){
546 suites[0].beforeEach(fn);
550 * Execute after each test case.
553 context.afterEach = function(fn){
554 suites[0].afterEach(fn);
558 * Describe a "suite" with the given `title`
559 * and callback `fn` containing nested suites
563 context.describe = function(title, fn){
564 var suite = Suite.create(suites[0], title);
565 suites.unshift(suite);
571 * Describe a specification or test-case
572 * with the given `title` and callback `fn`
576 context.it = function(title, fn){
577 suites[0].addTest(new Test(title, fn));
582 }); // module: interfaces/bdd.js
584 require.register("interfaces/exports.js", function(module, exports, require){
587 * Module dependencies.
590 var Suite = require('../suite')
591 , Test = require('../test');
594 * TDD-style interface:
598 * 'should return -1 when the value is not present': function(){
602 * 'should return the correct index when the value is present': function(){
610 module.exports = function(suite){
611 var suites = [suite];
613 suite.on('require', visit);
615 function visit(obj) {
617 for (var key in obj) {
618 if ('function' == typeof obj[key]) {
622 suites[0].beforeAll(fn);
625 suites[0].afterAll(fn);
628 suites[0].beforeEach(fn);
631 suites[0].afterEach(fn);
634 suites[0].addTest(new Test(key, fn));
637 var suite = Suite.create(suites[0], key);
638 suites.unshift(suite);
645 }); // module: interfaces/exports.js
647 require.register("interfaces/index.js", function(module, exports, require){
649 exports.bdd = require('./bdd');
650 exports.tdd = require('./tdd');
651 exports.qunit = require('./qunit');
652 exports.exports = require('./exports');
654 }); // module: interfaces/index.js
656 require.register("interfaces/qunit.js", function(module, exports, require){
659 * Module dependencies.
662 var Suite = require('../suite')
663 , Test = require('../test');
666 * QUnit-style interface:
670 * test('#length', function(){
672 * ok(arr.length == 3);
675 * test('#indexOf()', function(){
677 * ok(arr.indexOf(1) == 0);
678 * ok(arr.indexOf(2) == 1);
679 * ok(arr.indexOf(3) == 2);
684 * test('#length', function(){
685 * ok('foo'.length == 3);
690 module.exports = function(suite){
691 var suites = [suite];
693 suite.on('pre-require', function(context){
696 * Execute before running tests.
699 context.before = function(fn){
700 suites[0].beforeAll(fn);
704 * Execute after running tests.
707 context.after = function(fn){
708 suites[0].afterAll(fn);
712 * Execute before each test case.
715 context.beforeEach = function(fn){
716 suites[0].beforeEach(fn);
720 * Execute after each test case.
723 context.afterEach = function(fn){
724 suites[0].afterEach(fn);
728 * Describe a "suite" with the given `title`.
731 context.suite = function(title){
732 if (suites.length > 1) suites.shift();
733 var suite = Suite.create(suites[0], title);
734 suites.unshift(suite);
738 * Describe a specification or test-case
739 * with the given `title` and callback `fn`
743 context.test = function(title, fn){
744 suites[0].addTest(new Test(title, fn));
749 }); // module: interfaces/qunit.js
751 require.register("interfaces/tdd.js", function(module, exports, require){
754 * Module dependencies.
757 var Suite = require('../suite')
758 , Test = require('../test');
761 * TDD-style interface:
763 * suite('Array', function(){
764 * suite('#indexOf()', function(){
765 * suiteSetup(function(){
769 * test('should return -1 when not present', function(){
773 * test('should return the index when present', function(){
777 * suiteTeardown(function(){
785 module.exports = function(suite){
786 var suites = [suite];
788 suite.on('pre-require', function(context){
791 * Execute before each test case.
794 context.setup = function(fn){
795 suites[0].beforeEach(fn);
799 * Execute after each test case.
802 context.teardown = function(fn){
803 suites[0].afterEach(fn);
807 * Execute before the suite.
810 context.suiteSetup = function(fn){
811 suites[0].beforeAll(fn);
815 * Execute after the suite.
818 context.suiteTeardown = function(fn){
819 suites[0].afterAll(fn);
823 * Describe a "suite" with the given `title`
824 * and callback `fn` containing nested suites
828 context.suite = function(title, fn){
829 var suite = Suite.create(suites[0], title);
830 suites.unshift(suite);
836 * Describe a specification or test-case
837 * with the given `title` and callback `fn`
841 context.test = function(title, fn){
842 suites[0].addTest(new Test(title, fn));
847 }); // module: interfaces/tdd.js
849 require.register("mocha.js", function(module, exports, require){
853 * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
858 * Module dependencies.
861 var path = require('browser/path');
867 exports = module.exports = Mocha;
873 exports.version = '1.0.3';
879 exports.utils = require('./utils');
880 exports.interfaces = require('./interfaces');
881 exports.reporters = require('./reporters');
882 exports.Runnable = require('./runnable');
883 exports.Context = require('./context');
884 exports.Runner = require('./runner');
885 exports.Suite = require('./suite');
886 exports.Hook = require('./hook');
887 exports.Test = require('./test');
890 * Return image `name` path.
892 * @param {String} name
897 function image(name) {
898 return __dirname + '/../images/' + name + '.png';
902 * Setup mocha with `options`.
906 * - `ui` name "bdd", "tdd", "exports" etc
907 * - `reporter` reporter instance, defaults to `mocha.reporters.Dot`
908 * - `globals` array of accepted globals
909 * - `timeout` timeout in milliseconds
910 * - `ignoreLeaks` ignore global leaks
911 * - `grep` string or regexp to filter tests with
913 * @param {Object} options
917 function Mocha(options) {
918 options = options || {};
919 options.grep = 'string' == typeof options.grep
920 ? new RegExp(options.grep)
923 this.options = options;
924 this.suite = new exports.Suite('', new exports.Context);
926 this.reporter(options.reporter);
927 if (options.timeout) this.suite.timeout(options.timeout);
933 * @param {String} file
937 Mocha.prototype.addFile = function(file){
938 this.files.push(file);
943 * Set reporter to `name`, defaults to "dot".
945 * @param {String} name
949 Mocha.prototype.reporter = function(name){
950 name = name || 'dot';
951 this._reporter = require('./reporters/' + name);
952 if (!this._reporter) throw new Error('invalid reporter "' + name + '"');
957 * Set test UI `name`, defaults to "bdd".
959 * @param {String} bdd
963 Mocha.prototype.ui = function(name){
964 name = name || 'bdd';
965 this._ui = exports.interfaces[name];
966 if (!this._ui) throw new Error('invalid interface "' + name + '"');
967 this._ui = this._ui(this.suite);
972 * Load registered files.
977 Mocha.prototype.loadFiles = function(){
978 var suite = this.suite;
979 this.files.forEach(function(file){
980 file = path.resolve(file);
981 suite.emit('pre-require', global, file);
982 suite.emit('require', require(file), file);
983 suite.emit('post-require', global, file);
988 * Enable growl support.
993 Mocha.prototype.growl = function(runner, reporter) {
994 var notify = require('growl');
996 runner.on('end', function(){
997 var stats = reporter.stats;
998 if (stats.failures) {
999 var msg = stats.failures + ' of ' + runner.total + ' tests failed';
1000 notify(msg, { title: 'Failed', image: image('fail') });
1002 notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
1004 , image: image('pass')
1011 * Add regexp to grep for to the options object
1013 * @param {RegExp} or {String} re
1018 Mocha.prototype.grep = function(re){
1019 this.options.grep = 'string' == typeof re
1026 * Run tests and invoke `fn()` when complete.
1028 * @param {Function} fn
1033 Mocha.prototype.run = function(fn){
1035 var suite = this.suite;
1036 var options = this.options;
1037 var runner = new exports.Runner(suite);
1038 var reporter = new this._reporter(runner);
1039 runner.ignoreLeaks = options.ignoreLeaks;
1040 if (options.grep) runner.grep(options.grep);
1041 if (options.globals) runner.globals(options.globals);
1042 if (options.growl) this.growl(runner, reporter);
1043 return runner.run(fn);
1046 }); // module: mocha.js
1048 require.register("reporters/base.js", function(module, exports, require){
1051 * Module dependencies.
1054 var tty = require('browser/tty')
1055 , diff = require('browser/diff');
1058 * Save timer references to avoid Sinon interfering (see GH-237).
1061 var Date = global.Date
1062 , setTimeout = global.setTimeout
1063 , setInterval = global.setInterval
1064 , clearTimeout = global.clearTimeout
1065 , clearInterval = global.clearInterval;
1068 * Check if both stdio streams are associated with a tty.
1071 var isatty = tty.isatty(1) && tty.isatty(2);
1077 exports = module.exports = Base;
1080 * Enable coloring by default.
1083 exports.useColors = isatty;
1086 * Default color map.
1094 , 'bright yellow': 93
1098 , 'error message': 31
1108 , 'diff removed': 41
1112 * Color `str` with the given `type`,
1113 * allowing colors to be disabled,
1114 * as well as user-defined color
1117 * @param {String} type
1118 * @param {String} str
1123 var color = exports.color = function(type, str) {
1124 if (!exports.useColors) return str;
1125 return '\033[' + exports.colors[type] + 'm' + str + '\033[0m';
1129 * Expose term window size, with some
1130 * defaults for when stderr is not a tty.
1135 ? process.stdout.getWindowSize
1136 ? process.stdout.getWindowSize(1)[0]
1137 : tty.getWindowSize()[1]
1142 * Expose some basic cursor interactions
1143 * that are common among reporters.
1148 process.stdout.write('\033[?25l');
1152 process.stdout.write('\033[?25h');
1155 deleteLine: function(){
1156 process.stdout.write('\033[2K');
1159 beginningOfLine: function(){
1160 process.stdout.write('\033[0G');
1164 exports.cursor.deleteLine();
1165 exports.cursor.beginningOfLine();
1170 * A test is considered slow if it
1171 * exceeds the following value in milliseconds.
1177 * Outut the given `failures` as a list.
1179 * @param {Array} failures
1183 exports.list = function(failures){
1185 failures.forEach(function(test, i){
1187 var fmt = color('error title', ' %s) %s:\n')
1188 + color('error message', ' %s')
1189 + color('error stack', '\n%s\n');
1193 , message = err.message || ''
1194 , stack = err.stack || message
1195 , index = stack.indexOf(message) + message.length
1196 , msg = stack.slice(0, index)
1197 , actual = err.actual
1198 , expected = err.expected;
1200 // actual / expected diff
1201 if ('string' == typeof actual && 'string' == typeof expected) {
1202 var len = Math.max(actual.length, expected.length);
1204 if (len < 20) msg = errorDiff(err, 'Chars');
1205 else msg = errorDiff(err, 'Words');
1208 var lines = msg.split('\n');
1209 if (lines.length > 4) {
1210 var width = String(lines.length).length;
1211 msg = lines.map(function(str, i){
1212 return pad(++i, width) + ' |' + ' ' + str;
1218 + color('diff removed', 'actual')
1220 + color('diff added', 'expected')
1226 msg = msg.replace(/^/gm, ' ');
1228 fmt = color('error title', ' %s) %s:\n%s')
1229 + color('error stack', '\n%s\n');
1232 // indent stack trace without msg
1233 stack = stack.slice(index ? index + 1 : index)
1234 .replace(/^/gm, ' ');
1236 console.error(fmt, (i + 1), test.fullTitle(), msg, stack);
1241 * Initialize a new `Base` reporter.
1243 * All other reporters generally
1244 * inherit from this reporter, providing
1245 * stats such as test duration, number
1246 * of tests passed / failed etc.
1248 * @param {Runner} runner
1252 function Base(runner) {
1254 , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 }
1255 , failures = this.failures = [];
1257 if (!runner) return;
1258 this.runner = runner;
1260 runner.on('start', function(){
1261 stats.start = new Date;
1264 runner.on('suite', function(suite){
1265 stats.suites = stats.suites || 0;
1266 suite.root || stats.suites++;
1269 runner.on('test end', function(test){
1270 stats.tests = stats.tests || 0;
1274 runner.on('pass', function(test){
1275 stats.passes = stats.passes || 0;
1277 var medium = exports.slow / 2;
1278 test.speed = test.duration > exports.slow
1280 : test.duration > medium
1287 runner.on('fail', function(test, err){
1288 stats.failures = stats.failures || 0;
1291 failures.push(test);
1294 runner.on('end', function(){
1295 stats.end = new Date;
1296 stats.duration = new Date - stats.start;
1299 runner.on('pending', function(){
1305 * Output common epilogue used by many of
1306 * the bundled reporters.
1311 Base.prototype.epilogue = function(){
1312 var stats = this.stats
1318 function pluralize(n) {
1319 return 1 == n ? 'test' : 'tests';
1323 if (stats.failures) {
1324 fmt = color('bright fail', ' ✖')
1325 + color('fail', ' %d of %d %s failed')
1326 + color('light', ':')
1331 pluralize(this.runner.total));
1333 Base.list(this.failures);
1339 fmt = color('bright pass', ' ✔')
1340 + color('green', ' %d %s complete')
1341 + color('light', ' (%dms)');
1345 pluralize(stats.tests),
1349 if (stats.pending) {
1350 fmt = color('pending', ' •')
1351 + color('pending', ' %d %s pending');
1353 console.log(fmt, stats.pending, pluralize(stats.pending));
1360 * Pad the given `str` to `len`.
1362 * @param {String} str
1363 * @param {String} len
1368 function pad(str, len) {
1370 return Array(len - str.length + 1).join(' ') + str;
1374 * Return a character diff for `err`.
1376 * @param {Error} err
1381 function errorDiff(err, type) {
1382 return diff['diff' + type](err.actual, err.expected).map(function(str){
1383 if (/^(\n+)$/.test(str.value)) str.value = Array(++RegExp.$1.length).join('<newline>');
1384 if (str.added) return colorLines('diff added', str.value);
1385 if (str.removed) return colorLines('diff removed', str.value);
1391 * Color lines for `str`, using the color `name`.
1393 * @param {String} name
1394 * @param {String} str
1399 function colorLines(name, str) {
1400 return str.split('\n').map(function(str){
1401 return color(name, str);
1405 }); // module: reporters/base.js
1407 require.register("reporters/doc.js", function(module, exports, require){
1410 * Module dependencies.
1413 var Base = require('./base')
1414 , utils = require('../utils');
1420 exports = module.exports = Doc;
1423 * Initialize a new `Doc` reporter.
1425 * @param {Runner} runner
1429 function Doc(runner) {
1430 Base.call(this, runner);
1433 , stats = this.stats
1434 , total = runner.total
1438 return Array(indents).join(' ');
1441 runner.on('suite', function(suite){
1442 if (suite.root) return;
1444 console.log('%s<section class="suite">', indent());
1446 console.log('%s<h1>%s</h1>', indent(), suite.title);
1447 console.log('%s<dl>', indent());
1450 runner.on('suite end', function(suite){
1451 if (suite.root) return;
1452 console.log('%s</dl>', indent());
1454 console.log('%s</section>', indent());
1458 runner.on('pass', function(test){
1459 console.log('%s <dt>%s</dt>', indent(), test.title);
1460 var code = utils.escape(clean(test.fn.toString()));
1461 console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code);
1466 * Strip the function definition from `str`,
1467 * and re-indent for pre whitespace.
1470 function clean(str) {
1472 .replace(/^function *\(.*\) *{/, '')
1473 .replace(/\s+\}$/, '');
1475 var spaces = str.match(/^\n?( *)/)[1].length
1476 , re = new RegExp('^ {' + spaces + '}', 'gm');
1478 str = str.replace(re, '');
1482 }); // module: reporters/doc.js
1484 require.register("reporters/dot.js", function(module, exports, require){
1487 * Module dependencies.
1490 var Base = require('./base')
1491 , color = Base.color;
1497 exports = module.exports = Dot;
1500 * Initialize a new `Dot` matrix test reporter.
1502 * @param {Runner} runner
1506 function Dot(runner) {
1507 Base.call(this, runner);
1510 , stats = this.stats
1511 , width = Base.window.width * .75 | 0
1514 runner.on('start', function(){
1515 process.stdout.write('\n ');
1518 runner.on('pending', function(test){
1519 process.stdout.write(color('pending', '.'));
1522 runner.on('pass', function(test){
1523 if (++n % width == 0) process.stdout.write('\n ');
1524 if ('slow' == test.speed) {
1525 process.stdout.write(color('bright yellow', '.'));
1527 process.stdout.write(color(test.speed, '.'));
1531 runner.on('fail', function(test, err){
1532 if (++n % width == 0) process.stdout.write('\n ');
1533 process.stdout.write(color('fail', '.'));
1536 runner.on('end', function(){
1543 * Inherit from `Base.prototype`.
1546 Dot.prototype = new Base;
1547 Dot.prototype.constructor = Dot;
1549 }); // module: reporters/dot.js
1551 require.register("reporters/html-cov.js", function(module, exports, require){
1554 * Module dependencies.
1557 var JSONCov = require('./json-cov')
1558 , fs = require('browser/fs');
1564 exports = module.exports = HTMLCov;
1567 * Initialize a new `JsCoverage` reporter.
1569 * @param {Runner} runner
1573 function HTMLCov(runner) {
1574 var jade = require('jade')
1575 , file = __dirname + '/templates/coverage.jade'
1576 , str = fs.readFileSync(file, 'utf8')
1577 , fn = jade.compile(str, { filename: file })
1580 JSONCov.call(this, runner, false);
1582 runner.on('end', function(){
1583 process.stdout.write(fn({
1585 , coverageClass: coverageClass
1590 function coverageClass(n) {
1591 if (n >= 75) return 'high';
1592 if (n >= 50) return 'medium';
1593 if (n >= 25) return 'low';
1596 }); // module: reporters/html-cov.js
1598 require.register("reporters/html.js", function(module, exports, require){
1601 * Module dependencies.
1604 var Base = require('./base')
1605 , utils = require('../utils')
1606 , Progress = require('../browser/progress')
1607 , escape = utils.escape;
1610 * Save timer references to avoid Sinon interfering (see GH-237).
1613 var Date = global.Date
1614 , setTimeout = global.setTimeout
1615 , setInterval = global.setInterval
1616 , clearTimeout = global.clearTimeout
1617 , clearInterval = global.clearInterval;
1623 exports = module.exports = HTML;
1629 var statsTemplate = '<ul id="stats">'
1630 + '<li class="progress"><canvas width="40" height="40"></canvas></li>'
1631 + '<li class="passes">passes: <em>0</em></li>'
1632 + '<li class="failures">failures: <em>0</em></li>'
1633 + '<li class="duration">duration: <em>0</em>s</li>'
1637 * Initialize a new `Doc` reporter.
1639 * @param {Runner} runner
1643 function HTML(runner) {
1644 Base.call(this, runner);
1647 , stats = this.stats
1648 , total = runner.total
1649 , root = document.getElementById('mocha')
1650 , stat = fragment(statsTemplate)
1651 , items = stat.getElementsByTagName('li')
1652 , passes = items[1].getElementsByTagName('em')[0]
1653 , failures = items[2].getElementsByTagName('em')[0]
1654 , duration = items[3].getElementsByTagName('em')[0]
1655 , canvas = stat.getElementsByTagName('canvas')[0]
1660 if (canvas.getContext) {
1661 ctx = canvas.getContext('2d');
1662 progress = new Progress;
1665 if (!root) return error('#mocha div missing, add it to your document');
1667 root.appendChild(stat);
1669 if (progress) progress.size(40);
1671 runner.on('suite', function(suite){
1672 if (suite.root) return;
1675 var el = fragment('<div class="suite"><h1>%s</h1></div>', suite.title);
1678 stack[0].appendChild(el);
1679 stack.unshift(document.createElement('div'));
1680 el.appendChild(stack[0]);
1683 runner.on('suite end', function(suite){
1684 if (suite.root) return;
1688 runner.on('fail', function(test, err){
1689 if ('hook' == test.type || err.uncaught) runner.emit('test end', test);
1692 runner.on('test end', function(test){
1693 // TODO: add to stats
1694 var percent = stats.tests / total * 100 | 0;
1695 if (progress) progress.update(percent).draw(ctx);
1698 var ms = new Date - stats.start;
1699 text(passes, stats.passes);
1700 text(failures, stats.failures);
1701 text(duration, (ms / 1000).toFixed(2));
1704 if ('passed' == test.state) {
1705 var el = fragment('<div class="test pass %e"><h2>%e<span class="duration">%ems</span></h2></div>', test.speed, test.title, test.duration);
1706 } else if (test.pending) {
1707 var el = fragment('<div class="test pass pending"><h2>%e</h2></div>', test.title);
1709 var el = fragment('<div class="test fail"><h2>%e</h2></div>', test.title);
1710 var str = test.err.stack || test.err.toString();
1712 // FF / Opera do not add the message
1713 if (!~str.indexOf(test.err.message)) {
1714 str = test.err.message + '\n' + str;
1717 // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
1718 // check for the result of the stringifying.
1719 if ('[object Error]' == str) str = test.err.message;
1721 // Safari doesn't give you a stack. Let's at least provide a source line.
1722 if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) {
1723 str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")";
1726 el.appendChild(fragment('<pre class="error">%e</pre>', str));
1730 var h2 = el.getElementsByTagName('h2')[0];
1732 on(h2, 'click', function(){
1733 pre.style.display = 'none' == pre.style.display
1740 if (!test.pending) {
1741 var pre = fragment('<pre><code>%e</code></pre>', clean(test.fn.toString()));
1742 el.appendChild(pre);
1743 pre.style.display = 'none';
1746 stack[0].appendChild(el);
1751 * Display error `msg`.
1754 function error(msg) {
1755 document.body.appendChild(fragment('<div id="error">%s</div>', msg));
1759 * Return a DOM fragment from `html`.
1762 function fragment(html) {
1763 var args = arguments
1764 , div = document.createElement('div')
1767 div.innerHTML = html.replace(/%([se])/g, function(_, type){
1769 case 's': return String(args[i++]);
1770 case 'e': return escape(args[i++]);
1774 return div.firstChild;
1778 * Set `el` text to `str`.
1781 function text(el, str) {
1782 if (el.textContent) {
1783 el.textContent = str;
1790 * Listen on `event` with callback `fn`.
1793 function on(el, event, fn) {
1794 if (el.addEventListener) {
1795 el.addEventListener(event, fn, false);
1797 el.attachEvent('on' + event, fn);
1802 * Strip the function definition from `str`,
1803 * and re-indent for pre whitespace.
1806 function clean(str) {
1808 .replace(/^function *\(.*\) *{/, '')
1809 .replace(/\s+\}$/, '');
1811 var spaces = str.match(/^\n?( *)/)[1].length
1812 , re = new RegExp('^ {' + spaces + '}', 'gm');
1816 .replace(/^\s+/, '');
1821 }); // module: reporters/html.js
1823 require.register("reporters/index.js", function(module, exports, require){
1825 exports.Base = require('./base');
1826 exports.Dot = require('./dot');
1827 exports.Doc = require('./doc');
1828 exports.TAP = require('./tap');
1829 exports.JSON = require('./json');
1830 exports.HTML = require('./html');
1831 exports.List = require('./list');
1832 exports.Min = require('./min');
1833 exports.Spec = require('./spec');
1834 exports.Progress = require('./progress');
1835 exports.Landing = require('./landing');
1836 exports.JSONCov = require('./json-cov');
1837 exports.HTMLCov = require('./html-cov');
1838 exports.JSONStream = require('./json-stream');
1839 exports.XUnit = require('./xunit')
1840 exports.Teamcity = require('./teamcity')
1842 }); // module: reporters/index.js
1844 require.register("reporters/json-cov.js", function(module, exports, require){
1847 * Module dependencies.
1850 var Base = require('./base');
1856 exports = module.exports = JSONCov;
1859 * Initialize a new `JsCoverage` reporter.
1861 * @param {Runner} runner
1862 * @param {Boolean} output
1866 function JSONCov(runner, output) {
1868 , output = 1 == arguments.length ? true : output;
1870 Base.call(this, runner);
1876 runner.on('test end', function(test){
1880 runner.on('pass', function(test){
1884 runner.on('fail', function(test){
1885 failures.push(test);
1888 runner.on('end', function(){
1889 var cov = global._$jscoverage || {};
1890 var result = self.cov = map(cov);
1891 result.stats = self.stats;
1892 result.tests = tests.map(clean);
1893 result.failures = failures.map(clean);
1894 result.passes = passes.map(clean);
1895 if (!output) return;
1896 process.stdout.write(JSON.stringify(result, null, 2 ));
1901 * Map jscoverage data to a JSON structure
1902 * suitable for reporting.
1904 * @param {Object} cov
1911 instrumentation: 'node-jscoverage'
1919 for (var filename in cov) {
1920 var data = coverage(filename, cov[filename]);
1921 ret.files.push(data);
1922 ret.hits += data.hits;
1923 ret.misses += data.misses;
1924 ret.sloc += data.sloc;
1928 ret.coverage = (ret.hits / ret.sloc) * 100;
1935 * Map jscoverage data for a single source file
1936 * to a JSON structure suitable for reporting.
1938 * @param {String} filename name of the source file
1939 * @param {Object} data jscoverage coverage data
1944 function coverage(filename, data) {
1954 data.source.forEach(function(line, num){
1957 if (data[num] === 0) {
1960 } else if (data[num] !== undefined) {
1967 , coverage: data[num] === undefined
1973 ret.coverage = ret.hits / ret.sloc * 100;
1979 * Return a plain-object representation of `test`
1980 * free of cyclic properties etc.
1982 * @param {Object} test
1987 function clean(test) {
1990 , fullTitle: test.fullTitle()
1991 , duration: test.duration
1995 }); // module: reporters/json-cov.js
1997 require.register("reporters/json-stream.js", function(module, exports, require){
2000 * Module dependencies.
2003 var Base = require('./base')
2004 , color = Base.color;
2010 exports = module.exports = List;
2013 * Initialize a new `List` test reporter.
2015 * @param {Runner} runner
2019 function List(runner) {
2020 Base.call(this, runner);
2023 , stats = this.stats
2024 , total = runner.total;
2026 runner.on('start', function(){
2027 console.log(JSON.stringify(['start', { total: total }]));
2030 runner.on('pass', function(test){
2031 console.log(JSON.stringify(['pass', clean(test)]));
2034 runner.on('fail', function(test, err){
2035 console.log(JSON.stringify(['fail', clean(test)]));
2038 runner.on('end', function(){
2039 process.stdout.write(JSON.stringify(['end', self.stats]));
2044 * Return a plain-object representation of `test`
2045 * free of cyclic properties etc.
2047 * @param {Object} test
2052 function clean(test) {
2055 , fullTitle: test.fullTitle()
2056 , duration: test.duration
2059 }); // module: reporters/json-stream.js
2061 require.register("reporters/json.js", function(module, exports, require){
2064 * Module dependencies.
2067 var Base = require('./base')
2068 , cursor = Base.cursor
2069 , color = Base.color;
2075 exports = module.exports = JSONReporter;
2078 * Initialize a new `JSON` reporter.
2080 * @param {Runner} runner
2084 function JSONReporter(runner) {
2086 Base.call(this, runner);
2092 runner.on('test end', function(test){
2096 runner.on('pass', function(test){
2100 runner.on('fail', function(test){
2101 failures.push(test);
2104 runner.on('end', function(){
2107 , tests: tests.map(clean)
2108 , failures: failures.map(clean)
2109 , passes: passes.map(clean)
2112 process.stdout.write(JSON.stringify(obj, null, 2));
2117 * Return a plain-object representation of `test`
2118 * free of cyclic properties etc.
2120 * @param {Object} test
2125 function clean(test) {
2128 , fullTitle: test.fullTitle()
2129 , duration: test.duration
2132 }); // module: reporters/json.js
2134 require.register("reporters/landing.js", function(module, exports, require){
2137 * Module dependencies.
2140 var Base = require('./base')
2141 , cursor = Base.cursor
2142 , color = Base.color;
2148 exports = module.exports = Landing;
2154 Base.colors.plane = 0;
2157 * Airplane crash color.
2160 Base.colors['plane crash'] = 31;
2166 Base.colors.runway = 90;
2169 * Initialize a new `Landing` reporter.
2171 * @param {Runner} runner
2175 function Landing(runner) {
2176 Base.call(this, runner);
2179 , stats = this.stats
2180 , width = Base.window.width * .75 | 0
2181 , total = runner.total
2182 , stream = process.stdout
2183 , plane = color('plane', '✈')
2188 var buf = Array(width).join('-');
2189 return ' ' + color('runway', buf);
2192 runner.on('start', function(){
2193 stream.write('\n ');
2197 runner.on('test end', function(test){
2198 // check if the plane crashed
2199 var col = -1 == crashed
2200 ? width * ++n / total | 0
2204 if ('failed' == test.state) {
2205 plane = color('plane crash', '✈');
2209 // render landing strip
2210 stream.write('\033[4F\n\n');
2211 stream.write(runway());
2212 stream.write('\n ');
2213 stream.write(color('runway', Array(col).join('â‹…')));
2215 stream.write(color('runway', Array(width - col).join('â‹…') + '\n'));
2216 stream.write(runway());
2217 stream.write('\033[0m');
2220 runner.on('end', function(){
2228 * Inherit from `Base.prototype`.
2231 Landing.prototype = new Base;
2232 Landing.prototype.constructor = Landing;
2234 }); // module: reporters/landing.js
2236 require.register("reporters/list.js", function(module, exports, require){
2239 * Module dependencies.
2242 var Base = require('./base')
2243 , cursor = Base.cursor
2244 , color = Base.color;
2250 exports = module.exports = List;
2253 * Initialize a new `List` test reporter.
2255 * @param {Runner} runner
2259 function List(runner) {
2260 Base.call(this, runner);
2263 , stats = this.stats
2266 runner.on('start', function(){
2270 runner.on('test', function(test){
2271 process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));
2274 runner.on('pending', function(test){
2275 var fmt = color('checkmark', ' -')
2276 + color('pending', ' %s');
2277 console.log(fmt, test.fullTitle());
2280 runner.on('pass', function(test){
2281 var fmt = color('checkmark', ' ✓')
2282 + color('pass', ' %s: ')
2283 + color(test.speed, '%dms');
2285 console.log(fmt, test.fullTitle(), test.duration);
2288 runner.on('fail', function(test, err){
2290 console.log(color('fail', ' %d) %s'), ++n, test.fullTitle());
2293 runner.on('end', self.epilogue.bind(self));
2297 * Inherit from `Base.prototype`.
2300 List.prototype = new Base;
2301 List.prototype.constructor = List;
2304 }); // module: reporters/list.js
2306 require.register("reporters/markdown.js", function(module, exports, require){
2309 * Module dependencies.
2312 var Base = require('./base')
2313 , utils = require('../utils');
2316 * Expose `Markdown`.
2319 exports = module.exports = Markdown;
2322 * Initialize a new `Markdown` reporter.
2324 * @param {Runner} runner
2328 function Markdown(runner) {
2329 Base.call(this, runner);
2332 , stats = this.stats
2333 , total = runner.total
2337 function title(str) {
2338 return Array(level).join('#') + ' ' + str;
2342 return Array(level).join(' ');
2345 function mapTOC(suite, obj) {
2347 obj = obj[suite.title] = obj[suite.title] || { suite: suite };
2348 suite.suites.forEach(function(suite){
2354 function stringifyTOC(obj, level) {
2358 for (var key in obj) {
2359 if ('suite' == key) continue;
2360 if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
2361 if (key) buf += Array(level).join(' ') + link;
2362 buf += stringifyTOC(obj[key], level);
2368 function generateTOC(suite) {
2369 var obj = mapTOC(suite, {});
2370 return stringifyTOC(obj, 0);
2373 generateTOC(runner.suite);
2375 runner.on('suite', function(suite){
2377 var slug = utils.slug(suite.fullTitle());
2378 buf += '<a name="' + slug + '" />' + '\n';
2379 buf += title(suite.title) + '\n';
2382 runner.on('suite end', function(suite){
2386 runner.on('pass', function(test){
2387 var code = clean(test.fn.toString());
2388 buf += test.title + '.\n';
2394 runner.on('end', function(){
2395 process.stdout.write('# TOC\n');
2396 process.stdout.write(generateTOC(runner.suite));
2397 process.stdout.write(buf);
2402 * Strip the function definition from `str`,
2403 * and re-indent for pre whitespace.
2406 function clean(str) {
2408 .replace(/^function *\(.*\) *{/, '')
2409 .replace(/\s+\}$/, '');
2411 var spaces = str.match(/^\n?( *)/)[1].length
2412 , re = new RegExp('^ {' + spaces + '}', 'gm');
2414 str = str.replace(re, '');
2418 }); // module: reporters/markdown.js
2420 require.register("reporters/min.js", function(module, exports, require){
2422 * Module dependencies.
2425 var Base = require('./base');
2431 exports = module.exports = Min;
2434 * Initialize a new `Min` minimal test reporter (best used with --watch).
2436 * @param {Runner} runner
2440 function Min(runner) {
2441 Base.call(this, runner);
2443 runner.on('start', function(){
2445 process.stdout.write('\033[2J');
2446 // set cursor position
2447 process.stdout.write('\033[1;3H');
2450 runner.on('end', this.epilogue.bind(this));
2454 * Inherit from `Base.prototype`.
2457 Min.prototype = new Base;
2458 Min.prototype.constructor = Min;
2460 }); // module: reporters/min.js
2462 require.register("reporters/progress.js", function(module, exports, require){
2465 * Module dependencies.
2468 var Base = require('./base')
2469 , cursor = Base.cursor
2470 , color = Base.color;
2473 * Expose `Progress`.
2476 exports = module.exports = Progress;
2479 * General progress bar color.
2482 Base.colors.progress = 90;
2485 * Initialize a new `Progress` bar test reporter.
2487 * @param {Runner} runner
2488 * @param {Object} options
2492 function Progress(runner, options) {
2493 Base.call(this, runner);
2496 , options = options || {}
2497 , stats = this.stats
2498 , width = Base.window.width * .50 | 0
2499 , total = runner.total
2504 options.open = options.open || '[';
2505 options.complete = options.complete || 'â–¬';
2506 options.incomplete = options.incomplete || 'â‹…';
2507 options.close = options.close || ']';
2508 options.verbose = false;
2511 runner.on('start', function(){
2517 runner.on('test end', function(){
2519 var incomplete = total - complete
2520 , percent = complete / total
2521 , n = width * percent | 0
2525 process.stdout.write('\033[J');
2526 process.stdout.write(color('progress', ' ' + options.open));
2527 process.stdout.write(Array(n).join(options.complete));
2528 process.stdout.write(Array(i).join(options.incomplete));
2529 process.stdout.write(color('progress', options.close));
2530 if (options.verbose) {
2531 process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
2535 // tests are complete, output some stats
2536 // and the failures if any
2537 runner.on('end', function(){
2545 * Inherit from `Base.prototype`.
2548 Progress.prototype = new Base;
2549 Progress.prototype.constructor = Progress;
2552 }); // module: reporters/progress.js
2554 require.register("reporters/spec.js", function(module, exports, require){
2557 * Module dependencies.
2560 var Base = require('./base')
2561 , cursor = Base.cursor
2562 , color = Base.color;
2568 exports = module.exports = Spec;
2571 * Initialize a new `Spec` test reporter.
2573 * @param {Runner} runner
2577 function Spec(runner) {
2578 Base.call(this, runner);
2581 , stats = this.stats
2586 return Array(indents).join(' ')
2589 runner.on('start', function(){
2593 runner.on('suite', function(suite){
2595 console.log(color('suite', '%s%s'), indent(), suite.title);
2598 runner.on('suite end', function(suite){
2600 if (1 == indents) console.log();
2603 runner.on('test', function(test){
2604 process.stdout.write(indent() + color('pass', ' â—¦ ' + test.title + ': '));
2607 runner.on('pending', function(test){
2608 var fmt = indent() + color('pending', ' - %s');
2609 console.log(fmt, test.title);
2612 runner.on('pass', function(test){
2613 if ('fast' == test.speed) {
2615 + color('checkmark', ' ✓')
2616 + color('pass', ' %s ');
2618 console.log(fmt, test.title);
2621 + color('checkmark', ' ✓')
2622 + color('pass', ' %s ')
2623 + color(test.speed, '(%dms)');
2625 console.log(fmt, test.title, test.duration);
2629 runner.on('fail', function(test, err){
2631 console.log(indent() + color('fail', ' %d) %s'), ++n, test.title);
2634 runner.on('end', self.epilogue.bind(self));
2638 * Inherit from `Base.prototype`.
2641 Spec.prototype = new Base;
2642 Spec.prototype.constructor = Spec;
2645 }); // module: reporters/spec.js
2647 require.register("reporters/tap.js", function(module, exports, require){
2650 * Module dependencies.
2653 var Base = require('./base')
2654 , cursor = Base.cursor
2655 , color = Base.color;
2661 exports = module.exports = TAP;
2664 * Initialize a new `TAP` reporter.
2666 * @param {Runner} runner
2670 function TAP(runner) {
2671 Base.call(this, runner);
2674 , stats = this.stats
2675 , total = runner.total
2678 runner.on('start', function(){
2679 console.log('%d..%d', 1, total);
2682 runner.on('test end', function(){
2686 runner.on('pending', function(test){
2687 console.log('ok %d %s # SKIP -', n, title(test));
2690 runner.on('pass', function(test){
2691 console.log('ok %d %s', n, title(test));
2694 runner.on('fail', function(test, err){
2695 console.log('not ok %d %s', n, title(test));
2696 console.log(err.stack.replace(/^/gm, ' '));
2701 * Return a TAP-safe title of `test`
2703 * @param {Object} test
2708 function title(test) {
2709 return test.fullTitle().replace(/#/g, '');
2712 }); // module: reporters/tap.js
2714 require.register("reporters/teamcity.js", function(module, exports, require){
2717 * Module dependencies.
2720 var Base = require('./base');
2723 * Expose `Teamcity`.
2726 exports = module.exports = Teamcity;
2729 * Initialize a new `Teamcity` reporter.
2731 * @param {Runner} runner
2735 function Teamcity(runner) {
2736 Base.call(this, runner);
2737 var stats = this.stats;
2739 runner.on('start', function() {
2740 console.log("##teamcity[testSuiteStarted name='mocha.suite']");
2743 runner.on('test', function(test) {
2744 console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']");
2747 runner.on('fail', function(test, err) {
2748 console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']");
2751 runner.on('pending', function(test) {
2752 console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']");
2755 runner.on('test end', function(test) {
2756 console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']");
2759 runner.on('end', function() {
2760 console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']");
2765 * Escape the given `str`.
2768 function escape(str) {
2769 return str.replace(/'/g, "|'");
2771 }); // module: reporters/teamcity.js
2773 require.register("reporters/xunit.js", function(module, exports, require){
2776 * Module dependencies.
2779 var Base = require('./base')
2780 , utils = require('../utils')
2781 , escape = utils.escape;
2784 * Save timer references to avoid Sinon interfering (see GH-237).
2787 var Date = global.Date
2788 , setTimeout = global.setTimeout
2789 , setInterval = global.setInterval
2790 , clearTimeout = global.clearTimeout
2791 , clearInterval = global.clearInterval;
2797 exports = module.exports = XUnit;
2800 * Initialize a new `XUnit` reporter.
2802 * @param {Runner} runner
2806 function XUnit(runner) {
2807 Base.call(this, runner);
2808 var stats = this.stats
2812 runner.on('test end', function(test){
2816 runner.on('end', function(){
2817 console.log(tag('testsuite', {
2819 , tests: stats.tests
2820 , failures: stats.failures
2821 , errors: stats.failures
2822 , skip: stats.tests - stats.failures - stats.passes
2823 , timestamp: (new Date).toUTCString()
2824 , time: stats.duration / 1000
2827 tests.forEach(test);
2828 console.log('</testsuite>');
2833 * Inherit from `Base.prototype`.
2836 XUnit.prototype = new Base;
2837 XUnit.prototype.constructor = XUnit;
2841 * Output tag for the given `test.`
2844 function test(test) {
2846 classname: test.parent.fullTitle()
2848 , time: test.duration / 1000
2851 if ('failed' == test.state) {
2853 attrs.message = escape(err.message);
2854 console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack))));
2855 } else if (test.pending) {
2856 console.log(tag('testcase', attrs, false, tag('skipped', {}, true)));
2858 console.log(tag('testcase', attrs, true) );
2866 function tag(name, attrs, close, content) {
2867 var end = close ? '/>' : '>'
2871 for (var key in attrs) {
2872 pairs.push(key + '="' + escape(attrs[key]) + '"');
2875 tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
2876 if (content) tag += content + '</' + name + end;
2881 * Return cdata escaped CDATA `str`.
2884 function cdata(str) {
2885 return '<![CDATA[' + escape(str) + ']]>';
2888 }); // module: reporters/xunit.js
2890 require.register("runnable.js", function(module, exports, require){
2893 * Module dependencies.
2896 var EventEmitter = require('browser/events').EventEmitter
2897 , debug = require('browser/debug')('runnable');
2900 * Save timer references to avoid Sinon interfering (see GH-237).
2903 var Date = global.Date
2904 , setTimeout = global.setTimeout
2905 , setInterval = global.setInterval
2906 , clearTimeout = global.clearTimeout
2907 , clearInterval = global.clearInterval;
2910 * Expose `Runnable`.
2913 module.exports = Runnable;
2916 * Initialize a new `Runnable` with the given `title` and callback `fn`.
2918 * @param {String} title
2919 * @param {Function} fn
2923 function Runnable(title, fn) {
2926 this.async = fn && fn.length;
2927 this.sync = ! this.async;
2928 this._timeout = 2000;
2929 this.timedOut = false;
2933 * Inherit from `EventEmitter.prototype`.
2936 Runnable.prototype = new EventEmitter;
2937 Runnable.prototype.constructor = Runnable;
2941 * Set & get timeout `ms`.
2943 * @param {Number} ms
2944 * @return {Runnable|Number} ms or self
2948 Runnable.prototype.timeout = function(ms){
2949 if (0 == arguments.length) return this._timeout;
2950 debug('timeout %d', ms);
2952 if (this.timer) this.resetTimeout();
2957 * Return the full title generated by recursively
2958 * concatenating the parent's full title.
2964 Runnable.prototype.fullTitle = function(){
2965 return this.parent.fullTitle() + ' ' + this.title;
2969 * Clear the timeout.
2974 Runnable.prototype.clearTimeout = function(){
2975 clearTimeout(this.timer);
2979 * Reset the timeout.
2984 Runnable.prototype.resetTimeout = function(){
2986 , ms = this.timeout();
2988 this.clearTimeout();
2990 this.timer = setTimeout(function(){
2991 self.callback(new Error('timeout of ' + ms + 'ms exceeded'));
2992 self.timedOut = true;
2998 * Run the test and invoke `fn(err)`.
3000 * @param {Function} fn
3004 Runnable.prototype.run = function(fn){
3006 , ms = this.timeout()
3012 if (ctx) ctx.runnable(this);
3017 this.timer = setTimeout(function(){
3018 done(new Error('timeout of ' + ms + 'ms exceeded'));
3019 self.timedOut = true;
3024 // called multiple times
3025 function multiple() {
3026 if (emitted) return;
3028 self.emit('error', new Error('done() called multiple times'));
3032 function done(err) {
3033 if (self.timedOut) return;
3034 if (finished) return multiple();
3035 self.clearTimeout();
3036 self.duration = new Date - start;
3041 // for .resetTimeout()
3042 this.callback = done;
3047 this.fn.call(ctx, function(err){
3048 if (err instanceof Error) return done(err);
3049 if (null != err) return done(new Error('done() invoked with non-Error: ' + err));
3060 if (!this.pending) this.fn.call(ctx);
3061 this.duration = new Date - start;
3068 }); // module: runnable.js
3070 require.register("runner.js", function(module, exports, require){
3073 * Module dependencies.
3076 var EventEmitter = require('browser/events').EventEmitter
3077 , debug = require('browser/debug')('runner')
3078 , Test = require('./test')
3079 , utils = require('./utils')
3080 , noop = function(){};
3086 module.exports = Runner;
3089 * Initialize a `Runner` for the given `suite`.
3093 * - `start` execution started
3094 * - `end` execution complete
3095 * - `suite` (suite) test suite execution started
3096 * - `suite end` (suite) all tests (and sub-suites) have finished
3097 * - `test` (test) test execution started
3098 * - `test end` (test) test completed
3099 * - `hook` (hook) hook execution started
3100 * - `hook end` (hook) hook complete
3101 * - `pass` (test) test passed
3102 * - `fail` (test, err) test failed
3107 function Runner(suite) {
3111 this.total = suite.total();
3113 this.on('test end', function(test){ self.checkGlobals(test); });
3114 this.on('hook end', function(hook){ self.checkGlobals(hook); });
3116 this.globals(utils.keys(global).concat(['errno']));
3120 * Inherit from `EventEmitter.prototype`.
3123 Runner.prototype = new EventEmitter;
3124 Runner.prototype.constructor = Runner;
3128 * Run tests with full titles matching `re`. Updates runner.total
3129 * with number of tests matched.
3131 * @param {RegExp} re
3132 * @return {Runner} for chaining
3136 Runner.prototype.grep = function(re){
3137 debug('grep %s', re);
3139 this.total = this.grepTotal(this.suite);
3144 * Returns the number of tests matching the grep search for the
3147 * @param {Suite} suite
3152 Runner.prototype.grepTotal = function(suite) {
3156 suite.eachTest(function(test){
3157 if (self._grep.test(test.fullTitle())) total++;
3164 * Allow the given `arr` of globals.
3166 * @param {Array} arr
3167 * @return {Runner} for chaining
3171 Runner.prototype.globals = function(arr){
3172 if (0 == arguments.length) return this._globals;
3173 debug('globals %j', arr);
3174 utils.forEach(arr, function(arr){
3175 this._globals.push(arr);
3181 * Check for global variable leaks.
3186 Runner.prototype.checkGlobals = function(test){
3187 if (this.ignoreLeaks) return;
3189 var leaks = utils.filter(utils.keys(global), function(key){
3190 return !~utils.indexOf(this._globals, key) && (!global.navigator || 'onerror' !== key);
3193 this._globals = this._globals.concat(leaks);
3195 if (leaks.length > 1) {
3196 this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + ''));
3197 } else if (leaks.length) {
3198 this.fail(test, new Error('global leak detected: ' + leaks[0]));
3203 * Fail the given `test`.
3205 * @param {Test} test
3206 * @param {Error} err
3210 Runner.prototype.fail = function(test, err){
3212 test.state = 'failed';
3213 if ('string' == typeof err) {
3214 err = new Error('the string "' + err + '" was thrown, throw an Error :)');
3216 this.emit('fail', test, err);
3220 * Fail the given `hook` with `err`.
3222 * Hook failures (currently) hard-end due
3223 * to that fact that a failing hook will
3224 * surely cause subsequent tests to fail,
3225 * causing jumbled reporting.
3227 * @param {Hook} hook
3228 * @param {Error} err
3232 Runner.prototype.failHook = function(hook, err){
3233 this.fail(hook, err);
3238 * Run hook `name` callbacks and then invoke `fn()`.
3240 * @param {String} name
3241 * @param {Function} function
3245 Runner.prototype.hook = function(name, fn){
3246 var suite = this.suite
3247 , hooks = suite['_' + name]
3248 , ms = suite._timeout
3253 var hook = hooks[i];
3254 if (!hook) return fn();
3255 self.currentRunnable = hook;
3257 self.emit('hook', hook);
3259 hook.on('error', function(err){
3260 self.failHook(hook, err);
3263 hook.run(function(err){
3264 hook.removeAllListeners('error');
3265 if (err) return self.failHook(hook, err);
3266 self.emit('hook end', hook);
3271 process.nextTick(function(){
3277 * Run hook `name` for the given array of `suites`
3278 * in order, and callback `fn(err)`.
3280 * @param {String} name
3281 * @param {Array} suites
3282 * @param {Function} fn
3286 Runner.prototype.hooks = function(name, suites, fn){
3288 , orig = this.suite;
3290 function next(suite) {
3298 self.hook(name, function(err){
3312 * Run hooks from the top level down.
3314 * @param {String} name
3315 * @param {Function} fn
3319 Runner.prototype.hookUp = function(name, fn){
3320 var suites = [this.suite].concat(this.parents()).reverse();
3321 this.hooks(name, suites, fn);
3325 * Run hooks from the bottom up.
3327 * @param {String} name
3328 * @param {Function} fn
3332 Runner.prototype.hookDown = function(name, fn){
3333 var suites = [this.suite].concat(this.parents());
3334 this.hooks(name, suites, fn);
3338 * Return an array of parent Suites from
3339 * closest to furthest.
3345 Runner.prototype.parents = function(){
3346 var suite = this.suite
3348 while (suite = suite.parent) suites.push(suite);
3353 * Run the current test and callback `fn(err)`.
3355 * @param {Function} fn
3359 Runner.prototype.runTest = function(fn){
3360 var test = this.test
3364 test.on('error', function(err){
3365 self.fail(test, err);
3374 * Run tests in the given `suite` and invoke
3375 * the callback `fn()` when complete.
3377 * @param {Suite} suite
3378 * @param {Function} fn
3382 Runner.prototype.runTests = function(suite, fn){
3384 , tests = suite.tests
3387 function next(err) {
3388 // if we bail after first err
3389 if (self.failures && suite._bail) return fn();
3392 test = tests.shift();
3395 if (!test) return fn();
3398 if (!self._grep.test(test.fullTitle())) return next();
3402 self.emit('pending', test);
3403 self.emit('test end', test);
3407 // execute test and hook(s)
3408 self.emit('test', self.test = test);
3409 self.hookDown('beforeEach', function(){
3410 self.currentRunnable = self.test;
3411 self.runTest(function(err){
3415 self.fail(test, err);
3416 self.emit('test end', test);
3417 return self.hookUp('afterEach', next);
3420 test.state = 'passed';
3421 self.emit('pass', test);
3422 self.emit('test end', test);
3423 self.hookUp('afterEach', next);
3433 * Run the given `suite` and invoke the
3434 * callback `fn()` when complete.
3436 * @param {Suite} suite
3437 * @param {Function} fn
3441 Runner.prototype.runSuite = function(suite, fn){
3442 var total = this.grepTotal(suite)
3446 debug('run suite %s', suite.fullTitle());
3448 if (!total) return fn();
3450 this.emit('suite', this.suite = suite);
3453 var curr = suite.suites[i++];
3454 if (!curr) return done();
3455 self.runSuite(curr, next);
3460 self.hook('afterAll', function(){
3461 self.emit('suite end', suite);
3466 this.hook('beforeAll', function(){
3467 self.runTests(suite, next);
3472 * Handle uncaught exceptions.
3474 * @param {Error} err
3478 Runner.prototype.uncaught = function(err){
3479 debug('uncaught exception');
3480 var runnable = this.currentRunnable;
3481 if ('failed' == runnable.state) return;
3482 runnable.clearTimeout();
3483 err.uncaught = true;
3484 this.fail(runnable, err);
3486 // recover from test
3487 if ('test' == runnable.type) {
3488 this.emit('test end', runnable);
3489 this.hookUp('afterEach', this.next);
3498 * Run the root suite and invoke `fn(failures)`
3501 * @param {Function} fn
3502 * @return {Runner} for chaining
3506 Runner.prototype.run = function(fn){
3508 , fn = fn || function(){};
3513 this.on('end', function(){
3515 process.removeListener('uncaughtException', this.uncaught);
3521 this.runSuite(this.suite, function(){
3522 debug('finished running');
3526 // uncaught exception
3527 process.on('uncaughtException', function(err){
3534 }); // module: runner.js
3536 require.register("suite.js", function(module, exports, require){
3539 * Module dependencies.
3542 var EventEmitter = require('browser/events').EventEmitter
3543 , debug = require('browser/debug')('suite')
3544 , utils = require('./utils')
3545 , Hook = require('./hook');
3551 exports = module.exports = Suite;
3554 * Create a new `Suite` with the given `title`
3555 * and parent `Suite`. When a suite with the
3556 * same title is already present, that suite
3557 * is returned to provide nicer reporter
3558 * and more flexible meta-testing.
3560 * @param {Suite} parent
3561 * @param {String} title
3566 exports.create = function(parent, title){
3567 var suite = new Suite(title, parent.ctx);
3568 suite.parent = parent;
3569 title = suite.fullTitle();
3570 parent.addSuite(suite);
3575 * Initialize a new `Suite` with the given
3576 * `title` and `ctx`.
3578 * @param {String} title
3579 * @param {Context} ctx
3583 function Suite(title, ctx) {
3588 this._beforeEach = [];
3589 this._beforeAll = [];
3590 this._afterEach = [];
3591 this._afterAll = [];
3593 this._timeout = 2000;
3598 * Inherit from `EventEmitter.prototype`.
3601 Suite.prototype = new EventEmitter;
3602 Suite.prototype.constructor = Suite;
3606 * Return a clone of this `Suite`.
3612 Suite.prototype.clone = function(){
3613 var suite = new Suite(this.title);
3615 suite.ctx = this.ctx;
3616 suite.timeout(this.timeout());
3617 suite.bail(this.bail());
3622 * Set timeout `ms` or short-hand such as "2s".
3624 * @param {Number|String} ms
3625 * @return {Suite|Number} for chaining
3629 Suite.prototype.timeout = function(ms){
3630 if (0 == arguments.length) return this._timeout;
3631 if (String(ms).match(/s$/)) ms = parseFloat(ms) * 1000;
3632 debug('timeout %d', ms);
3633 this._timeout = parseInt(ms, 10);
3638 * Sets whether to bail after first error.
3640 * @parma {Boolean} bail
3641 * @return {Suite|Number} for chaining
3645 Suite.prototype.bail = function(bail){
3646 if (0 == arguments.length) return this._bail;
3647 debug('bail %s', bail);
3653 * Run `fn(test[, done])` before running tests.
3655 * @param {Function} fn
3656 * @return {Suite} for chaining
3660 Suite.prototype.beforeAll = function(fn){
3661 var hook = new Hook('"before all" hook', fn);
3663 hook.timeout(this.timeout());
3664 hook.ctx = this.ctx;
3665 this._beforeAll.push(hook);
3666 this.emit('beforeAll', hook);
3671 * Run `fn(test[, done])` after running tests.
3673 * @param {Function} fn
3674 * @return {Suite} for chaining
3678 Suite.prototype.afterAll = function(fn){
3679 var hook = new Hook('"after all" hook', fn);
3681 hook.timeout(this.timeout());
3682 hook.ctx = this.ctx;
3683 this._afterAll.push(hook);
3684 this.emit('afterAll', hook);
3689 * Run `fn(test[, done])` before each test case.
3691 * @param {Function} fn
3692 * @return {Suite} for chaining
3696 Suite.prototype.beforeEach = function(fn){
3697 var hook = new Hook('"before each" hook', fn);
3699 hook.timeout(this.timeout());
3700 hook.ctx = this.ctx;
3701 this._beforeEach.push(hook);
3702 this.emit('beforeEach', hook);
3707 * Run `fn(test[, done])` after each test case.
3709 * @param {Function} fn
3710 * @return {Suite} for chaining
3714 Suite.prototype.afterEach = function(fn){
3715 var hook = new Hook('"after each" hook', fn);
3717 hook.timeout(this.timeout());
3718 hook.ctx = this.ctx;
3719 this._afterEach.push(hook);
3720 this.emit('afterEach', hook);
3725 * Add a test `suite`.
3727 * @param {Suite} suite
3728 * @return {Suite} for chaining
3732 Suite.prototype.addSuite = function(suite){
3733 suite.parent = this;
3734 suite.timeout(this.timeout());
3735 suite.bail(this.bail());
3736 this.suites.push(suite);
3737 this.emit('suite', suite);
3742 * Add a `test` to this suite.
3744 * @param {Test} test
3745 * @return {Suite} for chaining
3749 Suite.prototype.addTest = function(test){
3751 test.timeout(this.timeout());
3752 test.ctx = this.ctx;
3753 this.tests.push(test);
3754 this.emit('test', test);
3759 * Return the full title generated by recursively
3760 * concatenating the parent's full title.
3766 Suite.prototype.fullTitle = function(){
3768 var full = this.parent.fullTitle();
3769 if (full) return full + ' ' + this.title;
3775 * Return the total number of tests.
3781 Suite.prototype.total = function(){
3782 return utils.reduce(this.suites, function(sum, suite){
3783 return sum + suite.total();
3784 }, 0) + this.tests.length;
3788 * Iterates through each suite recursively to find
3789 * all tests. Applies a function in the format
3792 * @param {Function} fn
3797 Suite.prototype.eachTest = function(fn){
3798 utils.forEach(this.tests, fn);
3799 utils.forEach(this.suites, function(suite){
3805 }); // module: suite.js
3807 require.register("test.js", function(module, exports, require){
3810 * Module dependencies.
3813 var Runnable = require('./runnable');
3819 module.exports = Test;
3822 * Initialize a new `Test` with the given `title` and callback `fn`.
3824 * @param {String} title
3825 * @param {Function} fn
3829 function Test(title, fn) {
3830 Runnable.call(this, title, fn);
3836 * Inherit from `Runnable.prototype`.
3839 Test.prototype = new Runnable;
3840 Test.prototype.constructor = Test;
3844 * Inspect the context void of private properties.
3850 Test.prototype.inspect = function(){
3851 return JSON.stringify(this, function(key, val){
3852 return '_' == key[0]
3859 }); // module: test.js
3861 require.register("utils.js", function(module, exports, require){
3864 * Module dependencies.
3867 var fs = require('browser/fs')
3868 , path = require('browser/path')
3870 , debug = require('browser/debug')('watch');
3873 * Ignored directories.
3876 var ignore = ['node_modules', '.git'];
3879 * Escape special characters in the given string of html.
3881 * @param {String} html
3886 exports.escape = function(html) {
3888 .replace(/&/g, '&')
3889 .replace(/"/g, '"')
3890 .replace(/</g, '<')
3891 .replace(/>/g, '>');
3895 * Array#forEach (<=IE8)
3897 * @param {Array} array
3898 * @param {Function} fn
3899 * @param {Object} scope
3903 exports.forEach = function(arr, fn, scope) {
3904 for (var i = 0, l = arr.length; i < l; i++)
3905 fn.call(scope, arr[i], i);
3909 * Array#indexOf (<=IE8)
3911 * @parma {Array} arr
3912 * @param {Object} obj to find index of
3913 * @param {Number} start
3917 exports.indexOf = function (arr, obj, start) {
3918 for (var i = start || 0, l = arr.length; i < l; i++) {
3926 * Array#reduce (<=IE8)
3928 * @param {Array} array
3929 * @param {Function} fn
3930 * @param {Object} initial value
3931 * @param {Object} scope
3935 exports.reduce = function(arr, fn, val, scope) {
3938 for (var i = 0, l = arr.length; i < l; i++) {
3939 rval = fn.call(scope, rval, arr[i], i, arr);
3946 * Array#filter (<=IE8)
3948 * @param {Array} array
3949 * @param {Function} fn
3950 * @param {Object} scope
3954 exports.filter = function(arr, fn, scope) {
3957 for (var i = 0, l = arr.length; i < l; i++) {
3959 if (fn.call(scope, val, i, arr))
3967 * Object.keys (<=IE8)
3969 * @param {Object} obj
3970 * @return {Array} keys
3974 exports.keys = Object.keys || function(obj) {
3976 , has = Object.prototype.hasOwnProperty // for `window` on <=IE8
3978 for (var key in obj) {
3979 if (has.call(obj, key)) {
3988 * Watch the given `files` for changes
3989 * and invoke `fn(file)` on modification.
3991 * @param {Array} files
3992 * @param {Function} fn
3996 exports.watch = function(files, fn){
3997 var options = { interval: 100 };
3998 files.forEach(function(file){
3999 debug('file %s', file);
4000 fs.watchFile(file, options, function(curr, prev){
4001 if (prev.mtime < curr.mtime) fn(file);
4010 function ignored(path){
4011 return !~ignore.indexOf(path);
4015 * Lookup files in the given `dir`.
4021 exports.files = function(dir, ret){
4026 .forEach(function(path){
4027 path = join(dir, path);
4028 if (fs.statSync(path).isDirectory()) {
4029 exports.files(path, ret);
4030 } else if (path.match(/\.(js|coffee)$/)) {
4039 * Compute a slug from the given `str`.
4041 * @param {String} str
4045 exports.slug = function(str){
4048 .replace(/ +/g, '-')
4049 .replace(/[^-\w]/g, '');
4051 }); // module: utils.js
4055 * These are meant only to allow
4056 * mocha.js to run untouched, not
4057 * to allow running node code in
4062 process.exit = function(status){};
4063 process.stdout = {};
4067 * next tick implementation.
4070 process.nextTick = (function(){
4071 // postMessage behaves badly on IE8
4072 if (window.ActiveXObject || !window.postMessage) {
4073 return function(fn){ fn() };
4076 // based on setZeroTimeout by David Baron
4077 // - http://dbaron.org/log/20100309-faster-timeouts
4079 , name = 'mocha-zero-timeout'
4081 window.addEventListener('message', function(e){
4082 if (e.source == window && e.data == name) {
4083 if (e.stopPropagation) e.stopPropagation();
4084 if (timeouts.length) timeouts.shift()();
4088 return function(fn){
4090 window.postMessage(name, '*');
4095 * Remove uncaughtException listener.
4098 process.removeListener = function(e){
4099 if ('uncaughtException' == e) {
4100 window.onerror = null;
4105 * Implements uncaughtException listener.
4108 process.on = function(e, fn){
4109 if ('uncaughtException' == e) {
4110 window.onerror = fn;
4118 window.mocha = require('mocha');
4122 var suite = new mocha.Suite('', new mocha.Context)
4123 , utils = mocha.utils
4127 * Highlight the given string of `js`.
4130 function highlight(js) {
4132 .replace(/</g, '<')
4133 .replace(/>/g, '>')
4134 .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
4135 .replace(/('.*?')/gm, '<span class="string">$1</span>')
4136 .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
4137 .replace(/(\d+)/gm, '<span class="number">$1</span>')
4138 .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
4139 .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
4143 * Highlight code contents.
4146 function highlightCode() {
4147 var code = document.getElementsByTagName('code');
4148 for (var i = 0, len = code.length; i < len; ++i) {
4149 code[i].innerHTML = highlight(code[i].innerHTML);
4154 * Parse the given `qs`.
4157 function parse(qs) {
4158 return utils.reduce(qs.replace('?', '').split('&'), function(obj, pair){
4159 var i = pair.indexOf('=')
4160 , key = pair.slice(0, i)
4161 , val = pair.slice(++i);
4163 obj[key] = decodeURIComponent(val);
4169 * Setup mocha with the given setting options.
4172 mocha.setup = function(opts){
4173 if ('string' === typeof opts) options.ui = opts;
4174 else options = opts;
4176 ui = mocha.interfaces[options.ui];
4177 if (!ui) throw new Error('invalid mocha interface "' + ui + '"');
4178 if (options.timeout) suite.timeout(options.timeout);
4180 suite.emit('pre-require', window);
4184 * Run mocha, returning the Runner.
4187 mocha.run = function(fn){
4189 var runner = new mocha.Runner(suite);
4190 var Reporter = options.reporter || mocha.reporters.HTML;
4191 var reporter = new Reporter(runner);
4192 var query = parse(window.location.search || "");
4193 if (query.grep) runner.grep(new RegExp(query.grep));
4194 if (options.ignoreLeaks) runner.ignoreLeaks = true;
4195 if (options.globals) runner.globals(options.globals);
4196 runner.globals(['location']);
4197 runner.on('end', highlightCode);
4198 return runner.run(fn);