├── .gitignore ├── History.md ├── Makefile ├── Readme.md ├── component.json ├── index.js ├── package.json └── test ├── expect.js ├── index.html ├── mocha.css ├── mocha.js ├── parse.js └── stringify.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | components 3 | build -------------------------------------------------------------------------------- /History.md: -------------------------------------------------------------------------------- 1 | 2 | 2.0.1 / 2021-02-02 3 | ================== 4 | 5 | * Bumped trim to 1.0.0 to resolve [CVE-2020-7753](https://snyk.io/vuln/SNYK-JS-TRIM-1017038) 6 | * add semicolon 7 | 8 | 2.0.0 / 2015-07-17 9 | ================== 10 | 11 | * respect `+`-encoded spaces in `#parse()` (#14, @sperand-io) 12 | * wrap `encodeURIComponent` and `decodeURIComponent` in `try/catch` (#14, @sperand-io) 13 | 14 | 1.3.3 / 2015-03-28 15 | ================== 16 | 17 | * index: don't keep creating regex object 18 | 19 | 1.3.2 / 2015-03-16 20 | ================== 21 | 22 | * package: fix browserify build, add missing "component-type" dep 23 | * package: fix "repository" field 24 | * component: update deps 25 | * pin deps and float devDeps with `~` 26 | 27 | 1.3.1 / 2014-06-12 28 | ================== 29 | 30 | * rename npm package to component-querystring 31 | 32 | 1.3.0 / 2014-04-14 33 | ================== 34 | 35 | * add array support 36 | 37 | 1.2.0 / 2013-12-07 38 | ================== 39 | 40 | * remove leading `?` 41 | 42 | 1.1.0 / 2013-04-04 43 | ================== 44 | 45 | * remove reduce dep 46 | * add trim dep 47 | 48 | 1.0.0 / 2012-11-08 49 | ================== 50 | 51 | * add build makefile targets 52 | * add reduce and trim deps 53 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | build: index.js components 3 | @component build --dev 4 | 5 | components: 6 | @component install --dev 7 | 8 | clean: 9 | rm -fr build components 10 | 11 | test: build 12 | @open test/index.html 13 | 14 | .PHONY: clean test 15 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | 2 | # querystring 3 | 4 | Simple key / value pair query-string parser and formatter. 5 | 6 | ## Installation 7 | 8 | ``` 9 | $ component install component/querystring 10 | ``` 11 | 12 | ## API 13 | 14 | ### .parse(string) 15 | 16 | Parse the given query `string`: 17 | 18 | ```js 19 | var query = require('querystring'); 20 | query.parse('name=tobi&species=ferret'); 21 | // => { name: 'tobi', species: 'ferret' } 22 | ``` 23 | 24 | ### .stringify(object) 25 | 26 | Stringify the given `object`: 27 | 28 | ```js 29 | var query = require('querystring'); 30 | query.stringify({ name: 'tobi', species: 'ferret' }); 31 | // => "name=tobi&species=ferret" 32 | ``` 33 | 34 | ## License 35 | 36 | MIT 37 | -------------------------------------------------------------------------------- /component.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "querystring", 3 | "version": "2.0.1", 4 | "description": "Simple key/value pair query-string parsing", 5 | "repository": "component/querystring", 6 | "keywords": [ 7 | "query", 8 | "querystring", 9 | "query-string", 10 | "parser" 11 | ], 12 | "scripts": [ 13 | "index.js" 14 | ], 15 | "dependencies": { 16 | "component/trim": "0.0.1", 17 | "component/type": "1.1.0" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Module dependencies. 4 | */ 5 | 6 | var trim = require('trim'); 7 | var type = require('type'); 8 | 9 | var pattern = /(\w+)\[(\d+)\]/; 10 | 11 | /** 12 | * Safely encode the given string 13 | * 14 | * @param {String} str 15 | * @return {String} 16 | * @api private 17 | */ 18 | 19 | var encode = function(str) { 20 | try { 21 | return encodeURIComponent(str); 22 | } catch (e) { 23 | return str; 24 | } 25 | }; 26 | 27 | /** 28 | * Safely decode the string 29 | * 30 | * @param {String} str 31 | * @return {String} 32 | * @api private 33 | */ 34 | 35 | var decode = function(str) { 36 | try { 37 | return decodeURIComponent(str.replace(/\+/g, ' ')); 38 | } catch (e) { 39 | return str; 40 | } 41 | } 42 | 43 | /** 44 | * Parse the given query `str`. 45 | * 46 | * @param {String} str 47 | * @return {Object} 48 | * @api public 49 | */ 50 | 51 | exports.parse = function(str){ 52 | if ('string' != typeof str) return {}; 53 | 54 | str = trim(str); 55 | if ('' == str) return {}; 56 | if ('?' == str.charAt(0)) str = str.slice(1); 57 | 58 | var obj = {}; 59 | var pairs = str.split('&'); 60 | for (var i = 0; i < pairs.length; i++) { 61 | var parts = pairs[i].split('='); 62 | var key = decode(parts[0]); 63 | var m; 64 | 65 | if (m = pattern.exec(key)) { 66 | obj[m[1]] = obj[m[1]] || []; 67 | obj[m[1]][m[2]] = decode(parts[1]); 68 | continue; 69 | } 70 | 71 | obj[parts[0]] = null == parts[1] 72 | ? '' 73 | : decode(parts[1]); 74 | } 75 | 76 | return obj; 77 | }; 78 | 79 | /** 80 | * Stringify the given `obj`. 81 | * 82 | * @param {Object} obj 83 | * @return {String} 84 | * @api public 85 | */ 86 | 87 | exports.stringify = function(obj){ 88 | if (!obj) return ''; 89 | var pairs = []; 90 | 91 | for (var key in obj) { 92 | var value = obj[key]; 93 | 94 | if ('array' == type(value)) { 95 | for (var i = 0; i < value.length; ++i) { 96 | pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i])); 97 | } 98 | continue; 99 | } 100 | 101 | pairs.push(encode(key) + '=' + encode(obj[key])); 102 | } 103 | 104 | return pairs.join('&'); 105 | }; 106 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "component-querystring", 3 | "description": "Simple key/value pair query-string parsing", 4 | "version": "2.0.1", 5 | "dependencies": { 6 | "trim": "1.0.0", 7 | "component-type": "1.1.0" 8 | }, 9 | "browser": { 10 | "type": "component-type" 11 | }, 12 | "devDependencies": { 13 | "mocha": "~2.0.1", 14 | "should": "~4.4.1" 15 | }, 16 | "component": { 17 | "scripts": { 18 | "querystring": "index.js" 19 | } 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "https://github.com/component/querystring.git" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /test/expect.js: -------------------------------------------------------------------------------- 1 | 2 | (function (global, module) { 3 | 4 | if ('undefined' == typeof module) { 5 | var module = { exports: {} } 6 | , exports = module.exports 7 | } 8 | 9 | /** 10 | * Exports. 11 | */ 12 | 13 | module.exports = expect; 14 | expect.Assertion = Assertion; 15 | 16 | /** 17 | * Exports version. 18 | */ 19 | 20 | expect.version = '0.1.2'; 21 | 22 | /** 23 | * Possible assertion flags. 24 | */ 25 | 26 | var flags = { 27 | not: ['to', 'be', 'have', 'include', 'only'] 28 | , to: ['be', 'have', 'include', 'only', 'not'] 29 | , only: ['have'] 30 | , have: ['own'] 31 | , be: ['an'] 32 | }; 33 | 34 | function expect (obj) { 35 | return new Assertion(obj); 36 | } 37 | 38 | /** 39 | * Constructor 40 | * 41 | * @api private 42 | */ 43 | 44 | function Assertion (obj, flag, parent) { 45 | this.obj = obj; 46 | this.flags = {}; 47 | 48 | if (undefined != parent) { 49 | this.flags[flag] = true; 50 | 51 | for (var i in parent.flags) { 52 | if (parent.flags.hasOwnProperty(i)) { 53 | this.flags[i] = true; 54 | } 55 | } 56 | } 57 | 58 | var $flags = flag ? flags[flag] : keys(flags) 59 | , self = this 60 | 61 | if ($flags) { 62 | for (var i = 0, l = $flags.length; i < l; i++) { 63 | // avoid recursion 64 | if (this.flags[$flags[i]]) continue; 65 | 66 | var name = $flags[i] 67 | , assertion = new Assertion(this.obj, name, this) 68 | 69 | if ('function' == typeof Assertion.prototype[name]) { 70 | // clone the function, make sure we dont touch the prot reference 71 | var old = this[name]; 72 | this[name] = function () { 73 | return old.apply(self, arguments); 74 | } 75 | 76 | for (var fn in Assertion.prototype) { 77 | if (Assertion.prototype.hasOwnProperty(fn) && fn != name) { 78 | this[name][fn] = bind(assertion[fn], assertion); 79 | } 80 | } 81 | } else { 82 | this[name] = assertion; 83 | } 84 | } 85 | } 86 | }; 87 | 88 | /** 89 | * Performs an assertion 90 | * 91 | * @api private 92 | */ 93 | 94 | Assertion.prototype.assert = function (truth, msg, error) { 95 | var msg = this.flags.not ? error : msg 96 | , ok = this.flags.not ? !truth : truth; 97 | 98 | if (!ok) { 99 | throw new Error(msg.call(this)); 100 | } 101 | 102 | this.and = new Assertion(this.obj); 103 | }; 104 | 105 | /** 106 | * Check if the value is truthy 107 | * 108 | * @api public 109 | */ 110 | 111 | Assertion.prototype.ok = function () { 112 | this.assert( 113 | !!this.obj 114 | , function(){ return 'expected ' + i(this.obj) + ' to be truthy' } 115 | , function(){ return 'expected ' + i(this.obj) + ' to be falsy' }); 116 | }; 117 | 118 | /** 119 | * Assert that the function throws. 120 | * 121 | * @param {Function|RegExp} callback, or regexp to match error string against 122 | * @api public 123 | */ 124 | 125 | Assertion.prototype.throwError = 126 | Assertion.prototype.throwException = function (fn) { 127 | expect(this.obj).to.be.a('function'); 128 | 129 | var thrown = false 130 | , not = this.flags.not 131 | 132 | try { 133 | this.obj(); 134 | } catch (e) { 135 | if ('function' == typeof fn) { 136 | fn(e); 137 | } else if ('object' == typeof fn) { 138 | var subject = 'string' == typeof e ? e : e.message; 139 | if (not) { 140 | expect(subject).to.not.match(fn); 141 | } else { 142 | expect(subject).to.match(fn); 143 | } 144 | } 145 | thrown = true; 146 | } 147 | 148 | if ('object' == typeof fn && not) { 149 | // in the presence of a matcher, ensure the `not` only applies to 150 | // the matching. 151 | this.flags.not = false; 152 | } 153 | 154 | var name = this.obj.name || 'fn'; 155 | this.assert( 156 | thrown 157 | , function(){ return 'expected ' + name + ' to throw an exception' } 158 | , function(){ return 'expected ' + name + ' not to throw an exception' }); 159 | }; 160 | 161 | /** 162 | * Checks if the array is empty. 163 | * 164 | * @api public 165 | */ 166 | 167 | Assertion.prototype.empty = function () { 168 | var expectation; 169 | 170 | if ('object' == typeof this.obj && null !== this.obj && !isArray(this.obj)) { 171 | if ('number' == typeof this.obj.length) { 172 | expectation = !this.obj.length; 173 | } else { 174 | expectation = !keys(this.obj).length; 175 | } 176 | } else { 177 | if ('string' != typeof this.obj) { 178 | expect(this.obj).to.be.an('object'); 179 | } 180 | 181 | expect(this.obj).to.have.property('length'); 182 | expectation = !this.obj.length; 183 | } 184 | 185 | this.assert( 186 | expectation 187 | , function(){ return 'expected ' + i(this.obj) + ' to be empty' } 188 | , function(){ return 'expected ' + i(this.obj) + ' to not be empty' }); 189 | return this; 190 | }; 191 | 192 | /** 193 | * Checks if the obj exactly equals another. 194 | * 195 | * @api public 196 | */ 197 | 198 | Assertion.prototype.be = 199 | Assertion.prototype.equal = function (obj) { 200 | this.assert( 201 | obj === this.obj 202 | , function(){ return 'expected ' + i(this.obj) + ' to equal ' + i(obj) } 203 | , function(){ return 'expected ' + i(this.obj) + ' to not equal ' + i(obj) }); 204 | return this; 205 | }; 206 | 207 | /** 208 | * Checks if the obj sortof equals another. 209 | * 210 | * @api public 211 | */ 212 | 213 | Assertion.prototype.eql = function (obj) { 214 | this.assert( 215 | expect.eql(obj, this.obj) 216 | , function(){ return 'expected ' + i(this.obj) + ' to sort of equal ' + i(obj) } 217 | , function(){ return 'expected ' + i(this.obj) + ' to sort of not equal ' + i(obj) }); 218 | return this; 219 | }; 220 | 221 | /** 222 | * Assert within start to finish (inclusive). 223 | * 224 | * @param {Number} start 225 | * @param {Number} finish 226 | * @api public 227 | */ 228 | 229 | Assertion.prototype.within = function (start, finish) { 230 | var range = start + '..' + finish; 231 | this.assert( 232 | this.obj >= start && this.obj <= finish 233 | , function(){ return 'expected ' + i(this.obj) + ' to be within ' + range } 234 | , function(){ return 'expected ' + i(this.obj) + ' to not be within ' + range }); 235 | return this; 236 | }; 237 | 238 | /** 239 | * Assert typeof / instance of 240 | * 241 | * @api public 242 | */ 243 | 244 | Assertion.prototype.a = 245 | Assertion.prototype.an = function (type) { 246 | if ('string' == typeof type) { 247 | // proper english in error msg 248 | var n = /^[aeiou]/.test(type) ? 'n' : ''; 249 | 250 | // typeof with support for 'array' 251 | this.assert( 252 | 'array' == type ? isArray(this.obj) : 253 | 'object' == type 254 | ? 'object' == typeof this.obj && null !== this.obj 255 | : type == typeof this.obj 256 | , function(){ return 'expected ' + i(this.obj) + ' to be a' + n + ' ' + type } 257 | , function(){ return 'expected ' + i(this.obj) + ' not to be a' + n + ' ' + type }); 258 | } else { 259 | // instanceof 260 | var name = type.name || 'supplied constructor'; 261 | this.assert( 262 | this.obj instanceof type 263 | , function(){ return 'expected ' + i(this.obj) + ' to be an instance of ' + name } 264 | , function(){ return 'expected ' + i(this.obj) + ' not to be an instance of ' + name }); 265 | } 266 | 267 | return this; 268 | }; 269 | 270 | /** 271 | * Assert numeric value above _n_. 272 | * 273 | * @param {Number} n 274 | * @api public 275 | */ 276 | 277 | Assertion.prototype.greaterThan = 278 | Assertion.prototype.above = function (n) { 279 | this.assert( 280 | this.obj > n 281 | , function(){ return 'expected ' + i(this.obj) + ' to be above ' + n } 282 | , function(){ return 'expected ' + i(this.obj) + ' to be below ' + n }); 283 | return this; 284 | }; 285 | 286 | /** 287 | * Assert numeric value below _n_. 288 | * 289 | * @param {Number} n 290 | * @api public 291 | */ 292 | 293 | Assertion.prototype.lessThan = 294 | Assertion.prototype.below = function (n) { 295 | this.assert( 296 | this.obj < n 297 | , function(){ return 'expected ' + i(this.obj) + ' to be below ' + n } 298 | , function(){ return 'expected ' + i(this.obj) + ' to be above ' + n }); 299 | return this; 300 | }; 301 | 302 | /** 303 | * Assert string value matches _regexp_. 304 | * 305 | * @param {RegExp} regexp 306 | * @api public 307 | */ 308 | 309 | Assertion.prototype.match = function (regexp) { 310 | this.assert( 311 | regexp.exec(this.obj) 312 | , function(){ return 'expected ' + i(this.obj) + ' to match ' + regexp } 313 | , function(){ return 'expected ' + i(this.obj) + ' not to match ' + regexp }); 314 | return this; 315 | }; 316 | 317 | /** 318 | * Assert property "length" exists and has value of _n_. 319 | * 320 | * @param {Number} n 321 | * @api public 322 | */ 323 | 324 | Assertion.prototype.length = function (n) { 325 | expect(this.obj).to.have.property('length'); 326 | var len = this.obj.length; 327 | this.assert( 328 | n == len 329 | , function(){ return 'expected ' + i(this.obj) + ' to have a length of ' + n + ' but got ' + len } 330 | , function(){ return 'expected ' + i(this.obj) + ' to not have a length of ' + len }); 331 | return this; 332 | }; 333 | 334 | /** 335 | * Assert property _name_ exists, with optional _val_. 336 | * 337 | * @param {String} name 338 | * @param {Mixed} val 339 | * @api public 340 | */ 341 | 342 | Assertion.prototype.property = function (name, val) { 343 | if (this.flags.own) { 344 | this.assert( 345 | Object.prototype.hasOwnProperty.call(this.obj, name) 346 | , function(){ return 'expected ' + i(this.obj) + ' to have own property ' + i(name) } 347 | , function(){ return 'expected ' + i(this.obj) + ' to not have own property ' + i(name) }); 348 | return this; 349 | } 350 | 351 | if (this.flags.not && undefined !== val) { 352 | if (undefined === this.obj[name]) { 353 | throw new Error(i(this.obj) + ' has no property ' + i(name)); 354 | } 355 | } else { 356 | var hasProp; 357 | try { 358 | hasProp = name in this.obj 359 | } catch (e) { 360 | hasProp = undefined !== this.obj[name] 361 | } 362 | 363 | this.assert( 364 | hasProp 365 | , function(){ return 'expected ' + i(this.obj) + ' to have a property ' + i(name) } 366 | , function(){ return 'expected ' + i(this.obj) + ' to not have a property ' + i(name) }); 367 | } 368 | 369 | if (undefined !== val) { 370 | this.assert( 371 | val === this.obj[name] 372 | , function(){ return 'expected ' + i(this.obj) + ' to have a property ' + i(name) 373 | + ' of ' + i(val) + ', but got ' + i(this.obj[name]) } 374 | , function(){ return 'expected ' + i(this.obj) + ' to not have a property ' + i(name) 375 | + ' of ' + i(val) }); 376 | } 377 | 378 | this.obj = this.obj[name]; 379 | return this; 380 | }; 381 | 382 | /** 383 | * Assert that the array contains _obj_ or string contains _obj_. 384 | * 385 | * @param {Mixed} obj|string 386 | * @api public 387 | */ 388 | 389 | Assertion.prototype.string = 390 | Assertion.prototype.contain = function (obj) { 391 | if ('string' == typeof this.obj) { 392 | this.assert( 393 | ~this.obj.indexOf(obj) 394 | , function(){ return 'expected ' + i(this.obj) + ' to contain ' + i(obj) } 395 | , function(){ return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) }); 396 | } else { 397 | this.assert( 398 | ~indexOf(this.obj, obj) 399 | , function(){ return 'expected ' + i(this.obj) + ' to contain ' + i(obj) } 400 | , function(){ return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) }); 401 | } 402 | return this; 403 | }; 404 | 405 | /** 406 | * Assert exact keys or inclusion of keys by using 407 | * the `.own` modifier. 408 | * 409 | * @param {Array|String ...} keys 410 | * @api public 411 | */ 412 | 413 | Assertion.prototype.key = 414 | Assertion.prototype.keys = function ($keys) { 415 | var str 416 | , ok = true; 417 | 418 | $keys = isArray($keys) 419 | ? $keys 420 | : Array.prototype.slice.call(arguments); 421 | 422 | if (!$keys.length) throw new Error('keys required'); 423 | 424 | var actual = keys(this.obj) 425 | , len = $keys.length; 426 | 427 | // Inclusion 428 | ok = every($keys, function (key) { 429 | return ~indexOf(actual, key); 430 | }); 431 | 432 | // Strict 433 | if (!this.flags.not && this.flags.only) { 434 | ok = ok && $keys.length == actual.length; 435 | } 436 | 437 | // Key string 438 | if (len > 1) { 439 | $keys = map($keys, function (key) { 440 | return i(key); 441 | }); 442 | var last = $keys.pop(); 443 | str = $keys.join(', ') + ', and ' + last; 444 | } else { 445 | str = i($keys[0]); 446 | } 447 | 448 | // Form 449 | str = (len > 1 ? 'keys ' : 'key ') + str; 450 | 451 | // Have / include 452 | str = (!this.flags.only ? 'include ' : 'only have ') + str; 453 | 454 | // Assertion 455 | this.assert( 456 | ok 457 | , function(){ return 'expected ' + i(this.obj) + ' to ' + str } 458 | , function(){ return 'expected ' + i(this.obj) + ' to not ' + str }); 459 | 460 | return this; 461 | }; 462 | /** 463 | * Assert a failure. 464 | * 465 | * @param {String ...} custom message 466 | * @api public 467 | */ 468 | Assertion.prototype.fail = function (msg) { 469 | msg = msg || "explicit failure"; 470 | this.assert(false, msg, msg); 471 | return this; 472 | }; 473 | 474 | /** 475 | * Function bind implementation. 476 | */ 477 | 478 | function bind (fn, scope) { 479 | return function () { 480 | return fn.apply(scope, arguments); 481 | } 482 | } 483 | 484 | /** 485 | * Array every compatibility 486 | * 487 | * @see bit.ly/5Fq1N2 488 | * @api public 489 | */ 490 | 491 | function every (arr, fn, thisObj) { 492 | var scope = thisObj || global; 493 | for (var i = 0, j = arr.length; i < j; ++i) { 494 | if (!fn.call(scope, arr[i], i, arr)) { 495 | return false; 496 | } 497 | } 498 | return true; 499 | }; 500 | 501 | /** 502 | * Array indexOf compatibility. 503 | * 504 | * @see bit.ly/a5Dxa2 505 | * @api public 506 | */ 507 | 508 | function indexOf (arr, o, i) { 509 | if (Array.prototype.indexOf) { 510 | return Array.prototype.indexOf.call(arr, o, i); 511 | } 512 | 513 | if (arr.length === undefined) { 514 | return -1; 515 | } 516 | 517 | for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0 518 | ; i < j && arr[i] !== o; i++); 519 | 520 | return j <= i ? -1 : i; 521 | }; 522 | 523 | // https://gist.github.com/1044128/ 524 | var getOuterHTML = function(element) { 525 | if ('outerHTML' in element) return element.outerHTML; 526 | var ns = "http://www.w3.org/1999/xhtml"; 527 | var container = document.createElementNS(ns, '_'); 528 | var elemProto = (window.HTMLElement || window.Element).prototype; 529 | var xmlSerializer = new XMLSerializer(); 530 | var html; 531 | if (document.xmlVersion) { 532 | return xmlSerializer.serializeToString(element); 533 | } else { 534 | container.appendChild(element.cloneNode(false)); 535 | html = container.innerHTML.replace('><', '>' + element.innerHTML + '<'); 536 | container.innerHTML = ''; 537 | return html; 538 | } 539 | }; 540 | 541 | // Returns true if object is a DOM element. 542 | var isDOMElement = function (object) { 543 | if (typeof HTMLElement === 'object') { 544 | return object instanceof HTMLElement; 545 | } else { 546 | return object && 547 | typeof object === 'object' && 548 | object.nodeType === 1 && 549 | typeof object.nodeName === 'string'; 550 | } 551 | }; 552 | 553 | /** 554 | * Inspects an object. 555 | * 556 | * @see taken from node.js `util` module (copyright Joyent, MIT license) 557 | * @api private 558 | */ 559 | 560 | function i (obj, showHidden, depth) { 561 | var seen = []; 562 | 563 | function stylize (str) { 564 | return str; 565 | }; 566 | 567 | function format (value, recurseTimes) { 568 | // Provide a hook for user-specified inspect functions. 569 | // Check that value is an object with an inspect function on it 570 | if (value && typeof value.inspect === 'function' && 571 | // Filter out the util module, it's inspect function is special 572 | value !== exports && 573 | // Also filter out any prototype objects using the circular check. 574 | !(value.constructor && value.constructor.prototype === value)) { 575 | return value.inspect(recurseTimes); 576 | } 577 | 578 | // Primitive types cannot have properties 579 | switch (typeof value) { 580 | case 'undefined': 581 | return stylize('undefined', 'undefined'); 582 | 583 | case 'string': 584 | var simple = '\'' + json.stringify(value).replace(/^"|"$/g, '') 585 | .replace(/'/g, "\\'") 586 | .replace(/\\"/g, '"') + '\''; 587 | return stylize(simple, 'string'); 588 | 589 | case 'number': 590 | return stylize('' + value, 'number'); 591 | 592 | case 'boolean': 593 | return stylize('' + value, 'boolean'); 594 | } 595 | // For some reason typeof null is "object", so special case here. 596 | if (value === null) { 597 | return stylize('null', 'null'); 598 | } 599 | 600 | if (isDOMElement(value)) { 601 | return getOuterHTML(value); 602 | } 603 | 604 | // Look up the keys of the object. 605 | var visible_keys = keys(value); 606 | var $keys = showHidden ? Object.getOwnPropertyNames(value) : visible_keys; 607 | 608 | // Functions without properties can be shortcutted. 609 | if (typeof value === 'function' && $keys.length === 0) { 610 | if (isRegExp(value)) { 611 | return stylize('' + value, 'regexp'); 612 | } else { 613 | var name = value.name ? ': ' + value.name : ''; 614 | return stylize('[Function' + name + ']', 'special'); 615 | } 616 | } 617 | 618 | // Dates without properties can be shortcutted 619 | if (isDate(value) && $keys.length === 0) { 620 | return stylize(value.toUTCString(), 'date'); 621 | } 622 | 623 | var base, type, braces; 624 | // Determine the object type 625 | if (isArray(value)) { 626 | type = 'Array'; 627 | braces = ['[', ']']; 628 | } else { 629 | type = 'Object'; 630 | braces = ['{', '}']; 631 | } 632 | 633 | // Make functions say that they are functions 634 | if (typeof value === 'function') { 635 | var n = value.name ? ': ' + value.name : ''; 636 | base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']'; 637 | } else { 638 | base = ''; 639 | } 640 | 641 | // Make dates with properties first say the date 642 | if (isDate(value)) { 643 | base = ' ' + value.toUTCString(); 644 | } 645 | 646 | if ($keys.length === 0) { 647 | return braces[0] + base + braces[1]; 648 | } 649 | 650 | if (recurseTimes < 0) { 651 | if (isRegExp(value)) { 652 | return stylize('' + value, 'regexp'); 653 | } else { 654 | return stylize('[Object]', 'special'); 655 | } 656 | } 657 | 658 | seen.push(value); 659 | 660 | var output = map($keys, function (key) { 661 | var name, str; 662 | if (value.__lookupGetter__) { 663 | if (value.__lookupGetter__(key)) { 664 | if (value.__lookupSetter__(key)) { 665 | str = stylize('[Getter/Setter]', 'special'); 666 | } else { 667 | str = stylize('[Getter]', 'special'); 668 | } 669 | } else { 670 | if (value.__lookupSetter__(key)) { 671 | str = stylize('[Setter]', 'special'); 672 | } 673 | } 674 | } 675 | if (indexOf(visible_keys, key) < 0) { 676 | name = '[' + key + ']'; 677 | } 678 | if (!str) { 679 | if (indexOf(seen, value[key]) < 0) { 680 | if (recurseTimes === null) { 681 | str = format(value[key]); 682 | } else { 683 | str = format(value[key], recurseTimes - 1); 684 | } 685 | if (str.indexOf('\n') > -1) { 686 | if (isArray(value)) { 687 | str = map(str.split('\n'), function (line) { 688 | return ' ' + line; 689 | }).join('\n').substr(2); 690 | } else { 691 | str = '\n' + map(str.split('\n'), function (line) { 692 | return ' ' + line; 693 | }).join('\n'); 694 | } 695 | } 696 | } else { 697 | str = stylize('[Circular]', 'special'); 698 | } 699 | } 700 | if (typeof name === 'undefined') { 701 | if (type === 'Array' && key.match(/^\d+$/)) { 702 | return str; 703 | } 704 | name = json.stringify('' + key); 705 | if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { 706 | name = name.substr(1, name.length - 2); 707 | name = stylize(name, 'name'); 708 | } else { 709 | name = name.replace(/'/g, "\\'") 710 | .replace(/\\"/g, '"') 711 | .replace(/(^"|"$)/g, "'"); 712 | name = stylize(name, 'string'); 713 | } 714 | } 715 | 716 | return name + ': ' + str; 717 | }); 718 | 719 | seen.pop(); 720 | 721 | var numLinesEst = 0; 722 | var length = reduce(output, function (prev, cur) { 723 | numLinesEst++; 724 | if (indexOf(cur, '\n') >= 0) numLinesEst++; 725 | return prev + cur.length + 1; 726 | }, 0); 727 | 728 | if (length > 50) { 729 | output = braces[0] + 730 | (base === '' ? '' : base + '\n ') + 731 | ' ' + 732 | output.join(',\n ') + 733 | ' ' + 734 | braces[1]; 735 | 736 | } else { 737 | output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; 738 | } 739 | 740 | return output; 741 | } 742 | return format(obj, (typeof depth === 'undefined' ? 2 : depth)); 743 | }; 744 | 745 | function isArray (ar) { 746 | return Object.prototype.toString.call(ar) == '[object Array]'; 747 | }; 748 | 749 | function isRegExp(re) { 750 | var s; 751 | try { 752 | s = '' + re; 753 | } catch (e) { 754 | return false; 755 | } 756 | 757 | return re instanceof RegExp || // easy case 758 | // duck-type for context-switching evalcx case 759 | typeof(re) === 'function' && 760 | re.constructor.name === 'RegExp' && 761 | re.compile && 762 | re.test && 763 | re.exec && 764 | s.match(/^\/.*\/[gim]{0,3}$/); 765 | }; 766 | 767 | function isDate(d) { 768 | if (d instanceof Date) return true; 769 | return false; 770 | }; 771 | 772 | function keys (obj) { 773 | if (Object.keys) { 774 | return Object.keys(obj); 775 | } 776 | 777 | var keys = []; 778 | 779 | for (var i in obj) { 780 | if (Object.prototype.hasOwnProperty.call(obj, i)) { 781 | keys.push(i); 782 | } 783 | } 784 | 785 | return keys; 786 | } 787 | 788 | function map (arr, mapper, that) { 789 | if (Array.prototype.map) { 790 | return Array.prototype.map.call(arr, mapper, that); 791 | } 792 | 793 | var other= new Array(arr.length); 794 | 795 | for (var i= 0, n = arr.length; i= 2) { 821 | var rv = arguments[1]; 822 | } else { 823 | do { 824 | if (i in this) { 825 | rv = this[i++]; 826 | break; 827 | } 828 | 829 | // if array contains no values, no initial value to return 830 | if (++i >= len) 831 | throw new TypeError(); 832 | } while (true); 833 | } 834 | 835 | for (; i < len; i++) { 836 | if (i in this) 837 | rv = fun.call(null, rv, this[i], i, this); 838 | } 839 | 840 | return rv; 841 | }; 842 | 843 | /** 844 | * Asserts deep equality 845 | * 846 | * @see taken from node.js `assert` module (copyright Joyent, MIT license) 847 | * @api private 848 | */ 849 | 850 | expect.eql = function eql (actual, expected) { 851 | // 7.1. All identical values are equivalent, as determined by ===. 852 | if (actual === expected) { 853 | return true; 854 | } else if ('undefined' != typeof Buffer 855 | && Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { 856 | if (actual.length != expected.length) return false; 857 | 858 | for (var i = 0; i < actual.length; i++) { 859 | if (actual[i] !== expected[i]) return false; 860 | } 861 | 862 | return true; 863 | 864 | // 7.2. If the expected value is a Date object, the actual value is 865 | // equivalent if it is also a Date object that refers to the same time. 866 | } else if (actual instanceof Date && expected instanceof Date) { 867 | return actual.getTime() === expected.getTime(); 868 | 869 | // 7.3. Other pairs that do not both pass typeof value == "object", 870 | // equivalence is determined by ==. 871 | } else if (typeof actual != 'object' && typeof expected != 'object') { 872 | return actual == expected; 873 | 874 | // 7.4. For all other Object pairs, including Array objects, equivalence is 875 | // determined by having the same number of owned properties (as verified 876 | // with Object.prototype.hasOwnProperty.call), the same set of keys 877 | // (although not necessarily the same order), equivalent values for every 878 | // corresponding key, and an identical "prototype" property. Note: this 879 | // accounts for both named and indexed properties on Arrays. 880 | } else { 881 | return objEquiv(actual, expected); 882 | } 883 | } 884 | 885 | function isUndefinedOrNull (value) { 886 | return value === null || value === undefined; 887 | } 888 | 889 | function isArguments (object) { 890 | return Object.prototype.toString.call(object) == '[object Arguments]'; 891 | } 892 | 893 | function objEquiv (a, b) { 894 | if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) 895 | return false; 896 | // an identical "prototype" property. 897 | if (a.prototype !== b.prototype) return false; 898 | //~~~I've managed to break Object.keys through screwy arguments passing. 899 | // Converting to array solves the problem. 900 | if (isArguments(a)) { 901 | if (!isArguments(b)) { 902 | return false; 903 | } 904 | a = pSlice.call(a); 905 | b = pSlice.call(b); 906 | return expect.eql(a, b); 907 | } 908 | try{ 909 | var ka = keys(a), 910 | kb = keys(b), 911 | key, i; 912 | } catch (e) {//happens when one is a string literal and the other isn't 913 | return false; 914 | } 915 | // having the same number of owned properties (keys incorporates hasOwnProperty) 916 | if (ka.length != kb.length) 917 | return false; 918 | //the same set of keys (although not necessarily the same order), 919 | ka.sort(); 920 | kb.sort(); 921 | //~~~cheap key test 922 | for (i = ka.length - 1; i >= 0; i--) { 923 | if (ka[i] != kb[i]) 924 | return false; 925 | } 926 | //equivalent values for every corresponding key, and 927 | //~~~possibly expensive deep test 928 | for (i = ka.length - 1; i >= 0; i--) { 929 | key = ka[i]; 930 | if (!expect.eql(a[key], b[key])) 931 | return false; 932 | } 933 | return true; 934 | } 935 | 936 | var json = (function () { 937 | "use strict"; 938 | 939 | if ('object' == typeof JSON && JSON.parse && JSON.stringify) { 940 | return { 941 | parse: nativeJSON.parse 942 | , stringify: nativeJSON.stringify 943 | } 944 | } 945 | 946 | var JSON = {}; 947 | 948 | function f(n) { 949 | // Format integers to have at least two digits. 950 | return n < 10 ? '0' + n : n; 951 | } 952 | 953 | function date(d, key) { 954 | return isFinite(d.valueOf()) ? 955 | d.getUTCFullYear() + '-' + 956 | f(d.getUTCMonth() + 1) + '-' + 957 | f(d.getUTCDate()) + 'T' + 958 | f(d.getUTCHours()) + ':' + 959 | f(d.getUTCMinutes()) + ':' + 960 | f(d.getUTCSeconds()) + 'Z' : null; 961 | }; 962 | 963 | var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, 964 | escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, 965 | gap, 966 | indent, 967 | meta = { // table of character substitutions 968 | '\b': '\\b', 969 | '\t': '\\t', 970 | '\n': '\\n', 971 | '\f': '\\f', 972 | '\r': '\\r', 973 | '"' : '\\"', 974 | '\\': '\\\\' 975 | }, 976 | rep; 977 | 978 | 979 | function quote(string) { 980 | 981 | // If the string contains no control characters, no quote characters, and no 982 | // backslash characters, then we can safely slap some quotes around it. 983 | // Otherwise we must also replace the offending characters with safe escape 984 | // sequences. 985 | 986 | escapable.lastIndex = 0; 987 | return escapable.test(string) ? '"' + string.replace(escapable, function (a) { 988 | var c = meta[a]; 989 | return typeof c === 'string' ? c : 990 | '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); 991 | }) + '"' : '"' + string + '"'; 992 | } 993 | 994 | 995 | function str(key, holder) { 996 | 997 | // Produce a string from holder[key]. 998 | 999 | var i, // The loop counter. 1000 | k, // The member key. 1001 | v, // The member value. 1002 | length, 1003 | mind = gap, 1004 | partial, 1005 | value = holder[key]; 1006 | 1007 | // If the value has a toJSON method, call it to obtain a replacement value. 1008 | 1009 | if (value instanceof Date) { 1010 | value = date(key); 1011 | } 1012 | 1013 | // If we were called with a replacer function, then call the replacer to 1014 | // obtain a replacement value. 1015 | 1016 | if (typeof rep === 'function') { 1017 | value = rep.call(holder, key, value); 1018 | } 1019 | 1020 | // What happens next depends on the value's type. 1021 | 1022 | switch (typeof value) { 1023 | case 'string': 1024 | return quote(value); 1025 | 1026 | case 'number': 1027 | 1028 | // JSON numbers must be finite. Encode non-finite numbers as null. 1029 | 1030 | return isFinite(value) ? String(value) : 'null'; 1031 | 1032 | case 'boolean': 1033 | case 'null': 1034 | 1035 | // If the value is a boolean or null, convert it to a string. Note: 1036 | // typeof null does not produce 'null'. The case is included here in 1037 | // the remote chance that this gets fixed someday. 1038 | 1039 | return String(value); 1040 | 1041 | // If the type is 'object', we might be dealing with an object or an array or 1042 | // null. 1043 | 1044 | case 'object': 1045 | 1046 | // Due to a specification blunder in ECMAScript, typeof null is 'object', 1047 | // so watch out for that case. 1048 | 1049 | if (!value) { 1050 | return 'null'; 1051 | } 1052 | 1053 | // Make an array to hold the partial results of stringifying this object value. 1054 | 1055 | gap += indent; 1056 | partial = []; 1057 | 1058 | // Is the value an array? 1059 | 1060 | if (Object.prototype.toString.apply(value) === '[object Array]') { 1061 | 1062 | // The value is an array. Stringify every element. Use null as a placeholder 1063 | // for non-JSON values. 1064 | 1065 | length = value.length; 1066 | for (i = 0; i < length; i += 1) { 1067 | partial[i] = str(i, value) || 'null'; 1068 | } 1069 | 1070 | // Join all of the elements together, separated with commas, and wrap them in 1071 | // brackets. 1072 | 1073 | v = partial.length === 0 ? '[]' : gap ? 1074 | '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : 1075 | '[' + partial.join(',') + ']'; 1076 | gap = mind; 1077 | return v; 1078 | } 1079 | 1080 | // If the replacer is an array, use it to select the members to be stringified. 1081 | 1082 | if (rep && typeof rep === 'object') { 1083 | length = rep.length; 1084 | for (i = 0; i < length; i += 1) { 1085 | if (typeof rep[i] === 'string') { 1086 | k = rep[i]; 1087 | v = str(k, value); 1088 | if (v) { 1089 | partial.push(quote(k) + (gap ? ': ' : ':') + v); 1090 | } 1091 | } 1092 | } 1093 | } else { 1094 | 1095 | // Otherwise, iterate through all of the keys in the object. 1096 | 1097 | for (k in value) { 1098 | if (Object.prototype.hasOwnProperty.call(value, k)) { 1099 | v = str(k, value); 1100 | if (v) { 1101 | partial.push(quote(k) + (gap ? ': ' : ':') + v); 1102 | } 1103 | } 1104 | } 1105 | } 1106 | 1107 | // Join all of the member texts together, separated with commas, 1108 | // and wrap them in braces. 1109 | 1110 | v = partial.length === 0 ? '{}' : gap ? 1111 | '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : 1112 | '{' + partial.join(',') + '}'; 1113 | gap = mind; 1114 | return v; 1115 | } 1116 | } 1117 | 1118 | // If the JSON object does not yet have a stringify method, give it one. 1119 | 1120 | JSON.stringify = function (value, replacer, space) { 1121 | 1122 | // The stringify method takes a value and an optional replacer, and an optional 1123 | // space parameter, and returns a JSON text. The replacer can be a function 1124 | // that can replace values, or an array of strings that will select the keys. 1125 | // A default replacer method can be provided. Use of the space parameter can 1126 | // produce text that is more easily readable. 1127 | 1128 | var i; 1129 | gap = ''; 1130 | indent = ''; 1131 | 1132 | // If the space parameter is a number, make an indent string containing that 1133 | // many spaces. 1134 | 1135 | if (typeof space === 'number') { 1136 | for (i = 0; i < space; i += 1) { 1137 | indent += ' '; 1138 | } 1139 | 1140 | // If the space parameter is a string, it will be used as the indent string. 1141 | 1142 | } else if (typeof space === 'string') { 1143 | indent = space; 1144 | } 1145 | 1146 | // If there is a replacer, it must be a function or an array. 1147 | // Otherwise, throw an error. 1148 | 1149 | rep = replacer; 1150 | if (replacer && typeof replacer !== 'function' && 1151 | (typeof replacer !== 'object' || 1152 | typeof replacer.length !== 'number')) { 1153 | throw new Error('JSON.stringify'); 1154 | } 1155 | 1156 | // Make a fake root object containing our value under the key of ''. 1157 | // Return the result of stringifying the value. 1158 | 1159 | return str('', {'': value}); 1160 | }; 1161 | 1162 | // If the JSON object does not yet have a parse method, give it one. 1163 | 1164 | JSON.parse = function (text, reviver) { 1165 | // The parse method takes a text and an optional reviver function, and returns 1166 | // a JavaScript value if the text is a valid JSON text. 1167 | 1168 | var j; 1169 | 1170 | function walk(holder, key) { 1171 | 1172 | // The walk method is used to recursively walk the resulting structure so 1173 | // that modifications can be made. 1174 | 1175 | var k, v, value = holder[key]; 1176 | if (value && typeof value === 'object') { 1177 | for (k in value) { 1178 | if (Object.prototype.hasOwnProperty.call(value, k)) { 1179 | v = walk(value, k); 1180 | if (v !== undefined) { 1181 | value[k] = v; 1182 | } else { 1183 | delete value[k]; 1184 | } 1185 | } 1186 | } 1187 | } 1188 | return reviver.call(holder, key, value); 1189 | } 1190 | 1191 | 1192 | // Parsing happens in four stages. In the first stage, we replace certain 1193 | // Unicode characters with escape sequences. JavaScript handles many characters 1194 | // incorrectly, either silently deleting them, or treating them as line endings. 1195 | 1196 | text = String(text); 1197 | cx.lastIndex = 0; 1198 | if (cx.test(text)) { 1199 | text = text.replace(cx, function (a) { 1200 | return '\\u' + 1201 | ('0000' + a.charCodeAt(0).toString(16)).slice(-4); 1202 | }); 1203 | } 1204 | 1205 | // In the second stage, we run the text against regular expressions that look 1206 | // for non-JSON patterns. We are especially concerned with '()' and 'new' 1207 | // because they can cause invocation, and '=' because it can cause mutation. 1208 | // But just to be safe, we want to reject all unexpected forms. 1209 | 1210 | // We split the second stage into 4 regexp operations in order to work around 1211 | // crippling inefficiencies in IE's and Safari's regexp engines. First we 1212 | // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we 1213 | // replace all simple value tokens with ']' characters. Third, we delete all 1214 | // open brackets that follow a colon or comma or that begin the text. Finally, 1215 | // we look to see that the remaining characters are only whitespace or ']' or 1216 | // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. 1217 | 1218 | if (/^[\],:{}\s]*$/ 1219 | .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') 1220 | .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') 1221 | .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { 1222 | 1223 | // In the third stage we use the eval function to compile the text into a 1224 | // JavaScript structure. The '{' operator is subject to a syntactic ambiguity 1225 | // in JavaScript: it can begin a block or an object literal. We wrap the text 1226 | // in parens to eliminate the ambiguity. 1227 | 1228 | j = eval('(' + text + ')'); 1229 | 1230 | // In the optional fourth stage, we recursively walk the new structure, passing 1231 | // each name/value pair to a reviver function for possible transformation. 1232 | 1233 | return typeof reviver === 'function' ? 1234 | walk({'': j}, '') : j; 1235 | } 1236 | 1237 | // If the text is not JSON parseable, then a SyntaxError is thrown. 1238 | 1239 | throw new SyntaxError('JSON.parse'); 1240 | }; 1241 | 1242 | return JSON; 1243 | })(); 1244 | 1245 | if ('undefined' != typeof window) { 1246 | window.expect = module.exports; 1247 | } 1248 | 1249 | })( 1250 | this 1251 | , 'undefined' != typeof module ? module : {} 1252 | , 'undefined' != typeof exports ? exports : {} 1253 | ); 1254 | -------------------------------------------------------------------------------- /test/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | querystring 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 17 | 18 | 19 |
20 | 21 | -------------------------------------------------------------------------------- /test/mocha.css: -------------------------------------------------------------------------------- 1 | @charset "UTF-8"; 2 | body { 3 | font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; 4 | padding: 60px 50px; 5 | } 6 | 7 | #mocha ul, #mocha li { 8 | margin: 0; 9 | padding: 0; 10 | } 11 | 12 | #mocha ul { 13 | list-style: none; 14 | } 15 | 16 | #mocha h1, #mocha h2 { 17 | margin: 0; 18 | } 19 | 20 | #mocha h1 { 21 | margin-top: 15px; 22 | font-size: 1em; 23 | font-weight: 200; 24 | } 25 | 26 | #mocha h1 a { 27 | text-decoration: none; 28 | color: inherit; 29 | } 30 | 31 | #mocha h1 a:hover { 32 | text-decoration: underline; 33 | } 34 | 35 | #mocha .suite .suite h1 { 36 | margin-top: 0; 37 | font-size: .8em; 38 | } 39 | 40 | .hidden { 41 | display: none; 42 | } 43 | 44 | #mocha h2 { 45 | font-size: 12px; 46 | font-weight: normal; 47 | cursor: pointer; 48 | } 49 | 50 | #mocha .suite { 51 | margin-left: 15px; 52 | } 53 | 54 | #mocha .test { 55 | margin-left: 15px; 56 | } 57 | 58 | #mocha .test.pending:hover h2::after { 59 | content: '(pending)'; 60 | font-family: arial; 61 | } 62 | 63 | #mocha .test.pass.medium .duration { 64 | background: #C09853; 65 | } 66 | 67 | #mocha .test.pass.slow .duration { 68 | background: #B94A48; 69 | } 70 | 71 | #mocha .test.pass::before { 72 | content: '✓'; 73 | font-size: 12px; 74 | display: block; 75 | float: left; 76 | margin-right: 5px; 77 | color: #00d6b2; 78 | } 79 | 80 | #mocha .test.pass .duration { 81 | font-size: 9px; 82 | margin-left: 5px; 83 | padding: 2px 5px; 84 | color: white; 85 | -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); 86 | -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); 87 | box-shadow: inset 0 1px 1px rgba(0,0,0,.2); 88 | -webkit-border-radius: 5px; 89 | -moz-border-radius: 5px; 90 | -ms-border-radius: 5px; 91 | -o-border-radius: 5px; 92 | border-radius: 5px; 93 | } 94 | 95 | #mocha .test.pass.fast .duration { 96 | display: none; 97 | } 98 | 99 | #mocha .test.pending { 100 | color: #0b97c4; 101 | } 102 | 103 | #mocha .test.pending::before { 104 | content: '◦'; 105 | color: #0b97c4; 106 | } 107 | 108 | #mocha .test.fail { 109 | color: #c00; 110 | } 111 | 112 | #mocha .test.fail pre { 113 | color: black; 114 | } 115 | 116 | #mocha .test.fail::before { 117 | content: '✖'; 118 | font-size: 12px; 119 | display: block; 120 | float: left; 121 | margin-right: 5px; 122 | color: #c00; 123 | } 124 | 125 | #mocha .test pre.error { 126 | color: #c00; 127 | max-height: 300px; 128 | overflow: auto; 129 | } 130 | 131 | #mocha .test pre { 132 | display: inline-block; 133 | font: 12px/1.5 monaco, monospace; 134 | margin: 5px; 135 | padding: 15px; 136 | border: 1px solid #eee; 137 | border-bottom-color: #ddd; 138 | -webkit-border-radius: 3px; 139 | -webkit-box-shadow: 0 1px 3px #eee; 140 | -moz-border-radius: 3px; 141 | -moz-box-shadow: 0 1px 3px #eee; 142 | } 143 | 144 | #mocha .test h2 { 145 | position: relative; 146 | } 147 | 148 | #mocha .test a.replay { 149 | position: absolute; 150 | top: 3px; 151 | right: -20px; 152 | text-decoration: none; 153 | vertical-align: middle; 154 | display: block; 155 | width: 15px; 156 | height: 15px; 157 | line-height: 15px; 158 | text-align: center; 159 | background: #eee; 160 | font-size: 15px; 161 | -moz-border-radius: 15px; 162 | border-radius: 15px; 163 | -webkit-transition: opacity 200ms; 164 | -moz-transition: opacity 200ms; 165 | transition: opacity 200ms; 166 | opacity: 0.2; 167 | color: #888; 168 | } 169 | 170 | #mocha .test:hover a.replay { 171 | opacity: 1; 172 | } 173 | 174 | #mocha-report.pass .test.fail { 175 | display: none; 176 | } 177 | 178 | #mocha-report.fail .test.pass { 179 | display: none; 180 | } 181 | 182 | #mocha-error { 183 | color: #c00; 184 | font-size: 1.5 em; 185 | font-weight: 100; 186 | letter-spacing: 1px; 187 | } 188 | 189 | #mocha-stats { 190 | position: fixed; 191 | top: 15px; 192 | right: 10px; 193 | font-size: 12px; 194 | margin: 0; 195 | color: #888; 196 | } 197 | 198 | #mocha-stats .progress { 199 | float: right; 200 | padding-top: 0; 201 | } 202 | 203 | #mocha-stats em { 204 | color: black; 205 | } 206 | 207 | #mocha-stats a { 208 | text-decoration: none; 209 | color: inherit; 210 | } 211 | 212 | #mocha-stats a:hover { 213 | border-bottom: 1px solid #eee; 214 | } 215 | 216 | #mocha-stats li { 217 | display: inline-block; 218 | margin: 0 5px; 219 | list-style: none; 220 | padding-top: 11px; 221 | } 222 | 223 | code .comment { color: #ddd } 224 | code .init { color: #2F6FAD } 225 | code .string { color: #5890AD } 226 | code .keyword { color: #8A6343 } 227 | code .number { color: #2F6FAD } 228 | -------------------------------------------------------------------------------- /test/mocha.js: -------------------------------------------------------------------------------- 1 | ;(function(){ 2 | 3 | 4 | // CommonJS require() 5 | 6 | function require(p){ 7 | var path = require.resolve(p) 8 | , mod = require.modules[path]; 9 | if (!mod) throw new Error('failed to require "' + p + '"'); 10 | if (!mod.exports) { 11 | mod.exports = {}; 12 | mod.call(mod.exports, mod, mod.exports, require.relative(path)); 13 | } 14 | return mod.exports; 15 | } 16 | 17 | require.modules = {}; 18 | 19 | require.resolve = function (path){ 20 | var orig = path 21 | , reg = path + '.js' 22 | , index = path + '/index.js'; 23 | return require.modules[reg] && reg 24 | || require.modules[index] && index 25 | || orig; 26 | }; 27 | 28 | require.register = function (path, fn){ 29 | require.modules[path] = fn; 30 | }; 31 | 32 | require.relative = function (parent) { 33 | return function(p){ 34 | if ('.' != p.charAt(0)) return require(p); 35 | 36 | var path = parent.split('/') 37 | , segs = p.split('/'); 38 | path.pop(); 39 | 40 | for (var i = 0; i < segs.length; i++) { 41 | var seg = segs[i]; 42 | if ('..' == seg) path.pop(); 43 | else if ('.' != seg) path.push(seg); 44 | } 45 | 46 | return require(path.join('/')); 47 | }; 48 | }; 49 | 50 | 51 | require.register("browser/debug.js", function(module, exports, require){ 52 | 53 | module.exports = function(type){ 54 | return function(){ 55 | 56 | } 57 | }; 58 | }); // module: browser/debug.js 59 | 60 | require.register("browser/diff.js", function(module, exports, require){ 61 | 62 | }); // module: browser/diff.js 63 | 64 | require.register("browser/events.js", function(module, exports, require){ 65 | 66 | /** 67 | * Module exports. 68 | */ 69 | 70 | exports.EventEmitter = EventEmitter; 71 | 72 | /** 73 | * Check if `obj` is an array. 74 | */ 75 | 76 | function isArray(obj) { 77 | return '[object Array]' == {}.toString.call(obj); 78 | } 79 | 80 | /** 81 | * Event emitter constructor. 82 | * 83 | * @api public 84 | */ 85 | 86 | function EventEmitter(){}; 87 | 88 | /** 89 | * Adds a listener. 90 | * 91 | * @api public 92 | */ 93 | 94 | EventEmitter.prototype.on = function (name, fn) { 95 | if (!this.$events) { 96 | this.$events = {}; 97 | } 98 | 99 | if (!this.$events[name]) { 100 | this.$events[name] = fn; 101 | } else if (isArray(this.$events[name])) { 102 | this.$events[name].push(fn); 103 | } else { 104 | this.$events[name] = [this.$events[name], fn]; 105 | } 106 | 107 | return this; 108 | }; 109 | 110 | EventEmitter.prototype.addListener = EventEmitter.prototype.on; 111 | 112 | /** 113 | * Adds a volatile listener. 114 | * 115 | * @api public 116 | */ 117 | 118 | EventEmitter.prototype.once = function (name, fn) { 119 | var self = this; 120 | 121 | function on () { 122 | self.removeListener(name, on); 123 | fn.apply(this, arguments); 124 | }; 125 | 126 | on.listener = fn; 127 | this.on(name, on); 128 | 129 | return this; 130 | }; 131 | 132 | /** 133 | * Removes a listener. 134 | * 135 | * @api public 136 | */ 137 | 138 | EventEmitter.prototype.removeListener = function (name, fn) { 139 | if (this.$events && this.$events[name]) { 140 | var list = this.$events[name]; 141 | 142 | if (isArray(list)) { 143 | var pos = -1; 144 | 145 | for (var i = 0, l = list.length; i < l; i++) { 146 | if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { 147 | pos = i; 148 | break; 149 | } 150 | } 151 | 152 | if (pos < 0) { 153 | return this; 154 | } 155 | 156 | list.splice(pos, 1); 157 | 158 | if (!list.length) { 159 | delete this.$events[name]; 160 | } 161 | } else if (list === fn || (list.listener && list.listener === fn)) { 162 | delete this.$events[name]; 163 | } 164 | } 165 | 166 | return this; 167 | }; 168 | 169 | /** 170 | * Removes all listeners for an event. 171 | * 172 | * @api public 173 | */ 174 | 175 | EventEmitter.prototype.removeAllListeners = function (name) { 176 | if (name === undefined) { 177 | this.$events = {}; 178 | return this; 179 | } 180 | 181 | if (this.$events && this.$events[name]) { 182 | this.$events[name] = null; 183 | } 184 | 185 | return this; 186 | }; 187 | 188 | /** 189 | * Gets all listeners for a certain event. 190 | * 191 | * @api public 192 | */ 193 | 194 | EventEmitter.prototype.listeners = function (name) { 195 | if (!this.$events) { 196 | this.$events = {}; 197 | } 198 | 199 | if (!this.$events[name]) { 200 | this.$events[name] = []; 201 | } 202 | 203 | if (!isArray(this.$events[name])) { 204 | this.$events[name] = [this.$events[name]]; 205 | } 206 | 207 | return this.$events[name]; 208 | }; 209 | 210 | /** 211 | * Emits an event. 212 | * 213 | * @api public 214 | */ 215 | 216 | EventEmitter.prototype.emit = function (name) { 217 | if (!this.$events) { 218 | return false; 219 | } 220 | 221 | var handler = this.$events[name]; 222 | 223 | if (!handler) { 224 | return false; 225 | } 226 | 227 | var args = [].slice.call(arguments, 1); 228 | 229 | if ('function' == typeof handler) { 230 | handler.apply(this, args); 231 | } else if (isArray(handler)) { 232 | var listeners = handler.slice(); 233 | 234 | for (var i = 0, l = listeners.length; i < l; i++) { 235 | listeners[i].apply(this, args); 236 | } 237 | } else { 238 | return false; 239 | } 240 | 241 | return true; 242 | }; 243 | }); // module: browser/events.js 244 | 245 | require.register("browser/fs.js", function(module, exports, require){ 246 | 247 | }); // module: browser/fs.js 248 | 249 | require.register("browser/path.js", function(module, exports, require){ 250 | 251 | }); // module: browser/path.js 252 | 253 | require.register("browser/progress.js", function(module, exports, require){ 254 | 255 | /** 256 | * Expose `Progress`. 257 | */ 258 | 259 | module.exports = Progress; 260 | 261 | /** 262 | * Initialize a new `Progress` indicator. 263 | */ 264 | 265 | function Progress() { 266 | this.percent = 0; 267 | this.size(0); 268 | this.fontSize(11); 269 | this.font('helvetica, arial, sans-serif'); 270 | } 271 | 272 | /** 273 | * Set progress size to `n`. 274 | * 275 | * @param {Number} n 276 | * @return {Progress} for chaining 277 | * @api public 278 | */ 279 | 280 | Progress.prototype.size = function(n){ 281 | this._size = n; 282 | return this; 283 | }; 284 | 285 | /** 286 | * Set text to `str`. 287 | * 288 | * @param {String} str 289 | * @return {Progress} for chaining 290 | * @api public 291 | */ 292 | 293 | Progress.prototype.text = function(str){ 294 | this._text = str; 295 | return this; 296 | }; 297 | 298 | /** 299 | * Set font size to `n`. 300 | * 301 | * @param {Number} n 302 | * @return {Progress} for chaining 303 | * @api public 304 | */ 305 | 306 | Progress.prototype.fontSize = function(n){ 307 | this._fontSize = n; 308 | return this; 309 | }; 310 | 311 | /** 312 | * Set font `family`. 313 | * 314 | * @param {String} family 315 | * @return {Progress} for chaining 316 | */ 317 | 318 | Progress.prototype.font = function(family){ 319 | this._font = family; 320 | return this; 321 | }; 322 | 323 | /** 324 | * Update percentage to `n`. 325 | * 326 | * @param {Number} n 327 | * @return {Progress} for chaining 328 | */ 329 | 330 | Progress.prototype.update = function(n){ 331 | this.percent = n; 332 | return this; 333 | }; 334 | 335 | /** 336 | * Draw on `ctx`. 337 | * 338 | * @param {CanvasRenderingContext2d} ctx 339 | * @return {Progress} for chaining 340 | */ 341 | 342 | Progress.prototype.draw = function(ctx){ 343 | var percent = Math.min(this.percent, 100) 344 | , size = this._size 345 | , half = size / 2 346 | , x = half 347 | , y = half 348 | , rad = half - 1 349 | , fontSize = this._fontSize; 350 | 351 | ctx.font = fontSize + 'px ' + this._font; 352 | 353 | var angle = Math.PI * 2 * (percent / 100); 354 | ctx.clearRect(0, 0, size, size); 355 | 356 | // outer circle 357 | ctx.strokeStyle = '#9f9f9f'; 358 | ctx.beginPath(); 359 | ctx.arc(x, y, rad, 0, angle, false); 360 | ctx.stroke(); 361 | 362 | // inner circle 363 | ctx.strokeStyle = '#eee'; 364 | ctx.beginPath(); 365 | ctx.arc(x, y, rad - 1, 0, angle, true); 366 | ctx.stroke(); 367 | 368 | // text 369 | var text = this._text || (percent | 0) + '%' 370 | , w = ctx.measureText(text).width; 371 | 372 | ctx.fillText( 373 | text 374 | , x - w / 2 + 1 375 | , y + fontSize / 2 - 1); 376 | 377 | return this; 378 | }; 379 | 380 | }); // module: browser/progress.js 381 | 382 | require.register("browser/tty.js", function(module, exports, require){ 383 | 384 | exports.isatty = function(){ 385 | return true; 386 | }; 387 | 388 | exports.getWindowSize = function(){ 389 | return [window.innerHeight, window.innerWidth]; 390 | }; 391 | }); // module: browser/tty.js 392 | 393 | require.register("context.js", function(module, exports, require){ 394 | 395 | /** 396 | * Expose `Context`. 397 | */ 398 | 399 | module.exports = Context; 400 | 401 | /** 402 | * Initialize a new `Context`. 403 | * 404 | * @api private 405 | */ 406 | 407 | function Context(){} 408 | 409 | /** 410 | * Set or get the context `Runnable` to `runnable`. 411 | * 412 | * @param {Runnable} runnable 413 | * @return {Context} 414 | * @api private 415 | */ 416 | 417 | Context.prototype.runnable = function(runnable){ 418 | if (0 == arguments.length) return this._runnable; 419 | this.test = this._runnable = runnable; 420 | return this; 421 | }; 422 | 423 | /** 424 | * Set test timeout `ms`. 425 | * 426 | * @param {Number} ms 427 | * @return {Context} self 428 | * @api private 429 | */ 430 | 431 | Context.prototype.timeout = function(ms){ 432 | this.runnable().timeout(ms); 433 | return this; 434 | }; 435 | 436 | /** 437 | * Set test slowness threshold `ms`. 438 | * 439 | * @param {Number} ms 440 | * @return {Context} self 441 | * @api private 442 | */ 443 | 444 | Context.prototype.slow = function(ms){ 445 | this.runnable().slow(ms); 446 | return this; 447 | }; 448 | 449 | /** 450 | * Inspect the context void of `._runnable`. 451 | * 452 | * @return {String} 453 | * @api private 454 | */ 455 | 456 | Context.prototype.inspect = function(){ 457 | return JSON.stringify(this, function(key, val){ 458 | if ('_runnable' == key) return; 459 | if ('test' == key) return; 460 | return val; 461 | }, 2); 462 | }; 463 | 464 | }); // module: context.js 465 | 466 | require.register("hook.js", function(module, exports, require){ 467 | 468 | /** 469 | * Module dependencies. 470 | */ 471 | 472 | var Runnable = require('./runnable'); 473 | 474 | /** 475 | * Expose `Hook`. 476 | */ 477 | 478 | module.exports = Hook; 479 | 480 | /** 481 | * Initialize a new `Hook` with the given `title` and callback `fn`. 482 | * 483 | * @param {String} title 484 | * @param {Function} fn 485 | * @api private 486 | */ 487 | 488 | function Hook(title, fn) { 489 | Runnable.call(this, title, fn); 490 | this.type = 'hook'; 491 | } 492 | 493 | /** 494 | * Inherit from `Runnable.prototype`. 495 | */ 496 | 497 | Hook.prototype = new Runnable; 498 | Hook.prototype.constructor = Hook; 499 | 500 | 501 | /** 502 | * Get or set the test `err`. 503 | * 504 | * @param {Error} err 505 | * @return {Error} 506 | * @api public 507 | */ 508 | 509 | Hook.prototype.error = function(err){ 510 | if (0 == arguments.length) { 511 | var err = this._error; 512 | this._error = null; 513 | return err; 514 | } 515 | 516 | this._error = err; 517 | }; 518 | 519 | 520 | }); // module: hook.js 521 | 522 | require.register("interfaces/bdd.js", function(module, exports, require){ 523 | 524 | /** 525 | * Module dependencies. 526 | */ 527 | 528 | var Suite = require('../suite') 529 | , Test = require('../test'); 530 | 531 | /** 532 | * BDD-style interface: 533 | * 534 | * describe('Array', function(){ 535 | * describe('#indexOf()', function(){ 536 | * it('should return -1 when not present', function(){ 537 | * 538 | * }); 539 | * 540 | * it('should return the index when present', function(){ 541 | * 542 | * }); 543 | * }); 544 | * }); 545 | * 546 | */ 547 | 548 | module.exports = function(suite){ 549 | var suites = [suite]; 550 | 551 | suite.on('pre-require', function(context, file, mocha){ 552 | 553 | /** 554 | * Execute before running tests. 555 | */ 556 | 557 | context.before = function(fn){ 558 | suites[0].beforeAll(fn); 559 | }; 560 | 561 | /** 562 | * Execute after running tests. 563 | */ 564 | 565 | context.after = function(fn){ 566 | suites[0].afterAll(fn); 567 | }; 568 | 569 | /** 570 | * Execute before each test case. 571 | */ 572 | 573 | context.beforeEach = function(fn){ 574 | suites[0].beforeEach(fn); 575 | }; 576 | 577 | /** 578 | * Execute after each test case. 579 | */ 580 | 581 | context.afterEach = function(fn){ 582 | suites[0].afterEach(fn); 583 | }; 584 | 585 | /** 586 | * Describe a "suite" with the given `title` 587 | * and callback `fn` containing nested suites 588 | * and/or tests. 589 | */ 590 | 591 | context.describe = context.context = function(title, fn){ 592 | var suite = Suite.create(suites[0], title); 593 | suites.unshift(suite); 594 | fn.call(suite); 595 | suites.shift(); 596 | return suite; 597 | }; 598 | 599 | /** 600 | * Pending describe. 601 | */ 602 | 603 | context.xdescribe = 604 | context.xcontext = 605 | context.describe.skip = function(title, fn){ 606 | var suite = Suite.create(suites[0], title); 607 | suite.pending = true; 608 | suites.unshift(suite); 609 | fn.call(suite); 610 | suites.shift(); 611 | }; 612 | 613 | /** 614 | * Exclusive suite. 615 | */ 616 | 617 | context.describe.only = function(title, fn){ 618 | var suite = context.describe(title, fn); 619 | mocha.grep(suite.fullTitle()); 620 | }; 621 | 622 | /** 623 | * Describe a specification or test-case 624 | * with the given `title` and callback `fn` 625 | * acting as a thunk. 626 | */ 627 | 628 | context.it = context.specify = function(title, fn){ 629 | var suite = suites[0]; 630 | if (suite.pending) var fn = null; 631 | var test = new Test(title, fn); 632 | suite.addTest(test); 633 | return test; 634 | }; 635 | 636 | /** 637 | * Exclusive test-case. 638 | */ 639 | 640 | context.it.only = function(title, fn){ 641 | var test = context.it(title, fn); 642 | mocha.grep(test.fullTitle()); 643 | }; 644 | 645 | /** 646 | * Pending test case. 647 | */ 648 | 649 | context.xit = 650 | context.xspecify = 651 | context.it.skip = function(title){ 652 | context.it(title); 653 | }; 654 | }); 655 | }; 656 | 657 | }); // module: interfaces/bdd.js 658 | 659 | require.register("interfaces/exports.js", function(module, exports, require){ 660 | 661 | /** 662 | * Module dependencies. 663 | */ 664 | 665 | var Suite = require('../suite') 666 | , Test = require('../test'); 667 | 668 | /** 669 | * TDD-style interface: 670 | * 671 | * exports.Array = { 672 | * '#indexOf()': { 673 | * 'should return -1 when the value is not present': function(){ 674 | * 675 | * }, 676 | * 677 | * 'should return the correct index when the value is present': function(){ 678 | * 679 | * } 680 | * } 681 | * }; 682 | * 683 | */ 684 | 685 | module.exports = function(suite){ 686 | var suites = [suite]; 687 | 688 | suite.on('require', visit); 689 | 690 | function visit(obj) { 691 | var suite; 692 | for (var key in obj) { 693 | if ('function' == typeof obj[key]) { 694 | var fn = obj[key]; 695 | switch (key) { 696 | case 'before': 697 | suites[0].beforeAll(fn); 698 | break; 699 | case 'after': 700 | suites[0].afterAll(fn); 701 | break; 702 | case 'beforeEach': 703 | suites[0].beforeEach(fn); 704 | break; 705 | case 'afterEach': 706 | suites[0].afterEach(fn); 707 | break; 708 | default: 709 | suites[0].addTest(new Test(key, fn)); 710 | } 711 | } else { 712 | var suite = Suite.create(suites[0], key); 713 | suites.unshift(suite); 714 | visit(obj[key]); 715 | suites.shift(); 716 | } 717 | } 718 | } 719 | }; 720 | }); // module: interfaces/exports.js 721 | 722 | require.register("interfaces/index.js", function(module, exports, require){ 723 | 724 | exports.bdd = require('./bdd'); 725 | exports.tdd = require('./tdd'); 726 | exports.qunit = require('./qunit'); 727 | exports.exports = require('./exports'); 728 | 729 | }); // module: interfaces/index.js 730 | 731 | require.register("interfaces/qunit.js", function(module, exports, require){ 732 | 733 | /** 734 | * Module dependencies. 735 | */ 736 | 737 | var Suite = require('../suite') 738 | , Test = require('../test'); 739 | 740 | /** 741 | * QUnit-style interface: 742 | * 743 | * suite('Array'); 744 | * 745 | * test('#length', function(){ 746 | * var arr = [1,2,3]; 747 | * ok(arr.length == 3); 748 | * }); 749 | * 750 | * test('#indexOf()', function(){ 751 | * var arr = [1,2,3]; 752 | * ok(arr.indexOf(1) == 0); 753 | * ok(arr.indexOf(2) == 1); 754 | * ok(arr.indexOf(3) == 2); 755 | * }); 756 | * 757 | * suite('String'); 758 | * 759 | * test('#length', function(){ 760 | * ok('foo'.length == 3); 761 | * }); 762 | * 763 | */ 764 | 765 | module.exports = function(suite){ 766 | var suites = [suite]; 767 | 768 | suite.on('pre-require', function(context){ 769 | 770 | /** 771 | * Execute before running tests. 772 | */ 773 | 774 | context.before = function(fn){ 775 | suites[0].beforeAll(fn); 776 | }; 777 | 778 | /** 779 | * Execute after running tests. 780 | */ 781 | 782 | context.after = function(fn){ 783 | suites[0].afterAll(fn); 784 | }; 785 | 786 | /** 787 | * Execute before each test case. 788 | */ 789 | 790 | context.beforeEach = function(fn){ 791 | suites[0].beforeEach(fn); 792 | }; 793 | 794 | /** 795 | * Execute after each test case. 796 | */ 797 | 798 | context.afterEach = function(fn){ 799 | suites[0].afterEach(fn); 800 | }; 801 | 802 | /** 803 | * Describe a "suite" with the given `title`. 804 | */ 805 | 806 | context.suite = function(title){ 807 | if (suites.length > 1) suites.shift(); 808 | var suite = Suite.create(suites[0], title); 809 | suites.unshift(suite); 810 | }; 811 | 812 | /** 813 | * Describe a specification or test-case 814 | * with the given `title` and callback `fn` 815 | * acting as a thunk. 816 | */ 817 | 818 | context.test = function(title, fn){ 819 | suites[0].addTest(new Test(title, fn)); 820 | }; 821 | }); 822 | }; 823 | 824 | }); // module: interfaces/qunit.js 825 | 826 | require.register("interfaces/tdd.js", function(module, exports, require){ 827 | 828 | /** 829 | * Module dependencies. 830 | */ 831 | 832 | var Suite = require('../suite') 833 | , Test = require('../test'); 834 | 835 | /** 836 | * TDD-style interface: 837 | * 838 | * suite('Array', function(){ 839 | * suite('#indexOf()', function(){ 840 | * suiteSetup(function(){ 841 | * 842 | * }); 843 | * 844 | * test('should return -1 when not present', function(){ 845 | * 846 | * }); 847 | * 848 | * test('should return the index when present', function(){ 849 | * 850 | * }); 851 | * 852 | * suiteTeardown(function(){ 853 | * 854 | * }); 855 | * }); 856 | * }); 857 | * 858 | */ 859 | 860 | module.exports = function(suite){ 861 | var suites = [suite]; 862 | 863 | suite.on('pre-require', function(context, file, mocha){ 864 | 865 | /** 866 | * Execute before each test case. 867 | */ 868 | 869 | context.setup = function(fn){ 870 | suites[0].beforeEach(fn); 871 | }; 872 | 873 | /** 874 | * Execute after each test case. 875 | */ 876 | 877 | context.teardown = function(fn){ 878 | suites[0].afterEach(fn); 879 | }; 880 | 881 | /** 882 | * Execute before the suite. 883 | */ 884 | 885 | context.suiteSetup = function(fn){ 886 | suites[0].beforeAll(fn); 887 | }; 888 | 889 | /** 890 | * Execute after the suite. 891 | */ 892 | 893 | context.suiteTeardown = function(fn){ 894 | suites[0].afterAll(fn); 895 | }; 896 | 897 | /** 898 | * Describe a "suite" with the given `title` 899 | * and callback `fn` containing nested suites 900 | * and/or tests. 901 | */ 902 | 903 | context.suite = function(title, fn){ 904 | var suite = Suite.create(suites[0], title); 905 | suites.unshift(suite); 906 | fn.call(suite); 907 | suites.shift(); 908 | return suite; 909 | }; 910 | 911 | /** 912 | * Exclusive test-case. 913 | */ 914 | 915 | context.suite.only = function(title, fn){ 916 | var suite = context.suite(title, fn); 917 | mocha.grep(suite.fullTitle()); 918 | }; 919 | 920 | /** 921 | * Describe a specification or test-case 922 | * with the given `title` and callback `fn` 923 | * acting as a thunk. 924 | */ 925 | 926 | context.test = function(title, fn){ 927 | var test = new Test(title, fn); 928 | suites[0].addTest(test); 929 | return test; 930 | }; 931 | 932 | /** 933 | * Exclusive test-case. 934 | */ 935 | 936 | context.test.only = function(title, fn){ 937 | var test = context.test(title, fn); 938 | mocha.grep(test.fullTitle()); 939 | }; 940 | 941 | /** 942 | * Pending test case. 943 | */ 944 | 945 | context.test.skip = function(title){ 946 | context.test(title); 947 | }; 948 | }); 949 | }; 950 | 951 | }); // module: interfaces/tdd.js 952 | 953 | require.register("mocha.js", function(module, exports, require){ 954 | /*! 955 | * mocha 956 | * Copyright(c) 2011 TJ Holowaychuk 957 | * MIT Licensed 958 | */ 959 | 960 | /** 961 | * Module dependencies. 962 | */ 963 | 964 | var path = require('browser/path') 965 | , utils = require('./utils'); 966 | 967 | /** 968 | * Expose `Mocha`. 969 | */ 970 | 971 | exports = module.exports = Mocha; 972 | 973 | /** 974 | * Expose internals. 975 | */ 976 | 977 | exports.utils = utils; 978 | exports.interfaces = require('./interfaces'); 979 | exports.reporters = require('./reporters'); 980 | exports.Runnable = require('./runnable'); 981 | exports.Context = require('./context'); 982 | exports.Runner = require('./runner'); 983 | exports.Suite = require('./suite'); 984 | exports.Hook = require('./hook'); 985 | exports.Test = require('./test'); 986 | 987 | /** 988 | * Return image `name` path. 989 | * 990 | * @param {String} name 991 | * @return {String} 992 | * @api private 993 | */ 994 | 995 | function image(name) { 996 | return __dirname + '/../images/' + name + '.png'; 997 | } 998 | 999 | /** 1000 | * Setup mocha with `options`. 1001 | * 1002 | * Options: 1003 | * 1004 | * - `ui` name "bdd", "tdd", "exports" etc 1005 | * - `reporter` reporter instance, defaults to `mocha.reporters.Dot` 1006 | * - `globals` array of accepted globals 1007 | * - `timeout` timeout in milliseconds 1008 | * - `slow` milliseconds to wait before considering a test slow 1009 | * - `ignoreLeaks` ignore global leaks 1010 | * - `grep` string or regexp to filter tests with 1011 | * 1012 | * @param {Object} options 1013 | * @api public 1014 | */ 1015 | 1016 | function Mocha(options) { 1017 | options = options || {}; 1018 | this.files = []; 1019 | this.options = options; 1020 | this.grep(options.grep); 1021 | this.suite = new exports.Suite('', new exports.Context); 1022 | this.ui(options.ui); 1023 | this.reporter(options.reporter); 1024 | if (options.timeout) this.timeout(options.timeout); 1025 | if (options.slow) this.slow(options.slow); 1026 | } 1027 | 1028 | /** 1029 | * Add test `file`. 1030 | * 1031 | * @param {String} file 1032 | * @api public 1033 | */ 1034 | 1035 | Mocha.prototype.addFile = function(file){ 1036 | this.files.push(file); 1037 | return this; 1038 | }; 1039 | 1040 | /** 1041 | * Set reporter to `reporter`, defaults to "dot". 1042 | * 1043 | * @param {String|Function} reporter name of a reporter or a reporter constructor 1044 | * @api public 1045 | */ 1046 | 1047 | Mocha.prototype.reporter = function(reporter){ 1048 | if ('function' == typeof reporter) { 1049 | this._reporter = reporter; 1050 | } else { 1051 | reporter = reporter || 'dot'; 1052 | try { 1053 | this._reporter = require('./reporters/' + reporter); 1054 | } catch (err) { 1055 | this._reporter = require(reporter); 1056 | } 1057 | if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"'); 1058 | } 1059 | return this; 1060 | }; 1061 | 1062 | /** 1063 | * Set test UI `name`, defaults to "bdd". 1064 | * 1065 | * @param {String} bdd 1066 | * @api public 1067 | */ 1068 | 1069 | Mocha.prototype.ui = function(name){ 1070 | name = name || 'bdd'; 1071 | this._ui = exports.interfaces[name]; 1072 | if (!this._ui) throw new Error('invalid interface "' + name + '"'); 1073 | this._ui = this._ui(this.suite); 1074 | return this; 1075 | }; 1076 | 1077 | /** 1078 | * Load registered files. 1079 | * 1080 | * @api private 1081 | */ 1082 | 1083 | Mocha.prototype.loadFiles = function(fn){ 1084 | var self = this; 1085 | var suite = this.suite; 1086 | var pending = this.files.length; 1087 | this.files.forEach(function(file){ 1088 | file = path.resolve(file); 1089 | suite.emit('pre-require', global, file, self); 1090 | suite.emit('require', require(file), file, self); 1091 | suite.emit('post-require', global, file, self); 1092 | --pending || (fn && fn()); 1093 | }); 1094 | }; 1095 | 1096 | /** 1097 | * Enable growl support. 1098 | * 1099 | * @api private 1100 | */ 1101 | 1102 | Mocha.prototype._growl = function(runner, reporter) { 1103 | var notify = require('growl'); 1104 | 1105 | runner.on('end', function(){ 1106 | var stats = reporter.stats; 1107 | if (stats.failures) { 1108 | var msg = stats.failures + ' of ' + runner.total + ' tests failed'; 1109 | notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); 1110 | } else { 1111 | notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { 1112 | name: 'mocha' 1113 | , title: 'Passed' 1114 | , image: image('ok') 1115 | }); 1116 | } 1117 | }); 1118 | }; 1119 | 1120 | /** 1121 | * Add regexp to grep, if `re` is a string it is escaped. 1122 | * 1123 | * @param {RegExp|String} re 1124 | * @return {Mocha} 1125 | * @api public 1126 | */ 1127 | 1128 | Mocha.prototype.grep = function(re){ 1129 | this.options.grep = 'string' == typeof re 1130 | ? new RegExp(utils.escapeRegexp(re)) 1131 | : re; 1132 | return this; 1133 | }; 1134 | 1135 | /** 1136 | * Invert `.grep()` matches. 1137 | * 1138 | * @return {Mocha} 1139 | * @api public 1140 | */ 1141 | 1142 | Mocha.prototype.invert = function(){ 1143 | this.options.invert = true; 1144 | return this; 1145 | }; 1146 | 1147 | /** 1148 | * Ignore global leaks. 1149 | * 1150 | * @return {Mocha} 1151 | * @api public 1152 | */ 1153 | 1154 | Mocha.prototype.ignoreLeaks = function(){ 1155 | this.options.ignoreLeaks = true; 1156 | return this; 1157 | }; 1158 | 1159 | /** 1160 | * Enable global leak checking. 1161 | * 1162 | * @return {Mocha} 1163 | * @api public 1164 | */ 1165 | 1166 | Mocha.prototype.checkLeaks = function(){ 1167 | this.options.ignoreLeaks = false; 1168 | return this; 1169 | }; 1170 | 1171 | /** 1172 | * Enable growl support. 1173 | * 1174 | * @return {Mocha} 1175 | * @api public 1176 | */ 1177 | 1178 | Mocha.prototype.growl = function(){ 1179 | this.options.growl = true; 1180 | return this; 1181 | }; 1182 | 1183 | /** 1184 | * Ignore `globals` array or string. 1185 | * 1186 | * @param {Array|String} globals 1187 | * @return {Mocha} 1188 | * @api public 1189 | */ 1190 | 1191 | Mocha.prototype.globals = function(globals){ 1192 | this.options.globals = (this.options.globals || []).concat(globals); 1193 | return this; 1194 | }; 1195 | 1196 | /** 1197 | * Set the timeout in milliseconds. 1198 | * 1199 | * @param {Number} timeout 1200 | * @return {Mocha} 1201 | * @api public 1202 | */ 1203 | 1204 | Mocha.prototype.timeout = function(timeout){ 1205 | this.suite.timeout(timeout); 1206 | return this; 1207 | }; 1208 | 1209 | /** 1210 | * Set slowness threshold in milliseconds. 1211 | * 1212 | * @param {Number} slow 1213 | * @return {Mocha} 1214 | * @api public 1215 | */ 1216 | 1217 | Mocha.prototype.slow = function(slow){ 1218 | this.suite.slow(slow); 1219 | return this; 1220 | }; 1221 | 1222 | /** 1223 | * Makes all tests async (accepting a callback) 1224 | * 1225 | * @return {Mocha} 1226 | * @api public 1227 | */ 1228 | 1229 | Mocha.prototype.asyncOnly = function(){ 1230 | this.options.asyncOnly = true; 1231 | return this; 1232 | }; 1233 | 1234 | /** 1235 | * Run tests and invoke `fn()` when complete. 1236 | * 1237 | * @param {Function} fn 1238 | * @return {Runner} 1239 | * @api public 1240 | */ 1241 | 1242 | Mocha.prototype.run = function(fn){ 1243 | if (this.files.length) this.loadFiles(); 1244 | var suite = this.suite; 1245 | var options = this.options; 1246 | var runner = new exports.Runner(suite); 1247 | var reporter = new this._reporter(runner); 1248 | runner.ignoreLeaks = options.ignoreLeaks; 1249 | runner.asyncOnly = options.asyncOnly; 1250 | if (options.grep) runner.grep(options.grep, options.invert); 1251 | if (options.globals) runner.globals(options.globals); 1252 | if (options.growl) this._growl(runner, reporter); 1253 | return runner.run(fn); 1254 | }; 1255 | 1256 | }); // module: mocha.js 1257 | 1258 | require.register("ms.js", function(module, exports, require){ 1259 | 1260 | /** 1261 | * Helpers. 1262 | */ 1263 | 1264 | var s = 1000; 1265 | var m = s * 60; 1266 | var h = m * 60; 1267 | var d = h * 24; 1268 | 1269 | /** 1270 | * Parse or format the given `val`. 1271 | * 1272 | * @param {String|Number} val 1273 | * @return {String|Number} 1274 | * @api public 1275 | */ 1276 | 1277 | module.exports = function(val){ 1278 | if ('string' == typeof val) return parse(val); 1279 | return format(val); 1280 | } 1281 | 1282 | /** 1283 | * Parse the given `str` and return milliseconds. 1284 | * 1285 | * @param {String} str 1286 | * @return {Number} 1287 | * @api private 1288 | */ 1289 | 1290 | function parse(str) { 1291 | var m = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); 1292 | if (!m) return; 1293 | var n = parseFloat(m[1]); 1294 | var type = (m[2] || 'ms').toLowerCase(); 1295 | switch (type) { 1296 | case 'years': 1297 | case 'year': 1298 | case 'y': 1299 | return n * 31557600000; 1300 | case 'days': 1301 | case 'day': 1302 | case 'd': 1303 | return n * 86400000; 1304 | case 'hours': 1305 | case 'hour': 1306 | case 'h': 1307 | return n * 3600000; 1308 | case 'minutes': 1309 | case 'minute': 1310 | case 'm': 1311 | return n * 60000; 1312 | case 'seconds': 1313 | case 'second': 1314 | case 's': 1315 | return n * 1000; 1316 | case 'ms': 1317 | return n; 1318 | } 1319 | } 1320 | 1321 | /** 1322 | * Format the given `ms`. 1323 | * 1324 | * @param {Number} ms 1325 | * @return {String} 1326 | * @api public 1327 | */ 1328 | 1329 | function format(ms) { 1330 | if (ms == d) return Math.round(ms / d) + ' day'; 1331 | if (ms > d) return Math.round(ms / d) + ' days'; 1332 | if (ms == h) return Math.round(ms / h) + ' hour'; 1333 | if (ms > h) return Math.round(ms / h) + ' hours'; 1334 | if (ms == m) return Math.round(ms / m) + ' minute'; 1335 | if (ms > m) return Math.round(ms / m) + ' minutes'; 1336 | if (ms == s) return Math.round(ms / s) + ' second'; 1337 | if (ms > s) return Math.round(ms / s) + ' seconds'; 1338 | return ms + ' ms'; 1339 | } 1340 | }); // module: ms.js 1341 | 1342 | require.register("reporters/base.js", function(module, exports, require){ 1343 | 1344 | /** 1345 | * Module dependencies. 1346 | */ 1347 | 1348 | var tty = require('browser/tty') 1349 | , diff = require('browser/diff') 1350 | , ms = require('../ms'); 1351 | 1352 | /** 1353 | * Save timer references to avoid Sinon interfering (see GH-237). 1354 | */ 1355 | 1356 | var Date = global.Date 1357 | , setTimeout = global.setTimeout 1358 | , setInterval = global.setInterval 1359 | , clearTimeout = global.clearTimeout 1360 | , clearInterval = global.clearInterval; 1361 | 1362 | /** 1363 | * Check if both stdio streams are associated with a tty. 1364 | */ 1365 | 1366 | var isatty = tty.isatty(1) && tty.isatty(2); 1367 | 1368 | /** 1369 | * Expose `Base`. 1370 | */ 1371 | 1372 | exports = module.exports = Base; 1373 | 1374 | /** 1375 | * Enable coloring by default. 1376 | */ 1377 | 1378 | exports.useColors = isatty; 1379 | 1380 | /** 1381 | * Default color map. 1382 | */ 1383 | 1384 | exports.colors = { 1385 | 'pass': 90 1386 | , 'fail': 31 1387 | , 'bright pass': 92 1388 | , 'bright fail': 91 1389 | , 'bright yellow': 93 1390 | , 'pending': 36 1391 | , 'suite': 0 1392 | , 'error title': 0 1393 | , 'error message': 31 1394 | , 'error stack': 90 1395 | , 'checkmark': 32 1396 | , 'fast': 90 1397 | , 'medium': 33 1398 | , 'slow': 31 1399 | , 'green': 32 1400 | , 'light': 90 1401 | , 'diff gutter': 90 1402 | , 'diff added': 42 1403 | , 'diff removed': 41 1404 | }; 1405 | 1406 | /** 1407 | * Default symbol map. 1408 | */ 1409 | 1410 | exports.symbols = { 1411 | ok: '✔', 1412 | err: '✖', 1413 | dot: '․' 1414 | }; 1415 | 1416 | // With node.js on Windows: use symbols available in terminal default fonts 1417 | if ('win32' == process.platform) { 1418 | exports.symbols.ok = '\u221A'; 1419 | exports.symbols.err = '\u00D7'; 1420 | exports.symbols.dot = '.'; 1421 | } 1422 | 1423 | /** 1424 | * Color `str` with the given `type`, 1425 | * allowing colors to be disabled, 1426 | * as well as user-defined color 1427 | * schemes. 1428 | * 1429 | * @param {String} type 1430 | * @param {String} str 1431 | * @return {String} 1432 | * @api private 1433 | */ 1434 | 1435 | var color = exports.color = function(type, str) { 1436 | if (!exports.useColors) return str; 1437 | return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; 1438 | }; 1439 | 1440 | /** 1441 | * Expose term window size, with some 1442 | * defaults for when stderr is not a tty. 1443 | */ 1444 | 1445 | exports.window = { 1446 | width: isatty 1447 | ? process.stdout.getWindowSize 1448 | ? process.stdout.getWindowSize(1)[0] 1449 | : tty.getWindowSize()[1] 1450 | : 75 1451 | }; 1452 | 1453 | /** 1454 | * Expose some basic cursor interactions 1455 | * that are common among reporters. 1456 | */ 1457 | 1458 | exports.cursor = { 1459 | hide: function(){ 1460 | process.stdout.write('\u001b[?25l'); 1461 | }, 1462 | 1463 | show: function(){ 1464 | process.stdout.write('\u001b[?25h'); 1465 | }, 1466 | 1467 | deleteLine: function(){ 1468 | process.stdout.write('\u001b[2K'); 1469 | }, 1470 | 1471 | beginningOfLine: function(){ 1472 | process.stdout.write('\u001b[0G'); 1473 | }, 1474 | 1475 | CR: function(){ 1476 | exports.cursor.deleteLine(); 1477 | exports.cursor.beginningOfLine(); 1478 | } 1479 | }; 1480 | 1481 | /** 1482 | * Outut the given `failures` as a list. 1483 | * 1484 | * @param {Array} failures 1485 | * @api public 1486 | */ 1487 | 1488 | exports.list = function(failures){ 1489 | console.error(); 1490 | failures.forEach(function(test, i){ 1491 | // format 1492 | var fmt = color('error title', ' %s) %s:\n') 1493 | + color('error message', ' %s') 1494 | + color('error stack', '\n%s\n'); 1495 | 1496 | // msg 1497 | var err = test.err 1498 | , message = err.message || '' 1499 | , stack = err.stack || message 1500 | , index = stack.indexOf(message) + message.length 1501 | , msg = stack.slice(0, index) 1502 | , actual = err.actual 1503 | , expected = err.expected 1504 | , escape = true; 1505 | 1506 | // explicitly show diff 1507 | if (err.showDiff) { 1508 | escape = false; 1509 | err.actual = actual = JSON.stringify(actual, null, 2); 1510 | err.expected = expected = JSON.stringify(expected, null, 2); 1511 | } 1512 | 1513 | // actual / expected diff 1514 | if ('string' == typeof actual && 'string' == typeof expected) { 1515 | var len = Math.max(actual.length, expected.length); 1516 | 1517 | if (len < 20) msg = errorDiff(err, 'Chars', escape); 1518 | else msg = errorDiff(err, 'Words', escape); 1519 | 1520 | // linenos 1521 | var lines = msg.split('\n'); 1522 | if (lines.length > 4) { 1523 | var width = String(lines.length).length; 1524 | msg = lines.map(function(str, i){ 1525 | return pad(++i, width) + ' |' + ' ' + str; 1526 | }).join('\n'); 1527 | } 1528 | 1529 | // legend 1530 | msg = '\n' 1531 | + color('diff removed', 'actual') 1532 | + ' ' 1533 | + color('diff added', 'expected') 1534 | + '\n\n' 1535 | + msg 1536 | + '\n'; 1537 | 1538 | // indent 1539 | msg = msg.replace(/^/gm, ' '); 1540 | 1541 | fmt = color('error title', ' %s) %s:\n%s') 1542 | + color('error stack', '\n%s\n'); 1543 | } 1544 | 1545 | // indent stack trace without msg 1546 | stack = stack.slice(index ? index + 1 : index) 1547 | .replace(/^/gm, ' '); 1548 | 1549 | console.error(fmt, (i + 1), test.fullTitle(), msg, stack); 1550 | }); 1551 | }; 1552 | 1553 | /** 1554 | * Initialize a new `Base` reporter. 1555 | * 1556 | * All other reporters generally 1557 | * inherit from this reporter, providing 1558 | * stats such as test duration, number 1559 | * of tests passed / failed etc. 1560 | * 1561 | * @param {Runner} runner 1562 | * @api public 1563 | */ 1564 | 1565 | function Base(runner) { 1566 | var self = this 1567 | , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } 1568 | , failures = this.failures = []; 1569 | 1570 | if (!runner) return; 1571 | this.runner = runner; 1572 | 1573 | runner.stats = stats; 1574 | 1575 | runner.on('start', function(){ 1576 | stats.start = new Date; 1577 | }); 1578 | 1579 | runner.on('suite', function(suite){ 1580 | stats.suites = stats.suites || 0; 1581 | suite.root || stats.suites++; 1582 | }); 1583 | 1584 | runner.on('test end', function(test){ 1585 | stats.tests = stats.tests || 0; 1586 | stats.tests++; 1587 | }); 1588 | 1589 | runner.on('pass', function(test){ 1590 | stats.passes = stats.passes || 0; 1591 | 1592 | var medium = test.slow() / 2; 1593 | test.speed = test.duration > test.slow() 1594 | ? 'slow' 1595 | : test.duration > medium 1596 | ? 'medium' 1597 | : 'fast'; 1598 | 1599 | stats.passes++; 1600 | }); 1601 | 1602 | runner.on('fail', function(test, err){ 1603 | stats.failures = stats.failures || 0; 1604 | stats.failures++; 1605 | test.err = err; 1606 | failures.push(test); 1607 | }); 1608 | 1609 | runner.on('end', function(){ 1610 | stats.end = new Date; 1611 | stats.duration = new Date - stats.start; 1612 | }); 1613 | 1614 | runner.on('pending', function(){ 1615 | stats.pending++; 1616 | }); 1617 | } 1618 | 1619 | /** 1620 | * Output common epilogue used by many of 1621 | * the bundled reporters. 1622 | * 1623 | * @api public 1624 | */ 1625 | 1626 | Base.prototype.epilogue = function(){ 1627 | var stats = this.stats 1628 | , fmt 1629 | , tests; 1630 | 1631 | console.log(); 1632 | 1633 | function pluralize(n) { 1634 | return 1 == n ? 'test' : 'tests'; 1635 | } 1636 | 1637 | // failure 1638 | if (stats.failures) { 1639 | fmt = color('bright fail', ' ' + exports.symbols.err) 1640 | + color('fail', ' %d of %d %s failed') 1641 | + color('light', ':') 1642 | 1643 | console.error(fmt, 1644 | stats.failures, 1645 | this.runner.total, 1646 | pluralize(this.runner.total)); 1647 | 1648 | Base.list(this.failures); 1649 | console.error(); 1650 | return; 1651 | } 1652 | 1653 | // pass 1654 | fmt = color('bright pass', ' ' + exports.symbols.ok) 1655 | + color('green', ' %d %s complete') 1656 | + color('light', ' (%s)'); 1657 | 1658 | console.log(fmt, 1659 | stats.tests || 0, 1660 | pluralize(stats.tests), 1661 | ms(stats.duration)); 1662 | 1663 | // pending 1664 | if (stats.pending) { 1665 | fmt = color('pending', ' •') 1666 | + color('pending', ' %d %s pending'); 1667 | 1668 | console.log(fmt, stats.pending, pluralize(stats.pending)); 1669 | } 1670 | 1671 | console.log(); 1672 | }; 1673 | 1674 | /** 1675 | * Pad the given `str` to `len`. 1676 | * 1677 | * @param {String} str 1678 | * @param {String} len 1679 | * @return {String} 1680 | * @api private 1681 | */ 1682 | 1683 | function pad(str, len) { 1684 | str = String(str); 1685 | return Array(len - str.length + 1).join(' ') + str; 1686 | } 1687 | 1688 | /** 1689 | * Return a character diff for `err`. 1690 | * 1691 | * @param {Error} err 1692 | * @return {String} 1693 | * @api private 1694 | */ 1695 | 1696 | function errorDiff(err, type, escape) { 1697 | return diff['diff' + type](err.actual, err.expected).map(function(str){ 1698 | if (escape) { 1699 | str.value = str.value 1700 | .replace(/\t/g, '') 1701 | .replace(/\r/g, '') 1702 | .replace(/\n/g, '\n'); 1703 | } 1704 | if (str.added) return colorLines('diff added', str.value); 1705 | if (str.removed) return colorLines('diff removed', str.value); 1706 | return str.value; 1707 | }).join(''); 1708 | } 1709 | 1710 | /** 1711 | * Color lines for `str`, using the color `name`. 1712 | * 1713 | * @param {String} name 1714 | * @param {String} str 1715 | * @return {String} 1716 | * @api private 1717 | */ 1718 | 1719 | function colorLines(name, str) { 1720 | return str.split('\n').map(function(str){ 1721 | return color(name, str); 1722 | }).join('\n'); 1723 | } 1724 | 1725 | }); // module: reporters/base.js 1726 | 1727 | require.register("reporters/doc.js", function(module, exports, require){ 1728 | 1729 | /** 1730 | * Module dependencies. 1731 | */ 1732 | 1733 | var Base = require('./base') 1734 | , utils = require('../utils'); 1735 | 1736 | /** 1737 | * Expose `Doc`. 1738 | */ 1739 | 1740 | exports = module.exports = Doc; 1741 | 1742 | /** 1743 | * Initialize a new `Doc` reporter. 1744 | * 1745 | * @param {Runner} runner 1746 | * @api public 1747 | */ 1748 | 1749 | function Doc(runner) { 1750 | Base.call(this, runner); 1751 | 1752 | var self = this 1753 | , stats = this.stats 1754 | , total = runner.total 1755 | , indents = 2; 1756 | 1757 | function indent() { 1758 | return Array(indents).join(' '); 1759 | } 1760 | 1761 | runner.on('suite', function(suite){ 1762 | if (suite.root) return; 1763 | ++indents; 1764 | console.log('%s
', indent()); 1765 | ++indents; 1766 | console.log('%s

%s

', indent(), utils.escape(suite.title)); 1767 | console.log('%s
', indent()); 1768 | }); 1769 | 1770 | runner.on('suite end', function(suite){ 1771 | if (suite.root) return; 1772 | console.log('%s
', indent()); 1773 | --indents; 1774 | console.log('%s
', indent()); 1775 | --indents; 1776 | }); 1777 | 1778 | runner.on('pass', function(test){ 1779 | console.log('%s
%s
', indent(), utils.escape(test.title)); 1780 | var code = utils.escape(utils.clean(test.fn.toString())); 1781 | console.log('%s
%s
', indent(), code); 1782 | }); 1783 | } 1784 | 1785 | }); // module: reporters/doc.js 1786 | 1787 | require.register("reporters/dot.js", function(module, exports, require){ 1788 | 1789 | /** 1790 | * Module dependencies. 1791 | */ 1792 | 1793 | var Base = require('./base') 1794 | , color = Base.color; 1795 | 1796 | /** 1797 | * Expose `Dot`. 1798 | */ 1799 | 1800 | exports = module.exports = Dot; 1801 | 1802 | /** 1803 | * Initialize a new `Dot` matrix test reporter. 1804 | * 1805 | * @param {Runner} runner 1806 | * @api public 1807 | */ 1808 | 1809 | function Dot(runner) { 1810 | Base.call(this, runner); 1811 | 1812 | var self = this 1813 | , stats = this.stats 1814 | , width = Base.window.width * .75 | 0 1815 | , n = 0; 1816 | 1817 | runner.on('start', function(){ 1818 | process.stdout.write('\n '); 1819 | }); 1820 | 1821 | runner.on('pending', function(test){ 1822 | process.stdout.write(color('pending', Base.symbols.dot)); 1823 | }); 1824 | 1825 | runner.on('pass', function(test){ 1826 | if (++n % width == 0) process.stdout.write('\n '); 1827 | if ('slow' == test.speed) { 1828 | process.stdout.write(color('bright yellow', Base.symbols.dot)); 1829 | } else { 1830 | process.stdout.write(color(test.speed, Base.symbols.dot)); 1831 | } 1832 | }); 1833 | 1834 | runner.on('fail', function(test, err){ 1835 | if (++n % width == 0) process.stdout.write('\n '); 1836 | process.stdout.write(color('fail', Base.symbols.dot)); 1837 | }); 1838 | 1839 | runner.on('end', function(){ 1840 | console.log(); 1841 | self.epilogue(); 1842 | }); 1843 | } 1844 | 1845 | /** 1846 | * Inherit from `Base.prototype`. 1847 | */ 1848 | 1849 | Dot.prototype = new Base; 1850 | Dot.prototype.constructor = Dot; 1851 | 1852 | }); // module: reporters/dot.js 1853 | 1854 | require.register("reporters/html-cov.js", function(module, exports, require){ 1855 | 1856 | /** 1857 | * Module dependencies. 1858 | */ 1859 | 1860 | var JSONCov = require('./json-cov') 1861 | , fs = require('browser/fs'); 1862 | 1863 | /** 1864 | * Expose `HTMLCov`. 1865 | */ 1866 | 1867 | exports = module.exports = HTMLCov; 1868 | 1869 | /** 1870 | * Initialize a new `JsCoverage` reporter. 1871 | * 1872 | * @param {Runner} runner 1873 | * @api public 1874 | */ 1875 | 1876 | function HTMLCov(runner) { 1877 | var jade = require('jade') 1878 | , file = __dirname + '/templates/coverage.jade' 1879 | , str = fs.readFileSync(file, 'utf8') 1880 | , fn = jade.compile(str, { filename: file }) 1881 | , self = this; 1882 | 1883 | JSONCov.call(this, runner, false); 1884 | 1885 | runner.on('end', function(){ 1886 | process.stdout.write(fn({ 1887 | cov: self.cov 1888 | , coverageClass: coverageClass 1889 | })); 1890 | }); 1891 | } 1892 | 1893 | /** 1894 | * Return coverage class for `n`. 1895 | * 1896 | * @return {String} 1897 | * @api private 1898 | */ 1899 | 1900 | function coverageClass(n) { 1901 | if (n >= 75) return 'high'; 1902 | if (n >= 50) return 'medium'; 1903 | if (n >= 25) return 'low'; 1904 | return 'terrible'; 1905 | } 1906 | }); // module: reporters/html-cov.js 1907 | 1908 | require.register("reporters/html.js", function(module, exports, require){ 1909 | 1910 | /** 1911 | * Module dependencies. 1912 | */ 1913 | 1914 | var Base = require('./base') 1915 | , utils = require('../utils') 1916 | , Progress = require('../browser/progress') 1917 | , escape = utils.escape; 1918 | 1919 | /** 1920 | * Save timer references to avoid Sinon interfering (see GH-237). 1921 | */ 1922 | 1923 | var Date = global.Date 1924 | , setTimeout = global.setTimeout 1925 | , setInterval = global.setInterval 1926 | , clearTimeout = global.clearTimeout 1927 | , clearInterval = global.clearInterval; 1928 | 1929 | /** 1930 | * Expose `Doc`. 1931 | */ 1932 | 1933 | exports = module.exports = HTML; 1934 | 1935 | /** 1936 | * Stats template. 1937 | */ 1938 | 1939 | var statsTemplate = '
    ' 1940 | + '
  • ' 1941 | + '
  • passes: 0
  • ' 1942 | + '
  • failures: 0
  • ' 1943 | + '
  • duration: 0s
  • ' 1944 | + '
'; 1945 | 1946 | /** 1947 | * Initialize a new `Doc` reporter. 1948 | * 1949 | * @param {Runner} runner 1950 | * @api public 1951 | */ 1952 | 1953 | function HTML(runner, root) { 1954 | Base.call(this, runner); 1955 | 1956 | var self = this 1957 | , stats = this.stats 1958 | , total = runner.total 1959 | , stat = fragment(statsTemplate) 1960 | , items = stat.getElementsByTagName('li') 1961 | , passes = items[1].getElementsByTagName('em')[0] 1962 | , passesLink = items[1].getElementsByTagName('a')[0] 1963 | , failures = items[2].getElementsByTagName('em')[0] 1964 | , failuresLink = items[2].getElementsByTagName('a')[0] 1965 | , duration = items[3].getElementsByTagName('em')[0] 1966 | , canvas = stat.getElementsByTagName('canvas')[0] 1967 | , report = fragment('
    ') 1968 | , stack = [report] 1969 | , progress 1970 | , ctx 1971 | 1972 | root = root || document.getElementById('mocha'); 1973 | 1974 | if (canvas.getContext) { 1975 | var ratio = window.devicePixelRatio || 1; 1976 | canvas.style.width = canvas.width; 1977 | canvas.style.height = canvas.height; 1978 | canvas.width *= ratio; 1979 | canvas.height *= ratio; 1980 | ctx = canvas.getContext('2d'); 1981 | ctx.scale(ratio, ratio); 1982 | progress = new Progress; 1983 | } 1984 | 1985 | if (!root) return error('#mocha div missing, add it to your document'); 1986 | 1987 | // pass toggle 1988 | on(passesLink, 'click', function(){ 1989 | unhide(); 1990 | var name = /pass/.test(report.className) ? '' : ' pass'; 1991 | report.className = report.className.replace(/fail|pass/g, '') + name; 1992 | if (report.className.trim()) hideSuitesWithout('test pass'); 1993 | }); 1994 | 1995 | // failure toggle 1996 | on(failuresLink, 'click', function(){ 1997 | unhide(); 1998 | var name = /fail/.test(report.className) ? '' : ' fail'; 1999 | report.className = report.className.replace(/fail|pass/g, '') + name; 2000 | if (report.className.trim()) hideSuitesWithout('test fail'); 2001 | }); 2002 | 2003 | root.appendChild(stat); 2004 | root.appendChild(report); 2005 | 2006 | if (progress) progress.size(40); 2007 | 2008 | runner.on('suite', function(suite){ 2009 | if (suite.root) return; 2010 | 2011 | // suite 2012 | var url = '?grep=' + encodeURIComponent(suite.fullTitle()); 2013 | var el = fragment('
  • %s

  • ', url, escape(suite.title)); 2014 | 2015 | // container 2016 | stack[0].appendChild(el); 2017 | stack.unshift(document.createElement('ul')); 2018 | el.appendChild(stack[0]); 2019 | }); 2020 | 2021 | runner.on('suite end', function(suite){ 2022 | if (suite.root) return; 2023 | stack.shift(); 2024 | }); 2025 | 2026 | runner.on('fail', function(test, err){ 2027 | if ('hook' == test.type || err.uncaught) runner.emit('test end', test); 2028 | }); 2029 | 2030 | runner.on('test end', function(test){ 2031 | window.scrollTo(0, document.body.scrollHeight); 2032 | 2033 | // TODO: add to stats 2034 | var percent = stats.tests / this.total * 100 | 0; 2035 | if (progress) progress.update(percent).draw(ctx); 2036 | 2037 | // update stats 2038 | var ms = new Date - stats.start; 2039 | text(passes, stats.passes); 2040 | text(failures, stats.failures); 2041 | text(duration, (ms / 1000).toFixed(2)); 2042 | 2043 | // test 2044 | if ('passed' == test.state) { 2045 | var el = fragment('
  • %e%ems

  • ', test.speed, test.title, test.duration, encodeURIComponent(test.fullTitle())); 2046 | } else if (test.pending) { 2047 | var el = fragment('
  • %e

  • ', test.title); 2048 | } else { 2049 | var el = fragment('
  • %e

  • ', test.title, encodeURIComponent(test.fullTitle())); 2050 | var str = test.err.stack || test.err.toString(); 2051 | 2052 | // FF / Opera do not add the message 2053 | if (!~str.indexOf(test.err.message)) { 2054 | str = test.err.message + '\n' + str; 2055 | } 2056 | 2057 | // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we 2058 | // check for the result of the stringifying. 2059 | if ('[object Error]' == str) str = test.err.message; 2060 | 2061 | // Safari doesn't give you a stack. Let's at least provide a source line. 2062 | if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { 2063 | str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; 2064 | } 2065 | 2066 | el.appendChild(fragment('
    %e
    ', str)); 2067 | } 2068 | 2069 | // toggle code 2070 | // TODO: defer 2071 | if (!test.pending) { 2072 | var h2 = el.getElementsByTagName('h2')[0]; 2073 | 2074 | on(h2, 'click', function(){ 2075 | pre.style.display = 'none' == pre.style.display 2076 | ? 'inline-block' 2077 | : 'none'; 2078 | }); 2079 | 2080 | var pre = fragment('
    %e
    ', utils.clean(test.fn.toString())); 2081 | el.appendChild(pre); 2082 | pre.style.display = 'none'; 2083 | } 2084 | 2085 | // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. 2086 | if (stack[0]) stack[0].appendChild(el); 2087 | }); 2088 | } 2089 | 2090 | /** 2091 | * Display error `msg`. 2092 | */ 2093 | 2094 | function error(msg) { 2095 | document.body.appendChild(fragment('
    %s
    ', msg)); 2096 | } 2097 | 2098 | /** 2099 | * Return a DOM fragment from `html`. 2100 | */ 2101 | 2102 | function fragment(html) { 2103 | var args = arguments 2104 | , div = document.createElement('div') 2105 | , i = 1; 2106 | 2107 | div.innerHTML = html.replace(/%([se])/g, function(_, type){ 2108 | switch (type) { 2109 | case 's': return String(args[i++]); 2110 | case 'e': return escape(args[i++]); 2111 | } 2112 | }); 2113 | 2114 | return div.firstChild; 2115 | } 2116 | 2117 | /** 2118 | * Check for suites that do not have elements 2119 | * with `classname`, and hide them. 2120 | */ 2121 | 2122 | function hideSuitesWithout(classname) { 2123 | var suites = document.getElementsByClassName('suite'); 2124 | for (var i = 0; i < suites.length; i++) { 2125 | var els = suites[i].getElementsByClassName(classname); 2126 | if (0 == els.length) suites[i].className += ' hidden'; 2127 | } 2128 | } 2129 | 2130 | /** 2131 | * Unhide .hidden suites. 2132 | */ 2133 | 2134 | function unhide() { 2135 | var els = document.getElementsByClassName('suite hidden'); 2136 | for (var i = 0; i < els.length; ++i) { 2137 | els[i].className = els[i].className.replace('suite hidden', 'suite'); 2138 | } 2139 | } 2140 | 2141 | /** 2142 | * Set `el` text to `str`. 2143 | */ 2144 | 2145 | function text(el, str) { 2146 | if (el.textContent) { 2147 | el.textContent = str; 2148 | } else { 2149 | el.innerText = str; 2150 | } 2151 | } 2152 | 2153 | /** 2154 | * Listen on `event` with callback `fn`. 2155 | */ 2156 | 2157 | function on(el, event, fn) { 2158 | if (el.addEventListener) { 2159 | el.addEventListener(event, fn, false); 2160 | } else { 2161 | el.attachEvent('on' + event, fn); 2162 | } 2163 | } 2164 | 2165 | }); // module: reporters/html.js 2166 | 2167 | require.register("reporters/index.js", function(module, exports, require){ 2168 | 2169 | exports.Base = require('./base'); 2170 | exports.Dot = require('./dot'); 2171 | exports.Doc = require('./doc'); 2172 | exports.TAP = require('./tap'); 2173 | exports.JSON = require('./json'); 2174 | exports.HTML = require('./html'); 2175 | exports.List = require('./list'); 2176 | exports.Min = require('./min'); 2177 | exports.Spec = require('./spec'); 2178 | exports.Nyan = require('./nyan'); 2179 | exports.XUnit = require('./xunit'); 2180 | exports.Markdown = require('./markdown'); 2181 | exports.Progress = require('./progress'); 2182 | exports.Landing = require('./landing'); 2183 | exports.JSONCov = require('./json-cov'); 2184 | exports.HTMLCov = require('./html-cov'); 2185 | exports.JSONStream = require('./json-stream'); 2186 | exports.Teamcity = require('./teamcity'); 2187 | 2188 | }); // module: reporters/index.js 2189 | 2190 | require.register("reporters/json-cov.js", function(module, exports, require){ 2191 | 2192 | /** 2193 | * Module dependencies. 2194 | */ 2195 | 2196 | var Base = require('./base'); 2197 | 2198 | /** 2199 | * Expose `JSONCov`. 2200 | */ 2201 | 2202 | exports = module.exports = JSONCov; 2203 | 2204 | /** 2205 | * Initialize a new `JsCoverage` reporter. 2206 | * 2207 | * @param {Runner} runner 2208 | * @param {Boolean} output 2209 | * @api public 2210 | */ 2211 | 2212 | function JSONCov(runner, output) { 2213 | var self = this 2214 | , output = 1 == arguments.length ? true : output; 2215 | 2216 | Base.call(this, runner); 2217 | 2218 | var tests = [] 2219 | , failures = [] 2220 | , passes = []; 2221 | 2222 | runner.on('test end', function(test){ 2223 | tests.push(test); 2224 | }); 2225 | 2226 | runner.on('pass', function(test){ 2227 | passes.push(test); 2228 | }); 2229 | 2230 | runner.on('fail', function(test){ 2231 | failures.push(test); 2232 | }); 2233 | 2234 | runner.on('end', function(){ 2235 | var cov = global._$jscoverage || {}; 2236 | var result = self.cov = map(cov); 2237 | result.stats = self.stats; 2238 | result.tests = tests.map(clean); 2239 | result.failures = failures.map(clean); 2240 | result.passes = passes.map(clean); 2241 | if (!output) return; 2242 | process.stdout.write(JSON.stringify(result, null, 2 )); 2243 | }); 2244 | } 2245 | 2246 | /** 2247 | * Map jscoverage data to a JSON structure 2248 | * suitable for reporting. 2249 | * 2250 | * @param {Object} cov 2251 | * @return {Object} 2252 | * @api private 2253 | */ 2254 | 2255 | function map(cov) { 2256 | var ret = { 2257 | instrumentation: 'node-jscoverage' 2258 | , sloc: 0 2259 | , hits: 0 2260 | , misses: 0 2261 | , coverage: 0 2262 | , files: [] 2263 | }; 2264 | 2265 | for (var filename in cov) { 2266 | var data = coverage(filename, cov[filename]); 2267 | ret.files.push(data); 2268 | ret.hits += data.hits; 2269 | ret.misses += data.misses; 2270 | ret.sloc += data.sloc; 2271 | } 2272 | 2273 | ret.files.sort(function(a, b) { 2274 | return a.filename.localeCompare(b.filename); 2275 | }); 2276 | 2277 | if (ret.sloc > 0) { 2278 | ret.coverage = (ret.hits / ret.sloc) * 100; 2279 | } 2280 | 2281 | return ret; 2282 | }; 2283 | 2284 | /** 2285 | * Map jscoverage data for a single source file 2286 | * to a JSON structure suitable for reporting. 2287 | * 2288 | * @param {String} filename name of the source file 2289 | * @param {Object} data jscoverage coverage data 2290 | * @return {Object} 2291 | * @api private 2292 | */ 2293 | 2294 | function coverage(filename, data) { 2295 | var ret = { 2296 | filename: filename, 2297 | coverage: 0, 2298 | hits: 0, 2299 | misses: 0, 2300 | sloc: 0, 2301 | source: {} 2302 | }; 2303 | 2304 | data.source.forEach(function(line, num){ 2305 | num++; 2306 | 2307 | if (data[num] === 0) { 2308 | ret.misses++; 2309 | ret.sloc++; 2310 | } else if (data[num] !== undefined) { 2311 | ret.hits++; 2312 | ret.sloc++; 2313 | } 2314 | 2315 | ret.source[num] = { 2316 | source: line 2317 | , coverage: data[num] === undefined 2318 | ? '' 2319 | : data[num] 2320 | }; 2321 | }); 2322 | 2323 | ret.coverage = ret.hits / ret.sloc * 100; 2324 | 2325 | return ret; 2326 | } 2327 | 2328 | /** 2329 | * Return a plain-object representation of `test` 2330 | * free of cyclic properties etc. 2331 | * 2332 | * @param {Object} test 2333 | * @return {Object} 2334 | * @api private 2335 | */ 2336 | 2337 | function clean(test) { 2338 | return { 2339 | title: test.title 2340 | , fullTitle: test.fullTitle() 2341 | , duration: test.duration 2342 | } 2343 | } 2344 | 2345 | }); // module: reporters/json-cov.js 2346 | 2347 | require.register("reporters/json-stream.js", function(module, exports, require){ 2348 | 2349 | /** 2350 | * Module dependencies. 2351 | */ 2352 | 2353 | var Base = require('./base') 2354 | , color = Base.color; 2355 | 2356 | /** 2357 | * Expose `List`. 2358 | */ 2359 | 2360 | exports = module.exports = List; 2361 | 2362 | /** 2363 | * Initialize a new `List` test reporter. 2364 | * 2365 | * @param {Runner} runner 2366 | * @api public 2367 | */ 2368 | 2369 | function List(runner) { 2370 | Base.call(this, runner); 2371 | 2372 | var self = this 2373 | , stats = this.stats 2374 | , total = runner.total; 2375 | 2376 | runner.on('start', function(){ 2377 | console.log(JSON.stringify(['start', { total: total }])); 2378 | }); 2379 | 2380 | runner.on('pass', function(test){ 2381 | console.log(JSON.stringify(['pass', clean(test)])); 2382 | }); 2383 | 2384 | runner.on('fail', function(test, err){ 2385 | console.log(JSON.stringify(['fail', clean(test)])); 2386 | }); 2387 | 2388 | runner.on('end', function(){ 2389 | process.stdout.write(JSON.stringify(['end', self.stats])); 2390 | }); 2391 | } 2392 | 2393 | /** 2394 | * Return a plain-object representation of `test` 2395 | * free of cyclic properties etc. 2396 | * 2397 | * @param {Object} test 2398 | * @return {Object} 2399 | * @api private 2400 | */ 2401 | 2402 | function clean(test) { 2403 | return { 2404 | title: test.title 2405 | , fullTitle: test.fullTitle() 2406 | , duration: test.duration 2407 | } 2408 | } 2409 | }); // module: reporters/json-stream.js 2410 | 2411 | require.register("reporters/json.js", function(module, exports, require){ 2412 | 2413 | /** 2414 | * Module dependencies. 2415 | */ 2416 | 2417 | var Base = require('./base') 2418 | , cursor = Base.cursor 2419 | , color = Base.color; 2420 | 2421 | /** 2422 | * Expose `JSON`. 2423 | */ 2424 | 2425 | exports = module.exports = JSONReporter; 2426 | 2427 | /** 2428 | * Initialize a new `JSON` reporter. 2429 | * 2430 | * @param {Runner} runner 2431 | * @api public 2432 | */ 2433 | 2434 | function JSONReporter(runner) { 2435 | var self = this; 2436 | Base.call(this, runner); 2437 | 2438 | var tests = [] 2439 | , failures = [] 2440 | , passes = []; 2441 | 2442 | runner.on('test end', function(test){ 2443 | tests.push(test); 2444 | }); 2445 | 2446 | runner.on('pass', function(test){ 2447 | passes.push(test); 2448 | }); 2449 | 2450 | runner.on('fail', function(test){ 2451 | failures.push(test); 2452 | }); 2453 | 2454 | runner.on('end', function(){ 2455 | var obj = { 2456 | stats: self.stats 2457 | , tests: tests.map(clean) 2458 | , failures: failures.map(clean) 2459 | , passes: passes.map(clean) 2460 | }; 2461 | 2462 | process.stdout.write(JSON.stringify(obj, null, 2)); 2463 | }); 2464 | } 2465 | 2466 | /** 2467 | * Return a plain-object representation of `test` 2468 | * free of cyclic properties etc. 2469 | * 2470 | * @param {Object} test 2471 | * @return {Object} 2472 | * @api private 2473 | */ 2474 | 2475 | function clean(test) { 2476 | return { 2477 | title: test.title 2478 | , fullTitle: test.fullTitle() 2479 | , duration: test.duration 2480 | } 2481 | } 2482 | }); // module: reporters/json.js 2483 | 2484 | require.register("reporters/landing.js", function(module, exports, require){ 2485 | 2486 | /** 2487 | * Module dependencies. 2488 | */ 2489 | 2490 | var Base = require('./base') 2491 | , cursor = Base.cursor 2492 | , color = Base.color; 2493 | 2494 | /** 2495 | * Expose `Landing`. 2496 | */ 2497 | 2498 | exports = module.exports = Landing; 2499 | 2500 | /** 2501 | * Airplane color. 2502 | */ 2503 | 2504 | Base.colors.plane = 0; 2505 | 2506 | /** 2507 | * Airplane crash color. 2508 | */ 2509 | 2510 | Base.colors['plane crash'] = 31; 2511 | 2512 | /** 2513 | * Runway color. 2514 | */ 2515 | 2516 | Base.colors.runway = 90; 2517 | 2518 | /** 2519 | * Initialize a new `Landing` reporter. 2520 | * 2521 | * @param {Runner} runner 2522 | * @api public 2523 | */ 2524 | 2525 | function Landing(runner) { 2526 | Base.call(this, runner); 2527 | 2528 | var self = this 2529 | , stats = this.stats 2530 | , width = Base.window.width * .75 | 0 2531 | , total = runner.total 2532 | , stream = process.stdout 2533 | , plane = color('plane', '✈') 2534 | , crashed = -1 2535 | , n = 0; 2536 | 2537 | function runway() { 2538 | var buf = Array(width).join('-'); 2539 | return ' ' + color('runway', buf); 2540 | } 2541 | 2542 | runner.on('start', function(){ 2543 | stream.write('\n '); 2544 | cursor.hide(); 2545 | }); 2546 | 2547 | runner.on('test end', function(test){ 2548 | // check if the plane crashed 2549 | var col = -1 == crashed 2550 | ? width * ++n / total | 0 2551 | : crashed; 2552 | 2553 | // show the crash 2554 | if ('failed' == test.state) { 2555 | plane = color('plane crash', '✈'); 2556 | crashed = col; 2557 | } 2558 | 2559 | // render landing strip 2560 | stream.write('\u001b[4F\n\n'); 2561 | stream.write(runway()); 2562 | stream.write('\n '); 2563 | stream.write(color('runway', Array(col).join('⋅'))); 2564 | stream.write(plane) 2565 | stream.write(color('runway', Array(width - col).join('⋅') + '\n')); 2566 | stream.write(runway()); 2567 | stream.write('\u001b[0m'); 2568 | }); 2569 | 2570 | runner.on('end', function(){ 2571 | cursor.show(); 2572 | console.log(); 2573 | self.epilogue(); 2574 | }); 2575 | } 2576 | 2577 | /** 2578 | * Inherit from `Base.prototype`. 2579 | */ 2580 | 2581 | Landing.prototype = new Base; 2582 | Landing.prototype.constructor = Landing; 2583 | 2584 | }); // module: reporters/landing.js 2585 | 2586 | require.register("reporters/list.js", function(module, exports, require){ 2587 | 2588 | /** 2589 | * Module dependencies. 2590 | */ 2591 | 2592 | var Base = require('./base') 2593 | , cursor = Base.cursor 2594 | , color = Base.color; 2595 | 2596 | /** 2597 | * Expose `List`. 2598 | */ 2599 | 2600 | exports = module.exports = List; 2601 | 2602 | /** 2603 | * Initialize a new `List` test reporter. 2604 | * 2605 | * @param {Runner} runner 2606 | * @api public 2607 | */ 2608 | 2609 | function List(runner) { 2610 | Base.call(this, runner); 2611 | 2612 | var self = this 2613 | , stats = this.stats 2614 | , n = 0; 2615 | 2616 | runner.on('start', function(){ 2617 | console.log(); 2618 | }); 2619 | 2620 | runner.on('test', function(test){ 2621 | process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); 2622 | }); 2623 | 2624 | runner.on('pending', function(test){ 2625 | var fmt = color('checkmark', ' -') 2626 | + color('pending', ' %s'); 2627 | console.log(fmt, test.fullTitle()); 2628 | }); 2629 | 2630 | runner.on('pass', function(test){ 2631 | var fmt = color('checkmark', ' '+Base.symbols.dot) 2632 | + color('pass', ' %s: ') 2633 | + color(test.speed, '%dms'); 2634 | cursor.CR(); 2635 | console.log(fmt, test.fullTitle(), test.duration); 2636 | }); 2637 | 2638 | runner.on('fail', function(test, err){ 2639 | cursor.CR(); 2640 | console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); 2641 | }); 2642 | 2643 | runner.on('end', self.epilogue.bind(self)); 2644 | } 2645 | 2646 | /** 2647 | * Inherit from `Base.prototype`. 2648 | */ 2649 | 2650 | List.prototype = new Base; 2651 | List.prototype.constructor = List; 2652 | 2653 | 2654 | }); // module: reporters/list.js 2655 | 2656 | require.register("reporters/markdown.js", function(module, exports, require){ 2657 | /** 2658 | * Module dependencies. 2659 | */ 2660 | 2661 | var Base = require('./base') 2662 | , utils = require('../utils'); 2663 | 2664 | /** 2665 | * Expose `Markdown`. 2666 | */ 2667 | 2668 | exports = module.exports = Markdown; 2669 | 2670 | /** 2671 | * Initialize a new `Markdown` reporter. 2672 | * 2673 | * @param {Runner} runner 2674 | * @api public 2675 | */ 2676 | 2677 | function Markdown(runner) { 2678 | Base.call(this, runner); 2679 | 2680 | var self = this 2681 | , stats = this.stats 2682 | , total = runner.total 2683 | , level = 0 2684 | , buf = ''; 2685 | 2686 | function title(str) { 2687 | return Array(level).join('#') + ' ' + str; 2688 | } 2689 | 2690 | function indent() { 2691 | return Array(level).join(' '); 2692 | } 2693 | 2694 | function mapTOC(suite, obj) { 2695 | var ret = obj; 2696 | obj = obj[suite.title] = obj[suite.title] || { suite: suite }; 2697 | suite.suites.forEach(function(suite){ 2698 | mapTOC(suite, obj); 2699 | }); 2700 | return ret; 2701 | } 2702 | 2703 | function stringifyTOC(obj, level) { 2704 | ++level; 2705 | var buf = ''; 2706 | var link; 2707 | for (var key in obj) { 2708 | if ('suite' == key) continue; 2709 | if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; 2710 | if (key) buf += Array(level).join(' ') + link; 2711 | buf += stringifyTOC(obj[key], level); 2712 | } 2713 | --level; 2714 | return buf; 2715 | } 2716 | 2717 | function generateTOC(suite) { 2718 | var obj = mapTOC(suite, {}); 2719 | return stringifyTOC(obj, 0); 2720 | } 2721 | 2722 | generateTOC(runner.suite); 2723 | 2724 | runner.on('suite', function(suite){ 2725 | ++level; 2726 | var slug = utils.slug(suite.fullTitle()); 2727 | buf += '' + '\n'; 2728 | buf += title(suite.title) + '\n'; 2729 | }); 2730 | 2731 | runner.on('suite end', function(suite){ 2732 | --level; 2733 | }); 2734 | 2735 | runner.on('pass', function(test){ 2736 | var code = utils.clean(test.fn.toString()); 2737 | buf += test.title + '.\n'; 2738 | buf += '\n```js\n'; 2739 | buf += code + '\n'; 2740 | buf += '```\n\n'; 2741 | }); 2742 | 2743 | runner.on('end', function(){ 2744 | process.stdout.write('# TOC\n'); 2745 | process.stdout.write(generateTOC(runner.suite)); 2746 | process.stdout.write(buf); 2747 | }); 2748 | } 2749 | }); // module: reporters/markdown.js 2750 | 2751 | require.register("reporters/min.js", function(module, exports, require){ 2752 | 2753 | /** 2754 | * Module dependencies. 2755 | */ 2756 | 2757 | var Base = require('./base'); 2758 | 2759 | /** 2760 | * Expose `Min`. 2761 | */ 2762 | 2763 | exports = module.exports = Min; 2764 | 2765 | /** 2766 | * Initialize a new `Min` minimal test reporter (best used with --watch). 2767 | * 2768 | * @param {Runner} runner 2769 | * @api public 2770 | */ 2771 | 2772 | function Min(runner) { 2773 | Base.call(this, runner); 2774 | 2775 | runner.on('start', function(){ 2776 | // clear screen 2777 | process.stdout.write('\u001b[2J'); 2778 | // set cursor position 2779 | process.stdout.write('\u001b[1;3H'); 2780 | }); 2781 | 2782 | runner.on('end', this.epilogue.bind(this)); 2783 | } 2784 | 2785 | /** 2786 | * Inherit from `Base.prototype`. 2787 | */ 2788 | 2789 | Min.prototype = new Base; 2790 | Min.prototype.constructor = Min; 2791 | 2792 | }); // module: reporters/min.js 2793 | 2794 | require.register("reporters/nyan.js", function(module, exports, require){ 2795 | 2796 | /** 2797 | * Module dependencies. 2798 | */ 2799 | 2800 | var Base = require('./base') 2801 | , color = Base.color; 2802 | 2803 | /** 2804 | * Expose `Dot`. 2805 | */ 2806 | 2807 | exports = module.exports = NyanCat; 2808 | 2809 | /** 2810 | * Initialize a new `Dot` matrix test reporter. 2811 | * 2812 | * @param {Runner} runner 2813 | * @api public 2814 | */ 2815 | 2816 | function NyanCat(runner) { 2817 | Base.call(this, runner); 2818 | 2819 | var self = this 2820 | , stats = this.stats 2821 | , width = Base.window.width * .75 | 0 2822 | , rainbowColors = this.rainbowColors = self.generateColors() 2823 | , colorIndex = this.colorIndex = 0 2824 | , numerOfLines = this.numberOfLines = 4 2825 | , trajectories = this.trajectories = [[], [], [], []] 2826 | , nyanCatWidth = this.nyanCatWidth = 11 2827 | , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) 2828 | , scoreboardWidth = this.scoreboardWidth = 5 2829 | , tick = this.tick = 0 2830 | , n = 0; 2831 | 2832 | runner.on('start', function(){ 2833 | Base.cursor.hide(); 2834 | self.draw('start'); 2835 | }); 2836 | 2837 | runner.on('pending', function(test){ 2838 | self.draw('pending'); 2839 | }); 2840 | 2841 | runner.on('pass', function(test){ 2842 | self.draw('pass'); 2843 | }); 2844 | 2845 | runner.on('fail', function(test, err){ 2846 | self.draw('fail'); 2847 | }); 2848 | 2849 | runner.on('end', function(){ 2850 | Base.cursor.show(); 2851 | for (var i = 0; i < self.numberOfLines; i++) write('\n'); 2852 | self.epilogue(); 2853 | }); 2854 | } 2855 | 2856 | /** 2857 | * Draw the nyan cat with runner `status`. 2858 | * 2859 | * @param {String} status 2860 | * @api private 2861 | */ 2862 | 2863 | NyanCat.prototype.draw = function(status){ 2864 | this.appendRainbow(); 2865 | this.drawScoreboard(); 2866 | this.drawRainbow(); 2867 | this.drawNyanCat(status); 2868 | this.tick = !this.tick; 2869 | }; 2870 | 2871 | /** 2872 | * Draw the "scoreboard" showing the number 2873 | * of passes, failures and pending tests. 2874 | * 2875 | * @api private 2876 | */ 2877 | 2878 | NyanCat.prototype.drawScoreboard = function(){ 2879 | var stats = this.stats; 2880 | var colors = Base.colors; 2881 | 2882 | function draw(color, n) { 2883 | write(' '); 2884 | write('\u001b[' + color + 'm' + n + '\u001b[0m'); 2885 | write('\n'); 2886 | } 2887 | 2888 | draw(colors.green, stats.passes); 2889 | draw(colors.fail, stats.failures); 2890 | draw(colors.pending, stats.pending); 2891 | write('\n'); 2892 | 2893 | this.cursorUp(this.numberOfLines); 2894 | }; 2895 | 2896 | /** 2897 | * Append the rainbow. 2898 | * 2899 | * @api private 2900 | */ 2901 | 2902 | NyanCat.prototype.appendRainbow = function(){ 2903 | var segment = this.tick ? '_' : '-'; 2904 | var rainbowified = this.rainbowify(segment); 2905 | 2906 | for (var index = 0; index < this.numberOfLines; index++) { 2907 | var trajectory = this.trajectories[index]; 2908 | if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); 2909 | trajectory.push(rainbowified); 2910 | } 2911 | }; 2912 | 2913 | /** 2914 | * Draw the rainbow. 2915 | * 2916 | * @api private 2917 | */ 2918 | 2919 | NyanCat.prototype.drawRainbow = function(){ 2920 | var self = this; 2921 | 2922 | this.trajectories.forEach(function(line, index) { 2923 | write('\u001b[' + self.scoreboardWidth + 'C'); 2924 | write(line.join('')); 2925 | write('\n'); 2926 | }); 2927 | 2928 | this.cursorUp(this.numberOfLines); 2929 | }; 2930 | 2931 | /** 2932 | * Draw the nyan cat with `status`. 2933 | * 2934 | * @param {String} status 2935 | * @api private 2936 | */ 2937 | 2938 | NyanCat.prototype.drawNyanCat = function(status) { 2939 | var self = this; 2940 | var startWidth = this.scoreboardWidth + this.trajectories[0].length; 2941 | 2942 | [0, 1, 2, 3].forEach(function(index) { 2943 | write('\u001b[' + startWidth + 'C'); 2944 | 2945 | switch (index) { 2946 | case 0: 2947 | write('_,------,'); 2948 | write('\n'); 2949 | break; 2950 | case 1: 2951 | var padding = self.tick ? ' ' : ' '; 2952 | write('_|' + padding + '/\\_/\\ '); 2953 | write('\n'); 2954 | break; 2955 | case 2: 2956 | var padding = self.tick ? '_' : '__'; 2957 | var tail = self.tick ? '~' : '^'; 2958 | var face; 2959 | switch (status) { 2960 | case 'pass': 2961 | face = '( ^ .^)'; 2962 | break; 2963 | case 'fail': 2964 | face = '( o .o)'; 2965 | break; 2966 | default: 2967 | face = '( - .-)'; 2968 | } 2969 | write(tail + '|' + padding + face + ' '); 2970 | write('\n'); 2971 | break; 2972 | case 3: 2973 | var padding = self.tick ? ' ' : ' '; 2974 | write(padding + '"" "" '); 2975 | write('\n'); 2976 | break; 2977 | } 2978 | }); 2979 | 2980 | this.cursorUp(this.numberOfLines); 2981 | }; 2982 | 2983 | /** 2984 | * Move cursor up `n`. 2985 | * 2986 | * @param {Number} n 2987 | * @api private 2988 | */ 2989 | 2990 | NyanCat.prototype.cursorUp = function(n) { 2991 | write('\u001b[' + n + 'A'); 2992 | }; 2993 | 2994 | /** 2995 | * Move cursor down `n`. 2996 | * 2997 | * @param {Number} n 2998 | * @api private 2999 | */ 3000 | 3001 | NyanCat.prototype.cursorDown = function(n) { 3002 | write('\u001b[' + n + 'B'); 3003 | }; 3004 | 3005 | /** 3006 | * Generate rainbow colors. 3007 | * 3008 | * @return {Array} 3009 | * @api private 3010 | */ 3011 | 3012 | NyanCat.prototype.generateColors = function(){ 3013 | var colors = []; 3014 | 3015 | for (var i = 0; i < (6 * 7); i++) { 3016 | var pi3 = Math.floor(Math.PI / 3); 3017 | var n = (i * (1.0 / 6)); 3018 | var r = Math.floor(3 * Math.sin(n) + 3); 3019 | var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); 3020 | var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); 3021 | colors.push(36 * r + 6 * g + b + 16); 3022 | } 3023 | 3024 | return colors; 3025 | }; 3026 | 3027 | /** 3028 | * Apply rainbow to the given `str`. 3029 | * 3030 | * @param {String} str 3031 | * @return {String} 3032 | * @api private 3033 | */ 3034 | 3035 | NyanCat.prototype.rainbowify = function(str){ 3036 | var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; 3037 | this.colorIndex += 1; 3038 | return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; 3039 | }; 3040 | 3041 | /** 3042 | * Stdout helper. 3043 | */ 3044 | 3045 | function write(string) { 3046 | process.stdout.write(string); 3047 | } 3048 | 3049 | /** 3050 | * Inherit from `Base.prototype`. 3051 | */ 3052 | 3053 | NyanCat.prototype = new Base; 3054 | NyanCat.prototype.constructor = NyanCat; 3055 | 3056 | 3057 | }); // module: reporters/nyan.js 3058 | 3059 | require.register("reporters/progress.js", function(module, exports, require){ 3060 | 3061 | /** 3062 | * Module dependencies. 3063 | */ 3064 | 3065 | var Base = require('./base') 3066 | , cursor = Base.cursor 3067 | , color = Base.color; 3068 | 3069 | /** 3070 | * Expose `Progress`. 3071 | */ 3072 | 3073 | exports = module.exports = Progress; 3074 | 3075 | /** 3076 | * General progress bar color. 3077 | */ 3078 | 3079 | Base.colors.progress = 90; 3080 | 3081 | /** 3082 | * Initialize a new `Progress` bar test reporter. 3083 | * 3084 | * @param {Runner} runner 3085 | * @param {Object} options 3086 | * @api public 3087 | */ 3088 | 3089 | function Progress(runner, options) { 3090 | Base.call(this, runner); 3091 | 3092 | var self = this 3093 | , options = options || {} 3094 | , stats = this.stats 3095 | , width = Base.window.width * .50 | 0 3096 | , total = runner.total 3097 | , complete = 0 3098 | , max = Math.max; 3099 | 3100 | // default chars 3101 | options.open = options.open || '['; 3102 | options.complete = options.complete || '▬'; 3103 | options.incomplete = options.incomplete || Base.symbols.dot; 3104 | options.close = options.close || ']'; 3105 | options.verbose = false; 3106 | 3107 | // tests started 3108 | runner.on('start', function(){ 3109 | console.log(); 3110 | cursor.hide(); 3111 | }); 3112 | 3113 | // tests complete 3114 | runner.on('test end', function(){ 3115 | complete++; 3116 | var incomplete = total - complete 3117 | , percent = complete / total 3118 | , n = width * percent | 0 3119 | , i = width - n; 3120 | 3121 | cursor.CR(); 3122 | process.stdout.write('\u001b[J'); 3123 | process.stdout.write(color('progress', ' ' + options.open)); 3124 | process.stdout.write(Array(n).join(options.complete)); 3125 | process.stdout.write(Array(i).join(options.incomplete)); 3126 | process.stdout.write(color('progress', options.close)); 3127 | if (options.verbose) { 3128 | process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); 3129 | } 3130 | }); 3131 | 3132 | // tests are complete, output some stats 3133 | // and the failures if any 3134 | runner.on('end', function(){ 3135 | cursor.show(); 3136 | console.log(); 3137 | self.epilogue(); 3138 | }); 3139 | } 3140 | 3141 | /** 3142 | * Inherit from `Base.prototype`. 3143 | */ 3144 | 3145 | Progress.prototype = new Base; 3146 | Progress.prototype.constructor = Progress; 3147 | 3148 | 3149 | }); // module: reporters/progress.js 3150 | 3151 | require.register("reporters/spec.js", function(module, exports, require){ 3152 | 3153 | /** 3154 | * Module dependencies. 3155 | */ 3156 | 3157 | var Base = require('./base') 3158 | , cursor = Base.cursor 3159 | , color = Base.color; 3160 | 3161 | /** 3162 | * Expose `Spec`. 3163 | */ 3164 | 3165 | exports = module.exports = Spec; 3166 | 3167 | /** 3168 | * Initialize a new `Spec` test reporter. 3169 | * 3170 | * @param {Runner} runner 3171 | * @api public 3172 | */ 3173 | 3174 | function Spec(runner) { 3175 | Base.call(this, runner); 3176 | 3177 | var self = this 3178 | , stats = this.stats 3179 | , indents = 0 3180 | , n = 0; 3181 | 3182 | function indent() { 3183 | return Array(indents).join(' ') 3184 | } 3185 | 3186 | runner.on('start', function(){ 3187 | console.log(); 3188 | }); 3189 | 3190 | runner.on('suite', function(suite){ 3191 | ++indents; 3192 | console.log(color('suite', '%s%s'), indent(), suite.title); 3193 | }); 3194 | 3195 | runner.on('suite end', function(suite){ 3196 | --indents; 3197 | if (1 == indents) console.log(); 3198 | }); 3199 | 3200 | runner.on('test', function(test){ 3201 | process.stdout.write(indent() + color('pass', ' ◦ ' + test.title + ': ')); 3202 | }); 3203 | 3204 | runner.on('pending', function(test){ 3205 | var fmt = indent() + color('pending', ' - %s'); 3206 | console.log(fmt, test.title); 3207 | }); 3208 | 3209 | runner.on('pass', function(test){ 3210 | if ('fast' == test.speed) { 3211 | var fmt = indent() 3212 | + color('checkmark', ' ' + Base.symbols.ok) 3213 | + color('pass', ' %s '); 3214 | cursor.CR(); 3215 | console.log(fmt, test.title); 3216 | } else { 3217 | var fmt = indent() 3218 | + color('checkmark', ' ' + Base.symbols.ok) 3219 | + color('pass', ' %s ') 3220 | + color(test.speed, '(%dms)'); 3221 | cursor.CR(); 3222 | console.log(fmt, test.title, test.duration); 3223 | } 3224 | }); 3225 | 3226 | runner.on('fail', function(test, err){ 3227 | cursor.CR(); 3228 | console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); 3229 | }); 3230 | 3231 | runner.on('end', self.epilogue.bind(self)); 3232 | } 3233 | 3234 | /** 3235 | * Inherit from `Base.prototype`. 3236 | */ 3237 | 3238 | Spec.prototype = new Base; 3239 | Spec.prototype.constructor = Spec; 3240 | 3241 | 3242 | }); // module: reporters/spec.js 3243 | 3244 | require.register("reporters/tap.js", function(module, exports, require){ 3245 | 3246 | /** 3247 | * Module dependencies. 3248 | */ 3249 | 3250 | var Base = require('./base') 3251 | , cursor = Base.cursor 3252 | , color = Base.color; 3253 | 3254 | /** 3255 | * Expose `TAP`. 3256 | */ 3257 | 3258 | exports = module.exports = TAP; 3259 | 3260 | /** 3261 | * Initialize a new `TAP` reporter. 3262 | * 3263 | * @param {Runner} runner 3264 | * @api public 3265 | */ 3266 | 3267 | function TAP(runner) { 3268 | Base.call(this, runner); 3269 | 3270 | var self = this 3271 | , stats = this.stats 3272 | , n = 1; 3273 | 3274 | runner.on('start', function(){ 3275 | var total = runner.grepTotal(runner.suite); 3276 | console.log('%d..%d', 1, total); 3277 | }); 3278 | 3279 | runner.on('test end', function(){ 3280 | ++n; 3281 | }); 3282 | 3283 | runner.on('pending', function(test){ 3284 | console.log('ok %d %s # SKIP -', n, title(test)); 3285 | }); 3286 | 3287 | runner.on('pass', function(test){ 3288 | console.log('ok %d %s', n, title(test)); 3289 | }); 3290 | 3291 | runner.on('fail', function(test, err){ 3292 | console.log('not ok %d %s', n, title(test)); 3293 | console.log(err.stack.replace(/^/gm, ' ')); 3294 | }); 3295 | } 3296 | 3297 | /** 3298 | * Return a TAP-safe title of `test` 3299 | * 3300 | * @param {Object} test 3301 | * @return {String} 3302 | * @api private 3303 | */ 3304 | 3305 | function title(test) { 3306 | return test.fullTitle().replace(/#/g, ''); 3307 | } 3308 | 3309 | }); // module: reporters/tap.js 3310 | 3311 | require.register("reporters/teamcity.js", function(module, exports, require){ 3312 | 3313 | /** 3314 | * Module dependencies. 3315 | */ 3316 | 3317 | var Base = require('./base'); 3318 | 3319 | /** 3320 | * Expose `Teamcity`. 3321 | */ 3322 | 3323 | exports = module.exports = Teamcity; 3324 | 3325 | /** 3326 | * Initialize a new `Teamcity` reporter. 3327 | * 3328 | * @param {Runner} runner 3329 | * @api public 3330 | */ 3331 | 3332 | function Teamcity(runner) { 3333 | Base.call(this, runner); 3334 | var stats = this.stats; 3335 | 3336 | runner.on('start', function() { 3337 | console.log("##teamcity[testSuiteStarted name='mocha.suite']"); 3338 | }); 3339 | 3340 | runner.on('test', function(test) { 3341 | console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']"); 3342 | }); 3343 | 3344 | runner.on('fail', function(test, err) { 3345 | console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']"); 3346 | }); 3347 | 3348 | runner.on('pending', function(test) { 3349 | console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']"); 3350 | }); 3351 | 3352 | runner.on('test end', function(test) { 3353 | console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']"); 3354 | }); 3355 | 3356 | runner.on('end', function() { 3357 | console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']"); 3358 | }); 3359 | } 3360 | 3361 | /** 3362 | * Escape the given `str`. 3363 | */ 3364 | 3365 | function escape(str) { 3366 | return str 3367 | .replace(/\|/g, "||") 3368 | .replace(/\n/g, "|n") 3369 | .replace(/\r/g, "|r") 3370 | .replace(/\[/g, "|[") 3371 | .replace(/\]/g, "|]") 3372 | .replace(/\u0085/g, "|x") 3373 | .replace(/\u2028/g, "|l") 3374 | .replace(/\u2029/g, "|p") 3375 | .replace(/'/g, "|'"); 3376 | } 3377 | 3378 | }); // module: reporters/teamcity.js 3379 | 3380 | require.register("reporters/xunit.js", function(module, exports, require){ 3381 | 3382 | /** 3383 | * Module dependencies. 3384 | */ 3385 | 3386 | var Base = require('./base') 3387 | , utils = require('../utils') 3388 | , escape = utils.escape; 3389 | 3390 | /** 3391 | * Save timer references to avoid Sinon interfering (see GH-237). 3392 | */ 3393 | 3394 | var Date = global.Date 3395 | , setTimeout = global.setTimeout 3396 | , setInterval = global.setInterval 3397 | , clearTimeout = global.clearTimeout 3398 | , clearInterval = global.clearInterval; 3399 | 3400 | /** 3401 | * Expose `XUnit`. 3402 | */ 3403 | 3404 | exports = module.exports = XUnit; 3405 | 3406 | /** 3407 | * Initialize a new `XUnit` reporter. 3408 | * 3409 | * @param {Runner} runner 3410 | * @api public 3411 | */ 3412 | 3413 | function XUnit(runner) { 3414 | Base.call(this, runner); 3415 | var stats = this.stats 3416 | , tests = [] 3417 | , self = this; 3418 | 3419 | runner.on('pass', function(test){ 3420 | tests.push(test); 3421 | }); 3422 | 3423 | runner.on('fail', function(test){ 3424 | tests.push(test); 3425 | }); 3426 | 3427 | runner.on('end', function(){ 3428 | console.log(tag('testsuite', { 3429 | name: 'Mocha Tests' 3430 | , tests: stats.tests 3431 | , failures: stats.failures 3432 | , errors: stats.failures 3433 | , skip: stats.tests - stats.failures - stats.passes 3434 | , timestamp: (new Date).toUTCString() 3435 | , time: stats.duration / 1000 3436 | }, false)); 3437 | 3438 | tests.forEach(test); 3439 | console.log(''); 3440 | }); 3441 | } 3442 | 3443 | /** 3444 | * Inherit from `Base.prototype`. 3445 | */ 3446 | 3447 | XUnit.prototype = new Base; 3448 | XUnit.prototype.constructor = XUnit; 3449 | 3450 | 3451 | /** 3452 | * Output tag for the given `test.` 3453 | */ 3454 | 3455 | function test(test) { 3456 | var attrs = { 3457 | classname: test.parent.fullTitle() 3458 | , name: test.title 3459 | , time: test.duration / 1000 3460 | }; 3461 | 3462 | if ('failed' == test.state) { 3463 | var err = test.err; 3464 | attrs.message = escape(err.message); 3465 | console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack)))); 3466 | } else if (test.pending) { 3467 | console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); 3468 | } else { 3469 | console.log(tag('testcase', attrs, true) ); 3470 | } 3471 | } 3472 | 3473 | /** 3474 | * HTML tag helper. 3475 | */ 3476 | 3477 | function tag(name, attrs, close, content) { 3478 | var end = close ? '/>' : '>' 3479 | , pairs = [] 3480 | , tag; 3481 | 3482 | for (var key in attrs) { 3483 | pairs.push(key + '="' + escape(attrs[key]) + '"'); 3484 | } 3485 | 3486 | tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; 3487 | if (content) tag += content + ''; 3497 | } 3498 | 3499 | }); // module: reporters/xunit.js 3500 | 3501 | require.register("runnable.js", function(module, exports, require){ 3502 | 3503 | /** 3504 | * Module dependencies. 3505 | */ 3506 | 3507 | var EventEmitter = require('browser/events').EventEmitter 3508 | , debug = require('browser/debug')('mocha:runnable') 3509 | , milliseconds = require('./ms'); 3510 | 3511 | /** 3512 | * Save timer references to avoid Sinon interfering (see GH-237). 3513 | */ 3514 | 3515 | var Date = global.Date 3516 | , setTimeout = global.setTimeout 3517 | , setInterval = global.setInterval 3518 | , clearTimeout = global.clearTimeout 3519 | , clearInterval = global.clearInterval; 3520 | 3521 | /** 3522 | * Expose `Runnable`. 3523 | */ 3524 | 3525 | module.exports = Runnable; 3526 | 3527 | /** 3528 | * Initialize a new `Runnable` with the given `title` and callback `fn`. 3529 | * 3530 | * @param {String} title 3531 | * @param {Function} fn 3532 | * @api private 3533 | */ 3534 | 3535 | function Runnable(title, fn) { 3536 | this.title = title; 3537 | this.fn = fn; 3538 | this.async = fn && fn.length; 3539 | this.sync = ! this.async; 3540 | this._timeout = 2000; 3541 | this._slow = 75; 3542 | this.timedOut = false; 3543 | } 3544 | 3545 | /** 3546 | * Inherit from `EventEmitter.prototype`. 3547 | */ 3548 | 3549 | Runnable.prototype = new EventEmitter; 3550 | Runnable.prototype.constructor = Runnable; 3551 | 3552 | 3553 | /** 3554 | * Set & get timeout `ms`. 3555 | * 3556 | * @param {Number|String} ms 3557 | * @return {Runnable|Number} ms or self 3558 | * @api private 3559 | */ 3560 | 3561 | Runnable.prototype.timeout = function(ms){ 3562 | if (0 == arguments.length) return this._timeout; 3563 | if ('string' == typeof ms) ms = milliseconds(ms); 3564 | debug('timeout %d', ms); 3565 | this._timeout = ms; 3566 | if (this.timer) this.resetTimeout(); 3567 | return this; 3568 | }; 3569 | 3570 | /** 3571 | * Set & get slow `ms`. 3572 | * 3573 | * @param {Number|String} ms 3574 | * @return {Runnable|Number} ms or self 3575 | * @api private 3576 | */ 3577 | 3578 | Runnable.prototype.slow = function(ms){ 3579 | if (0 === arguments.length) return this._slow; 3580 | if ('string' == typeof ms) ms = milliseconds(ms); 3581 | debug('timeout %d', ms); 3582 | this._slow = ms; 3583 | return this; 3584 | }; 3585 | 3586 | /** 3587 | * Return the full title generated by recursively 3588 | * concatenating the parent's full title. 3589 | * 3590 | * @return {String} 3591 | * @api public 3592 | */ 3593 | 3594 | Runnable.prototype.fullTitle = function(){ 3595 | return this.parent.fullTitle() + ' ' + this.title; 3596 | }; 3597 | 3598 | /** 3599 | * Clear the timeout. 3600 | * 3601 | * @api private 3602 | */ 3603 | 3604 | Runnable.prototype.clearTimeout = function(){ 3605 | clearTimeout(this.timer); 3606 | }; 3607 | 3608 | /** 3609 | * Inspect the runnable void of private properties. 3610 | * 3611 | * @return {String} 3612 | * @api private 3613 | */ 3614 | 3615 | Runnable.prototype.inspect = function(){ 3616 | return JSON.stringify(this, function(key, val){ 3617 | if ('_' == key[0]) return; 3618 | if ('parent' == key) return '#'; 3619 | if ('ctx' == key) return '#'; 3620 | return val; 3621 | }, 2); 3622 | }; 3623 | 3624 | /** 3625 | * Reset the timeout. 3626 | * 3627 | * @api private 3628 | */ 3629 | 3630 | Runnable.prototype.resetTimeout = function(){ 3631 | var self = this 3632 | , ms = this.timeout(); 3633 | 3634 | this.clearTimeout(); 3635 | if (ms) { 3636 | this.timer = setTimeout(function(){ 3637 | self.callback(new Error('timeout of ' + ms + 'ms exceeded')); 3638 | self.timedOut = true; 3639 | }, ms); 3640 | } 3641 | }; 3642 | 3643 | /** 3644 | * Run the test and invoke `fn(err)`. 3645 | * 3646 | * @param {Function} fn 3647 | * @api private 3648 | */ 3649 | 3650 | Runnable.prototype.run = function(fn){ 3651 | var self = this 3652 | , ms = this.timeout() 3653 | , start = new Date 3654 | , ctx = this.ctx 3655 | , finished 3656 | , emitted; 3657 | 3658 | if (ctx) ctx.runnable(this); 3659 | 3660 | // timeout 3661 | if (this.async) { 3662 | if (ms) { 3663 | this.timer = setTimeout(function(){ 3664 | done(new Error('timeout of ' + ms + 'ms exceeded')); 3665 | self.timedOut = true; 3666 | }, ms); 3667 | } 3668 | } 3669 | 3670 | // called multiple times 3671 | function multiple(err) { 3672 | if (emitted) return; 3673 | emitted = true; 3674 | self.emit('error', err || new Error('done() called multiple times')); 3675 | } 3676 | 3677 | // finished 3678 | function done(err) { 3679 | if (self.timedOut) return; 3680 | if (finished) return multiple(err); 3681 | self.clearTimeout(); 3682 | self.duration = new Date - start; 3683 | finished = true; 3684 | fn(err); 3685 | } 3686 | 3687 | // for .resetTimeout() 3688 | this.callback = done; 3689 | 3690 | // async 3691 | if (this.async) { 3692 | try { 3693 | this.fn.call(ctx, function(err){ 3694 | if (err instanceof Error) return done(err); 3695 | if (null != err) return done(new Error('done() invoked with non-Error: ' + err)); 3696 | done(); 3697 | }); 3698 | } catch (err) { 3699 | done(err); 3700 | } 3701 | return; 3702 | } 3703 | 3704 | if (this.asyncOnly) { 3705 | return done(new Error('--async-only option in use without declaring `done()`')); 3706 | } 3707 | 3708 | // sync 3709 | try { 3710 | if (!this.pending) this.fn.call(ctx); 3711 | this.duration = new Date - start; 3712 | fn(); 3713 | } catch (err) { 3714 | fn(err); 3715 | } 3716 | }; 3717 | 3718 | }); // module: runnable.js 3719 | 3720 | require.register("runner.js", function(module, exports, require){ 3721 | 3722 | /** 3723 | * Module dependencies. 3724 | */ 3725 | 3726 | var EventEmitter = require('browser/events').EventEmitter 3727 | , debug = require('browser/debug')('mocha:runner') 3728 | , Test = require('./test') 3729 | , utils = require('./utils') 3730 | , filter = utils.filter 3731 | , keys = utils.keys 3732 | , noop = function(){}; 3733 | 3734 | /** 3735 | * Non-enumerable globals. 3736 | */ 3737 | 3738 | var globals = [ 3739 | 'setTimeout', 3740 | 'clearTimeout', 3741 | 'setInterval', 3742 | 'clearInterval', 3743 | 'XMLHttpRequest', 3744 | 'Date' 3745 | ]; 3746 | 3747 | /** 3748 | * Expose `Runner`. 3749 | */ 3750 | 3751 | module.exports = Runner; 3752 | 3753 | /** 3754 | * Initialize a `Runner` for the given `suite`. 3755 | * 3756 | * Events: 3757 | * 3758 | * - `start` execution started 3759 | * - `end` execution complete 3760 | * - `suite` (suite) test suite execution started 3761 | * - `suite end` (suite) all tests (and sub-suites) have finished 3762 | * - `test` (test) test execution started 3763 | * - `test end` (test) test completed 3764 | * - `hook` (hook) hook execution started 3765 | * - `hook end` (hook) hook complete 3766 | * - `pass` (test) test passed 3767 | * - `fail` (test, err) test failed 3768 | * 3769 | * @api public 3770 | */ 3771 | 3772 | function Runner(suite) { 3773 | var self = this; 3774 | this._globals = []; 3775 | this.suite = suite; 3776 | this.total = suite.total(); 3777 | this.failures = 0; 3778 | this.on('test end', function(test){ self.checkGlobals(test); }); 3779 | this.on('hook end', function(hook){ self.checkGlobals(hook); }); 3780 | this.grep(/.*/); 3781 | this.globals(this.globalProps().concat(['errno'])); 3782 | } 3783 | 3784 | /** 3785 | * Inherit from `EventEmitter.prototype`. 3786 | */ 3787 | 3788 | Runner.prototype = new EventEmitter; 3789 | Runner.prototype.constructor = Runner; 3790 | 3791 | 3792 | /** 3793 | * Run tests with full titles matching `re`. Updates runner.total 3794 | * with number of tests matched. 3795 | * 3796 | * @param {RegExp} re 3797 | * @param {Boolean} invert 3798 | * @return {Runner} for chaining 3799 | * @api public 3800 | */ 3801 | 3802 | Runner.prototype.grep = function(re, invert){ 3803 | debug('grep %s', re); 3804 | this._grep = re; 3805 | this._invert = invert; 3806 | this.total = this.grepTotal(this.suite); 3807 | return this; 3808 | }; 3809 | 3810 | /** 3811 | * Returns the number of tests matching the grep search for the 3812 | * given suite. 3813 | * 3814 | * @param {Suite} suite 3815 | * @return {Number} 3816 | * @api public 3817 | */ 3818 | 3819 | Runner.prototype.grepTotal = function(suite) { 3820 | var self = this; 3821 | var total = 0; 3822 | 3823 | suite.eachTest(function(test){ 3824 | var match = self._grep.test(test.fullTitle()); 3825 | if (self._invert) match = !match; 3826 | if (match) total++; 3827 | }); 3828 | 3829 | return total; 3830 | }; 3831 | 3832 | /** 3833 | * Return a list of global properties. 3834 | * 3835 | * @return {Array} 3836 | * @api private 3837 | */ 3838 | 3839 | Runner.prototype.globalProps = function() { 3840 | var props = utils.keys(global); 3841 | 3842 | // non-enumerables 3843 | for (var i = 0; i < globals.length; ++i) { 3844 | if (~props.indexOf(globals[i])) continue; 3845 | props.push(globals[i]); 3846 | } 3847 | 3848 | return props; 3849 | }; 3850 | 3851 | /** 3852 | * Allow the given `arr` of globals. 3853 | * 3854 | * @param {Array} arr 3855 | * @return {Runner} for chaining 3856 | * @api public 3857 | */ 3858 | 3859 | Runner.prototype.globals = function(arr){ 3860 | if (0 == arguments.length) return this._globals; 3861 | debug('globals %j', arr); 3862 | utils.forEach(arr, function(arr){ 3863 | this._globals.push(arr); 3864 | }, this); 3865 | return this; 3866 | }; 3867 | 3868 | /** 3869 | * Check for global variable leaks. 3870 | * 3871 | * @api private 3872 | */ 3873 | 3874 | Runner.prototype.checkGlobals = function(test){ 3875 | if (this.ignoreLeaks) return; 3876 | var ok = this._globals; 3877 | var globals = this.globalProps(); 3878 | var isNode = process.kill; 3879 | var leaks; 3880 | 3881 | // check length - 2 ('errno' and 'location' globals) 3882 | if (isNode && 1 == ok.length - globals.length) return 3883 | else if (2 == ok.length - globals.length) return; 3884 | 3885 | leaks = filterLeaks(ok, globals); 3886 | this._globals = this._globals.concat(leaks); 3887 | 3888 | if (leaks.length > 1) { 3889 | this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); 3890 | } else if (leaks.length) { 3891 | this.fail(test, new Error('global leak detected: ' + leaks[0])); 3892 | } 3893 | }; 3894 | 3895 | /** 3896 | * Fail the given `test`. 3897 | * 3898 | * @param {Test} test 3899 | * @param {Error} err 3900 | * @api private 3901 | */ 3902 | 3903 | Runner.prototype.fail = function(test, err){ 3904 | ++this.failures; 3905 | test.state = 'failed'; 3906 | if ('string' == typeof err) { 3907 | err = new Error('the string "' + err + '" was thrown, throw an Error :)'); 3908 | } 3909 | this.emit('fail', test, err); 3910 | }; 3911 | 3912 | /** 3913 | * Fail the given `hook` with `err`. 3914 | * 3915 | * Hook failures (currently) hard-end due 3916 | * to that fact that a failing hook will 3917 | * surely cause subsequent tests to fail, 3918 | * causing jumbled reporting. 3919 | * 3920 | * @param {Hook} hook 3921 | * @param {Error} err 3922 | * @api private 3923 | */ 3924 | 3925 | Runner.prototype.failHook = function(hook, err){ 3926 | this.fail(hook, err); 3927 | this.emit('end'); 3928 | }; 3929 | 3930 | /** 3931 | * Run hook `name` callbacks and then invoke `fn()`. 3932 | * 3933 | * @param {String} name 3934 | * @param {Function} function 3935 | * @api private 3936 | */ 3937 | 3938 | Runner.prototype.hook = function(name, fn){ 3939 | var suite = this.suite 3940 | , hooks = suite['_' + name] 3941 | , self = this 3942 | , timer; 3943 | 3944 | function next(i) { 3945 | var hook = hooks[i]; 3946 | if (!hook) return fn(); 3947 | self.currentRunnable = hook; 3948 | 3949 | self.emit('hook', hook); 3950 | 3951 | hook.on('error', function(err){ 3952 | self.failHook(hook, err); 3953 | }); 3954 | 3955 | hook.run(function(err){ 3956 | hook.removeAllListeners('error'); 3957 | var testError = hook.error(); 3958 | if (testError) self.fail(self.test, testError); 3959 | if (err) return self.failHook(hook, err); 3960 | self.emit('hook end', hook); 3961 | next(++i); 3962 | }); 3963 | } 3964 | 3965 | process.nextTick(function(){ 3966 | next(0); 3967 | }); 3968 | }; 3969 | 3970 | /** 3971 | * Run hook `name` for the given array of `suites` 3972 | * in order, and callback `fn(err)`. 3973 | * 3974 | * @param {String} name 3975 | * @param {Array} suites 3976 | * @param {Function} fn 3977 | * @api private 3978 | */ 3979 | 3980 | Runner.prototype.hooks = function(name, suites, fn){ 3981 | var self = this 3982 | , orig = this.suite; 3983 | 3984 | function next(suite) { 3985 | self.suite = suite; 3986 | 3987 | if (!suite) { 3988 | self.suite = orig; 3989 | return fn(); 3990 | } 3991 | 3992 | self.hook(name, function(err){ 3993 | if (err) { 3994 | self.suite = orig; 3995 | return fn(err); 3996 | } 3997 | 3998 | next(suites.pop()); 3999 | }); 4000 | } 4001 | 4002 | next(suites.pop()); 4003 | }; 4004 | 4005 | /** 4006 | * Run hooks from the top level down. 4007 | * 4008 | * @param {String} name 4009 | * @param {Function} fn 4010 | * @api private 4011 | */ 4012 | 4013 | Runner.prototype.hookUp = function(name, fn){ 4014 | var suites = [this.suite].concat(this.parents()).reverse(); 4015 | this.hooks(name, suites, fn); 4016 | }; 4017 | 4018 | /** 4019 | * Run hooks from the bottom up. 4020 | * 4021 | * @param {String} name 4022 | * @param {Function} fn 4023 | * @api private 4024 | */ 4025 | 4026 | Runner.prototype.hookDown = function(name, fn){ 4027 | var suites = [this.suite].concat(this.parents()); 4028 | this.hooks(name, suites, fn); 4029 | }; 4030 | 4031 | /** 4032 | * Return an array of parent Suites from 4033 | * closest to furthest. 4034 | * 4035 | * @return {Array} 4036 | * @api private 4037 | */ 4038 | 4039 | Runner.prototype.parents = function(){ 4040 | var suite = this.suite 4041 | , suites = []; 4042 | while (suite = suite.parent) suites.push(suite); 4043 | return suites; 4044 | }; 4045 | 4046 | /** 4047 | * Run the current test and callback `fn(err)`. 4048 | * 4049 | * @param {Function} fn 4050 | * @api private 4051 | */ 4052 | 4053 | Runner.prototype.runTest = function(fn){ 4054 | var test = this.test 4055 | , self = this; 4056 | 4057 | if (this.asyncOnly) test.asyncOnly = true; 4058 | 4059 | try { 4060 | test.on('error', function(err){ 4061 | self.fail(test, err); 4062 | }); 4063 | test.run(fn); 4064 | } catch (err) { 4065 | fn(err); 4066 | } 4067 | }; 4068 | 4069 | /** 4070 | * Run tests in the given `suite` and invoke 4071 | * the callback `fn()` when complete. 4072 | * 4073 | * @param {Suite} suite 4074 | * @param {Function} fn 4075 | * @api private 4076 | */ 4077 | 4078 | Runner.prototype.runTests = function(suite, fn){ 4079 | var self = this 4080 | , tests = suite.tests.slice() 4081 | , test; 4082 | 4083 | function next(err) { 4084 | // if we bail after first err 4085 | if (self.failures && suite._bail) return fn(); 4086 | 4087 | // next test 4088 | test = tests.shift(); 4089 | 4090 | // all done 4091 | if (!test) return fn(); 4092 | 4093 | // grep 4094 | var match = self._grep.test(test.fullTitle()); 4095 | if (self._invert) match = !match; 4096 | if (!match) return next(); 4097 | 4098 | // pending 4099 | if (test.pending) { 4100 | self.emit('pending', test); 4101 | self.emit('test end', test); 4102 | return next(); 4103 | } 4104 | 4105 | // execute test and hook(s) 4106 | self.emit('test', self.test = test); 4107 | self.hookDown('beforeEach', function(){ 4108 | self.currentRunnable = self.test; 4109 | self.runTest(function(err){ 4110 | test = self.test; 4111 | 4112 | if (err) { 4113 | self.fail(test, err); 4114 | self.emit('test end', test); 4115 | return self.hookUp('afterEach', next); 4116 | } 4117 | 4118 | test.state = 'passed'; 4119 | self.emit('pass', test); 4120 | self.emit('test end', test); 4121 | self.hookUp('afterEach', next); 4122 | }); 4123 | }); 4124 | } 4125 | 4126 | this.next = next; 4127 | next(); 4128 | }; 4129 | 4130 | /** 4131 | * Run the given `suite` and invoke the 4132 | * callback `fn()` when complete. 4133 | * 4134 | * @param {Suite} suite 4135 | * @param {Function} fn 4136 | * @api private 4137 | */ 4138 | 4139 | Runner.prototype.runSuite = function(suite, fn){ 4140 | var total = this.grepTotal(suite) 4141 | , self = this 4142 | , i = 0; 4143 | 4144 | debug('run suite %s', suite.fullTitle()); 4145 | 4146 | if (!total) return fn(); 4147 | 4148 | this.emit('suite', this.suite = suite); 4149 | 4150 | function next() { 4151 | var curr = suite.suites[i++]; 4152 | if (!curr) return done(); 4153 | self.runSuite(curr, next); 4154 | } 4155 | 4156 | function done() { 4157 | self.suite = suite; 4158 | self.hook('afterAll', function(){ 4159 | self.emit('suite end', suite); 4160 | fn(); 4161 | }); 4162 | } 4163 | 4164 | this.hook('beforeAll', function(){ 4165 | self.runTests(suite, next); 4166 | }); 4167 | }; 4168 | 4169 | /** 4170 | * Handle uncaught exceptions. 4171 | * 4172 | * @param {Error} err 4173 | * @api private 4174 | */ 4175 | 4176 | Runner.prototype.uncaught = function(err){ 4177 | debug('uncaught exception %s', err.message); 4178 | var runnable = this.currentRunnable; 4179 | if (!runnable || 'failed' == runnable.state) return; 4180 | runnable.clearTimeout(); 4181 | err.uncaught = true; 4182 | this.fail(runnable, err); 4183 | 4184 | // recover from test 4185 | if ('test' == runnable.type) { 4186 | this.emit('test end', runnable); 4187 | this.hookUp('afterEach', this.next); 4188 | return; 4189 | } 4190 | 4191 | // bail on hooks 4192 | this.emit('end'); 4193 | }; 4194 | 4195 | /** 4196 | * Run the root suite and invoke `fn(failures)` 4197 | * on completion. 4198 | * 4199 | * @param {Function} fn 4200 | * @return {Runner} for chaining 4201 | * @api public 4202 | */ 4203 | 4204 | Runner.prototype.run = function(fn){ 4205 | var self = this 4206 | , fn = fn || function(){}; 4207 | 4208 | debug('start'); 4209 | 4210 | // uncaught callback 4211 | function uncaught(err) { 4212 | self.uncaught(err); 4213 | } 4214 | 4215 | // callback 4216 | this.on('end', function(){ 4217 | debug('end'); 4218 | process.removeListener('uncaughtException', uncaught); 4219 | fn(self.failures); 4220 | }); 4221 | 4222 | // run suites 4223 | this.emit('start'); 4224 | this.runSuite(this.suite, function(){ 4225 | debug('finished running'); 4226 | self.emit('end'); 4227 | }); 4228 | 4229 | // uncaught exception 4230 | process.on('uncaughtException', uncaught); 4231 | 4232 | return this; 4233 | }; 4234 | 4235 | /** 4236 | * Filter leaks with the given globals flagged as `ok`. 4237 | * 4238 | * @param {Array} ok 4239 | * @param {Array} globals 4240 | * @return {Array} 4241 | * @api private 4242 | */ 4243 | 4244 | function filterLeaks(ok, globals) { 4245 | return filter(globals, function(key){ 4246 | var matched = filter(ok, function(ok){ 4247 | if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); 4248 | // Opera and IE expose global variables for HTML element IDs (issue #243) 4249 | if (/^mocha-/.test(key)) return true; 4250 | return key == ok; 4251 | }); 4252 | return matched.length == 0 && (!global.navigator || 'onerror' !== key); 4253 | }); 4254 | } 4255 | 4256 | }); // module: runner.js 4257 | 4258 | require.register("suite.js", function(module, exports, require){ 4259 | 4260 | /** 4261 | * Module dependencies. 4262 | */ 4263 | 4264 | var EventEmitter = require('browser/events').EventEmitter 4265 | , debug = require('browser/debug')('mocha:suite') 4266 | , milliseconds = require('./ms') 4267 | , utils = require('./utils') 4268 | , Hook = require('./hook'); 4269 | 4270 | /** 4271 | * Expose `Suite`. 4272 | */ 4273 | 4274 | exports = module.exports = Suite; 4275 | 4276 | /** 4277 | * Create a new `Suite` with the given `title` 4278 | * and parent `Suite`. When a suite with the 4279 | * same title is already present, that suite 4280 | * is returned to provide nicer reporter 4281 | * and more flexible meta-testing. 4282 | * 4283 | * @param {Suite} parent 4284 | * @param {String} title 4285 | * @return {Suite} 4286 | * @api public 4287 | */ 4288 | 4289 | exports.create = function(parent, title){ 4290 | var suite = new Suite(title, parent.ctx); 4291 | suite.parent = parent; 4292 | if (parent.pending) suite.pending = true; 4293 | title = suite.fullTitle(); 4294 | parent.addSuite(suite); 4295 | return suite; 4296 | }; 4297 | 4298 | /** 4299 | * Initialize a new `Suite` with the given 4300 | * `title` and `ctx`. 4301 | * 4302 | * @param {String} title 4303 | * @param {Context} ctx 4304 | * @api private 4305 | */ 4306 | 4307 | function Suite(title, ctx) { 4308 | this.title = title; 4309 | this.ctx = ctx; 4310 | this.suites = []; 4311 | this.tests = []; 4312 | this.pending = false; 4313 | this._beforeEach = []; 4314 | this._beforeAll = []; 4315 | this._afterEach = []; 4316 | this._afterAll = []; 4317 | this.root = !title; 4318 | this._timeout = 2000; 4319 | this._slow = 75; 4320 | this._bail = false; 4321 | } 4322 | 4323 | /** 4324 | * Inherit from `EventEmitter.prototype`. 4325 | */ 4326 | 4327 | Suite.prototype = new EventEmitter; 4328 | Suite.prototype.constructor = Suite; 4329 | 4330 | 4331 | /** 4332 | * Return a clone of this `Suite`. 4333 | * 4334 | * @return {Suite} 4335 | * @api private 4336 | */ 4337 | 4338 | Suite.prototype.clone = function(){ 4339 | var suite = new Suite(this.title); 4340 | debug('clone'); 4341 | suite.ctx = this.ctx; 4342 | suite.timeout(this.timeout()); 4343 | suite.slow(this.slow()); 4344 | suite.bail(this.bail()); 4345 | return suite; 4346 | }; 4347 | 4348 | /** 4349 | * Set timeout `ms` or short-hand such as "2s". 4350 | * 4351 | * @param {Number|String} ms 4352 | * @return {Suite|Number} for chaining 4353 | * @api private 4354 | */ 4355 | 4356 | Suite.prototype.timeout = function(ms){ 4357 | if (0 == arguments.length) return this._timeout; 4358 | if ('string' == typeof ms) ms = milliseconds(ms); 4359 | debug('timeout %d', ms); 4360 | this._timeout = parseInt(ms, 10); 4361 | return this; 4362 | }; 4363 | 4364 | /** 4365 | * Set slow `ms` or short-hand such as "2s". 4366 | * 4367 | * @param {Number|String} ms 4368 | * @return {Suite|Number} for chaining 4369 | * @api private 4370 | */ 4371 | 4372 | Suite.prototype.slow = function(ms){ 4373 | if (0 === arguments.length) return this._slow; 4374 | if ('string' == typeof ms) ms = milliseconds(ms); 4375 | debug('slow %d', ms); 4376 | this._slow = ms; 4377 | return this; 4378 | }; 4379 | 4380 | /** 4381 | * Sets whether to bail after first error. 4382 | * 4383 | * @parma {Boolean} bail 4384 | * @return {Suite|Number} for chaining 4385 | * @api private 4386 | */ 4387 | 4388 | Suite.prototype.bail = function(bail){ 4389 | if (0 == arguments.length) return this._bail; 4390 | debug('bail %s', bail); 4391 | this._bail = bail; 4392 | return this; 4393 | }; 4394 | 4395 | /** 4396 | * Run `fn(test[, done])` before running tests. 4397 | * 4398 | * @param {Function} fn 4399 | * @return {Suite} for chaining 4400 | * @api private 4401 | */ 4402 | 4403 | Suite.prototype.beforeAll = function(fn){ 4404 | if (this.pending) return this; 4405 | var hook = new Hook('"before all" hook', fn); 4406 | hook.parent = this; 4407 | hook.timeout(this.timeout()); 4408 | hook.slow(this.slow()); 4409 | hook.ctx = this.ctx; 4410 | this._beforeAll.push(hook); 4411 | this.emit('beforeAll', hook); 4412 | return this; 4413 | }; 4414 | 4415 | /** 4416 | * Run `fn(test[, done])` after running tests. 4417 | * 4418 | * @param {Function} fn 4419 | * @return {Suite} for chaining 4420 | * @api private 4421 | */ 4422 | 4423 | Suite.prototype.afterAll = function(fn){ 4424 | if (this.pending) return this; 4425 | var hook = new Hook('"after all" hook', fn); 4426 | hook.parent = this; 4427 | hook.timeout(this.timeout()); 4428 | hook.slow(this.slow()); 4429 | hook.ctx = this.ctx; 4430 | this._afterAll.push(hook); 4431 | this.emit('afterAll', hook); 4432 | return this; 4433 | }; 4434 | 4435 | /** 4436 | * Run `fn(test[, done])` before each test case. 4437 | * 4438 | * @param {Function} fn 4439 | * @return {Suite} for chaining 4440 | * @api private 4441 | */ 4442 | 4443 | Suite.prototype.beforeEach = function(fn){ 4444 | if (this.pending) return this; 4445 | var hook = new Hook('"before each" hook', fn); 4446 | hook.parent = this; 4447 | hook.timeout(this.timeout()); 4448 | hook.slow(this.slow()); 4449 | hook.ctx = this.ctx; 4450 | this._beforeEach.push(hook); 4451 | this.emit('beforeEach', hook); 4452 | return this; 4453 | }; 4454 | 4455 | /** 4456 | * Run `fn(test[, done])` after each test case. 4457 | * 4458 | * @param {Function} fn 4459 | * @return {Suite} for chaining 4460 | * @api private 4461 | */ 4462 | 4463 | Suite.prototype.afterEach = function(fn){ 4464 | if (this.pending) return this; 4465 | var hook = new Hook('"after each" hook', fn); 4466 | hook.parent = this; 4467 | hook.timeout(this.timeout()); 4468 | hook.slow(this.slow()); 4469 | hook.ctx = this.ctx; 4470 | this._afterEach.push(hook); 4471 | this.emit('afterEach', hook); 4472 | return this; 4473 | }; 4474 | 4475 | /** 4476 | * Add a test `suite`. 4477 | * 4478 | * @param {Suite} suite 4479 | * @return {Suite} for chaining 4480 | * @api private 4481 | */ 4482 | 4483 | Suite.prototype.addSuite = function(suite){ 4484 | suite.parent = this; 4485 | suite.timeout(this.timeout()); 4486 | suite.slow(this.slow()); 4487 | suite.bail(this.bail()); 4488 | this.suites.push(suite); 4489 | this.emit('suite', suite); 4490 | return this; 4491 | }; 4492 | 4493 | /** 4494 | * Add a `test` to this suite. 4495 | * 4496 | * @param {Test} test 4497 | * @return {Suite} for chaining 4498 | * @api private 4499 | */ 4500 | 4501 | Suite.prototype.addTest = function(test){ 4502 | test.parent = this; 4503 | test.timeout(this.timeout()); 4504 | test.slow(this.slow()); 4505 | test.ctx = this.ctx; 4506 | this.tests.push(test); 4507 | this.emit('test', test); 4508 | return this; 4509 | }; 4510 | 4511 | /** 4512 | * Return the full title generated by recursively 4513 | * concatenating the parent's full title. 4514 | * 4515 | * @return {String} 4516 | * @api public 4517 | */ 4518 | 4519 | Suite.prototype.fullTitle = function(){ 4520 | if (this.parent) { 4521 | var full = this.parent.fullTitle(); 4522 | if (full) return full + ' ' + this.title; 4523 | } 4524 | return this.title; 4525 | }; 4526 | 4527 | /** 4528 | * Return the total number of tests. 4529 | * 4530 | * @return {Number} 4531 | * @api public 4532 | */ 4533 | 4534 | Suite.prototype.total = function(){ 4535 | return utils.reduce(this.suites, function(sum, suite){ 4536 | return sum + suite.total(); 4537 | }, 0) + this.tests.length; 4538 | }; 4539 | 4540 | /** 4541 | * Iterates through each suite recursively to find 4542 | * all tests. Applies a function in the format 4543 | * `fn(test)`. 4544 | * 4545 | * @param {Function} fn 4546 | * @return {Suite} 4547 | * @api private 4548 | */ 4549 | 4550 | Suite.prototype.eachTest = function(fn){ 4551 | utils.forEach(this.tests, fn); 4552 | utils.forEach(this.suites, function(suite){ 4553 | suite.eachTest(fn); 4554 | }); 4555 | return this; 4556 | }; 4557 | 4558 | }); // module: suite.js 4559 | 4560 | require.register("test.js", function(module, exports, require){ 4561 | 4562 | /** 4563 | * Module dependencies. 4564 | */ 4565 | 4566 | var Runnable = require('./runnable'); 4567 | 4568 | /** 4569 | * Expose `Test`. 4570 | */ 4571 | 4572 | module.exports = Test; 4573 | 4574 | /** 4575 | * Initialize a new `Test` with the given `title` and callback `fn`. 4576 | * 4577 | * @param {String} title 4578 | * @param {Function} fn 4579 | * @api private 4580 | */ 4581 | 4582 | function Test(title, fn) { 4583 | Runnable.call(this, title, fn); 4584 | this.pending = !fn; 4585 | this.type = 'test'; 4586 | } 4587 | 4588 | /** 4589 | * Inherit from `Runnable.prototype`. 4590 | */ 4591 | 4592 | Test.prototype = new Runnable; 4593 | Test.prototype.constructor = Test; 4594 | 4595 | 4596 | }); // module: test.js 4597 | 4598 | require.register("utils.js", function(module, exports, require){ 4599 | 4600 | /** 4601 | * Module dependencies. 4602 | */ 4603 | 4604 | var fs = require('browser/fs') 4605 | , path = require('browser/path') 4606 | , join = path.join 4607 | , debug = require('browser/debug')('mocha:watch'); 4608 | 4609 | /** 4610 | * Ignored directories. 4611 | */ 4612 | 4613 | var ignore = ['node_modules', '.git']; 4614 | 4615 | /** 4616 | * Escape special characters in the given string of html. 4617 | * 4618 | * @param {String} html 4619 | * @return {String} 4620 | * @api private 4621 | */ 4622 | 4623 | exports.escape = function(html){ 4624 | return String(html) 4625 | .replace(/&/g, '&') 4626 | .replace(/"/g, '"') 4627 | .replace(//g, '>'); 4629 | }; 4630 | 4631 | /** 4632 | * Array#forEach (<=IE8) 4633 | * 4634 | * @param {Array} array 4635 | * @param {Function} fn 4636 | * @param {Object} scope 4637 | * @api private 4638 | */ 4639 | 4640 | exports.forEach = function(arr, fn, scope){ 4641 | for (var i = 0, l = arr.length; i < l; i++) 4642 | fn.call(scope, arr[i], i); 4643 | }; 4644 | 4645 | /** 4646 | * Array#indexOf (<=IE8) 4647 | * 4648 | * @parma {Array} arr 4649 | * @param {Object} obj to find index of 4650 | * @param {Number} start 4651 | * @api private 4652 | */ 4653 | 4654 | exports.indexOf = function(arr, obj, start){ 4655 | for (var i = start || 0, l = arr.length; i < l; i++) { 4656 | if (arr[i] === obj) 4657 | return i; 4658 | } 4659 | return -1; 4660 | }; 4661 | 4662 | /** 4663 | * Array#reduce (<=IE8) 4664 | * 4665 | * @param {Array} array 4666 | * @param {Function} fn 4667 | * @param {Object} initial value 4668 | * @api private 4669 | */ 4670 | 4671 | exports.reduce = function(arr, fn, val){ 4672 | var rval = val; 4673 | 4674 | for (var i = 0, l = arr.length; i < l; i++) { 4675 | rval = fn(rval, arr[i], i, arr); 4676 | } 4677 | 4678 | return rval; 4679 | }; 4680 | 4681 | /** 4682 | * Array#filter (<=IE8) 4683 | * 4684 | * @param {Array} array 4685 | * @param {Function} fn 4686 | * @api private 4687 | */ 4688 | 4689 | exports.filter = function(arr, fn){ 4690 | var ret = []; 4691 | 4692 | for (var i = 0, l = arr.length; i < l; i++) { 4693 | var val = arr[i]; 4694 | if (fn(val, i, arr)) ret.push(val); 4695 | } 4696 | 4697 | return ret; 4698 | }; 4699 | 4700 | /** 4701 | * Object.keys (<=IE8) 4702 | * 4703 | * @param {Object} obj 4704 | * @return {Array} keys 4705 | * @api private 4706 | */ 4707 | 4708 | exports.keys = Object.keys || function(obj) { 4709 | var keys = [] 4710 | , has = Object.prototype.hasOwnProperty // for `window` on <=IE8 4711 | 4712 | for (var key in obj) { 4713 | if (has.call(obj, key)) { 4714 | keys.push(key); 4715 | } 4716 | } 4717 | 4718 | return keys; 4719 | }; 4720 | 4721 | /** 4722 | * Watch the given `files` for changes 4723 | * and invoke `fn(file)` on modification. 4724 | * 4725 | * @param {Array} files 4726 | * @param {Function} fn 4727 | * @api private 4728 | */ 4729 | 4730 | exports.watch = function(files, fn){ 4731 | var options = { interval: 100 }; 4732 | files.forEach(function(file){ 4733 | debug('file %s', file); 4734 | fs.watchFile(file, options, function(curr, prev){ 4735 | if (prev.mtime < curr.mtime) fn(file); 4736 | }); 4737 | }); 4738 | }; 4739 | 4740 | /** 4741 | * Ignored files. 4742 | */ 4743 | 4744 | function ignored(path){ 4745 | return !~ignore.indexOf(path); 4746 | } 4747 | 4748 | /** 4749 | * Lookup files in the given `dir`. 4750 | * 4751 | * @return {Array} 4752 | * @api private 4753 | */ 4754 | 4755 | exports.files = function(dir, ret){ 4756 | ret = ret || []; 4757 | 4758 | fs.readdirSync(dir) 4759 | .filter(ignored) 4760 | .forEach(function(path){ 4761 | path = join(dir, path); 4762 | if (fs.statSync(path).isDirectory()) { 4763 | exports.files(path, ret); 4764 | } else if (path.match(/\.(js|coffee)$/)) { 4765 | ret.push(path); 4766 | } 4767 | }); 4768 | 4769 | return ret; 4770 | }; 4771 | 4772 | /** 4773 | * Compute a slug from the given `str`. 4774 | * 4775 | * @param {String} str 4776 | * @return {String} 4777 | * @api private 4778 | */ 4779 | 4780 | exports.slug = function(str){ 4781 | return str 4782 | .toLowerCase() 4783 | .replace(/ +/g, '-') 4784 | .replace(/[^-\w]/g, ''); 4785 | }; 4786 | 4787 | /** 4788 | * Strip the function definition from `str`, 4789 | * and re-indent for pre whitespace. 4790 | */ 4791 | 4792 | exports.clean = function(str) { 4793 | str = str 4794 | .replace(/^function *\(.*\) *{/, '') 4795 | .replace(/\s+\}$/, ''); 4796 | 4797 | var spaces = str.match(/^\n?( *)/)[1].length 4798 | , re = new RegExp('^ {' + spaces + '}', 'gm'); 4799 | 4800 | str = str.replace(re, ''); 4801 | 4802 | return exports.trim(str); 4803 | }; 4804 | 4805 | /** 4806 | * Escape regular expression characters in `str`. 4807 | * 4808 | * @param {String} str 4809 | * @return {String} 4810 | * @api private 4811 | */ 4812 | 4813 | exports.escapeRegexp = function(str){ 4814 | return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); 4815 | }; 4816 | 4817 | /** 4818 | * Trim the given `str`. 4819 | * 4820 | * @param {String} str 4821 | * @return {String} 4822 | * @api private 4823 | */ 4824 | 4825 | exports.trim = function(str){ 4826 | return str.replace(/^\s+|\s+$/g, ''); 4827 | }; 4828 | 4829 | /** 4830 | * Parse the given `qs`. 4831 | * 4832 | * @param {String} qs 4833 | * @return {Object} 4834 | * @api private 4835 | */ 4836 | 4837 | exports.parseQuery = function(qs){ 4838 | return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ 4839 | var i = pair.indexOf('=') 4840 | , key = pair.slice(0, i) 4841 | , val = pair.slice(++i); 4842 | 4843 | obj[key] = decodeURIComponent(val); 4844 | return obj; 4845 | }, {}); 4846 | }; 4847 | 4848 | /** 4849 | * Highlight the given string of `js`. 4850 | * 4851 | * @param {String} js 4852 | * @return {String} 4853 | * @api private 4854 | */ 4855 | 4856 | function highlight(js) { 4857 | return js 4858 | .replace(//g, '>') 4860 | .replace(/\/\/(.*)/gm, '//$1') 4861 | .replace(/('.*?')/gm, '$1') 4862 | .replace(/(\d+\.\d+)/gm, '$1') 4863 | .replace(/(\d+)/gm, '$1') 4864 | .replace(/\bnew *(\w+)/gm, 'new $1') 4865 | .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') 4866 | } 4867 | 4868 | /** 4869 | * Highlight the contents of tag `name`. 4870 | * 4871 | * @param {String} name 4872 | * @api private 4873 | */ 4874 | 4875 | exports.highlightTags = function(name) { 4876 | var code = document.getElementsByTagName(name); 4877 | for (var i = 0, len = code.length; i < len; ++i) { 4878 | code[i].innerHTML = highlight(code[i].innerHTML); 4879 | } 4880 | }; 4881 | 4882 | }); // module: utils.js 4883 | /** 4884 | * Node shims. 4885 | * 4886 | * These are meant only to allow 4887 | * mocha.js to run untouched, not 4888 | * to allow running node code in 4889 | * the browser. 4890 | */ 4891 | 4892 | process = {}; 4893 | process.exit = function(status){}; 4894 | process.stdout = {}; 4895 | global = window; 4896 | 4897 | /** 4898 | * next tick implementation. 4899 | */ 4900 | 4901 | process.nextTick = (function(){ 4902 | // postMessage behaves badly on IE8 4903 | if (window.ActiveXObject || !window.postMessage) { 4904 | return function(fn){ fn() }; 4905 | } 4906 | 4907 | // based on setZeroTimeout by David Baron 4908 | // - http://dbaron.org/log/20100309-faster-timeouts 4909 | var timeouts = [] 4910 | , name = 'mocha-zero-timeout' 4911 | 4912 | window.addEventListener('message', function(e){ 4913 | if (e.source == window && e.data == name) { 4914 | if (e.stopPropagation) e.stopPropagation(); 4915 | if (timeouts.length) timeouts.shift()(); 4916 | } 4917 | }, true); 4918 | 4919 | return function(fn){ 4920 | timeouts.push(fn); 4921 | window.postMessage(name, '*'); 4922 | } 4923 | })(); 4924 | 4925 | /** 4926 | * Remove uncaughtException listener. 4927 | */ 4928 | 4929 | process.removeListener = function(e){ 4930 | if ('uncaughtException' == e) { 4931 | window.onerror = null; 4932 | } 4933 | }; 4934 | 4935 | /** 4936 | * Implements uncaughtException listener. 4937 | */ 4938 | 4939 | process.on = function(e, fn){ 4940 | if ('uncaughtException' == e) { 4941 | window.onerror = fn; 4942 | } 4943 | }; 4944 | 4945 | // boot 4946 | ;(function(){ 4947 | 4948 | /** 4949 | * Expose mocha. 4950 | */ 4951 | 4952 | var Mocha = window.Mocha = require('mocha'), 4953 | mocha = window.mocha = new Mocha({ reporter: 'html' }); 4954 | 4955 | /** 4956 | * Override ui to ensure that the ui functions are initialized. 4957 | * Normally this would happen in Mocha.prototype.loadFiles. 4958 | */ 4959 | 4960 | mocha.ui = function(ui){ 4961 | Mocha.prototype.ui.call(this, ui); 4962 | this.suite.emit('pre-require', window, null, this); 4963 | return this; 4964 | }; 4965 | 4966 | /** 4967 | * Setup mocha with the given setting options. 4968 | */ 4969 | 4970 | mocha.setup = function(opts){ 4971 | if ('string' == typeof opts) opts = { ui: opts }; 4972 | for (var opt in opts) this[opt](opts[opt]); 4973 | return this; 4974 | }; 4975 | 4976 | /** 4977 | * Run mocha, returning the Runner. 4978 | */ 4979 | 4980 | mocha.run = function(fn){ 4981 | var options = mocha.options; 4982 | mocha.globals('location'); 4983 | 4984 | var query = Mocha.utils.parseQuery(window.location.search || ''); 4985 | if (query.grep) mocha.grep(query.grep); 4986 | if (query.invert) mocha.invert(); 4987 | 4988 | return Mocha.prototype.run.call(mocha, function(){ 4989 | Mocha.utils.highlightTags('code'); 4990 | if (fn) fn(); 4991 | }); 4992 | }; 4993 | })(); 4994 | })(); -------------------------------------------------------------------------------- /test/parse.js: -------------------------------------------------------------------------------- 1 | 2 | var query = require('querystring'); 3 | 4 | describe('.parse(str)', function(){ 5 | describe('when the string is empty', function(){ 6 | it('should return {}', function(){ 7 | expect(query.parse('')).to.eql({}); 8 | }) 9 | }) 10 | 11 | describe('when a non-string is passed', function(){ 12 | it('should return {}', function(){ 13 | expect(query.parse(null)).to.eql({}); 14 | expect(query.parse(0)).to.eql({}); 15 | expect(query.parse()).to.eql({}); 16 | }) 17 | }) 18 | 19 | describe('when a querystring value with spaces encoded as "+" is passed', function(){ 20 | it('should decode them to spaces', function(){ 21 | expect(query.parse('?names=friends+and+family')).to.eql({ names: 'friends and family' }); 22 | }) 23 | }) 24 | 25 | describe('when values are omitted', function(){ 26 | it('should default values to ""', function(){ 27 | var obj = query.parse('name&species'); 28 | expect(obj).to.eql({ name: '', species: '' }); 29 | }) 30 | }) 31 | 32 | describe('when values are present', function(){ 33 | it('should parse map the key / value pairs', function(){ 34 | var obj = query.parse('name=tobi&species=ferret'); 35 | expect(obj).to.eql({ name: 'tobi', species: 'ferret' }); 36 | }) 37 | }) 38 | 39 | describe('when the string includes a question-mark', function(){ 40 | it('should remove the question-mark', function(){ 41 | var obj = query.parse('?name=tobi&species=ferret'); 42 | expect(obj).to.eql({ name: 'tobi', species: 'ferret' }); 43 | }) 44 | }) 45 | 46 | describe('when querystring array is given', function(){ 47 | it('should parse as array', function(){ 48 | var obj = query.parse('items%5B0%5D=1&items%5B1%5D=2&items%5B2%5D=3&key=a'); 49 | expect(obj).to.eql({ items: [1, 2, 3], key: 'a' }); 50 | }) 51 | }) 52 | }) 53 | -------------------------------------------------------------------------------- /test/stringify.js: -------------------------------------------------------------------------------- 1 | 2 | var query = require('querystring'); 3 | 4 | describe('.stringify(obj)', function(){ 5 | describe('when the object is empty', function(){ 6 | it('should return ""', function(){ 7 | expect(query.stringify({})).to.eql(''); 8 | }) 9 | }) 10 | 11 | describe('when a non-object is given', function(){ 12 | it('should return ""', function(){ 13 | expect(query.stringify(null)).to.eql(''); 14 | expect(query.stringify(undefined)).to.eql(''); 15 | expect(query.stringify(0)).to.eql(''); 16 | expect(query.stringify()).to.eql(''); 17 | expect(query.stringify('')).to.eql(''); 18 | }) 19 | }) 20 | 21 | describe('when an object is given', function(){ 22 | it('should return a query-string', function(){ 23 | expect(query.stringify({ name: 'tobi', species: 'ferret' })) 24 | .to.eql('name=tobi&species=ferret'); 25 | }) 26 | 27 | it('should uri encode', function(){ 28 | expect(query.stringify({ 'some thing': 'something else' })) 29 | .to.eql('some%20thing=something%20else') 30 | }) 31 | }) 32 | 33 | describe('when object with arrays is given', function(){ 34 | it('should return a querystring', function(){ 35 | expect(query.stringify({ items: [1, 2, 3], key: 'b' })) 36 | .to.eql('items%5B0%5D=1&items%5B1%5D=2&items%5B2%5D=3&key=b'); 37 | }) 38 | }) 39 | }) 40 | --------------------------------------------------------------------------------