3 * https://github.com/caolan/nodeunit
4 * Copyright (c) 2010 Caolan McMahon
8 * http://www.JSON.org/json2.js
10 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
12 nodeunit = (function(){
14 http://www.JSON.org/json2.js
19 NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
21 See http://www.JSON.org/js.html
24 This code should be minified before deployment.
25 See http://javascript.crockford.com/jsmin.html
27 USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
31 This file creates a global JSON object containing two methods: stringify
34 JSON.stringify(value, replacer, space)
35 value any JavaScript value, usually an object or array.
37 replacer an optional parameter that determines how object
38 values are stringified for objects. It can be a
39 function or an array of strings.
41 space an optional parameter that specifies the indentation
42 of nested structures. If it is omitted, the text will
43 be packed without extra whitespace. If it is a number,
44 it will specify the number of spaces to indent at each
45 level. If it is a string (such as '\t' or ' '),
46 it contains the characters used to indent at each level.
48 This method produces a JSON text from a JavaScript value.
50 When an object value is found, if the object contains a toJSON
51 method, its toJSON method will be called and the result will be
52 stringified. A toJSON method does not serialize: it returns the
53 value represented by the name/value pair that should be serialized,
54 or undefined if nothing should be serialized. The toJSON method
55 will be passed the key associated with the value, and this will be
58 For example, this would serialize Dates as ISO strings.
60 Date.prototype.toJSON = function (key) {
62 // Format integers to have at least two digits.
63 return n < 10 ? '0' + n : n;
66 return this.getUTCFullYear() + '-' +
67 f(this.getUTCMonth() + 1) + '-' +
68 f(this.getUTCDate()) + 'T' +
69 f(this.getUTCHours()) + ':' +
70 f(this.getUTCMinutes()) + ':' +
71 f(this.getUTCSeconds()) + 'Z';
74 You can provide an optional replacer method. It will be passed the
75 key and value of each member, with this bound to the containing
76 object. The value that is returned from your method will be
77 serialized. If your method returns undefined, then the member will
78 be excluded from the serialization.
80 If the replacer parameter is an array of strings, then it will be
81 used to select the members to be serialized. It filters the results
82 such that only members with keys listed in the replacer array are
85 Values that do not have JSON representations, such as undefined or
86 functions, will not be serialized. Such values in objects will be
87 dropped; in arrays they will be replaced with null. You can use
88 a replacer function to replace those with JSON values.
89 JSON.stringify(undefined) returns undefined.
91 The optional space parameter produces a stringification of the
92 value that is filled with line breaks and indentation to make it
95 If the space parameter is a non-empty string, then that string will
96 be used for indentation. If the space parameter is a number, then
97 the indentation will be that many spaces.
101 text = JSON.stringify(['e', {pluribus: 'unum'}]);
102 // text is '["e",{"pluribus":"unum"}]'
105 text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
106 // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
108 text = JSON.stringify([new Date()], function (key, value) {
109 return this[key] instanceof Date ?
110 'Date(' + this[key] + ')' : value;
112 // text is '["Date(---current time---)"]'
115 JSON.parse(text, reviver)
116 This method parses a JSON text to produce an object or array.
117 It can throw a SyntaxError exception.
119 The optional reviver parameter is a function that can filter and
120 transform the results. It receives each of the keys and values,
121 and its return value is used instead of the original value.
122 If it returns what it received, then the structure is not modified.
123 If it returns undefined then the member is deleted.
127 // Parse the text. Values that look like ISO date strings will
128 // be converted to Date objects.
130 myData = JSON.parse(text, function (key, value) {
132 if (typeof value === 'string') {
134 /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
136 return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
143 myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
145 if (typeof value === 'string' &&
146 value.slice(0, 5) === 'Date(' &&
147 value.slice(-1) === ')') {
148 d = new Date(value.slice(5, -1));
157 This is a reference implementation. You are free to copy, modify, or
161 /*jslint evil: true, strict: false, regexp: false */
163 /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
164 call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
165 getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
166 lastIndex, length, parse, prototype, push, replace, slice, stringify,
167 test, toJSON, toString, valueOf
171 // Create a JSON object only if one does not already exist. We create the
172 // methods in a closure to avoid creating global variables.
180 // Format integers to have at least two digits.
181 return n < 10 ? '0' + n : n;
184 if (typeof Date.prototype.toJSON !== 'function') {
186 Date.prototype.toJSON = function (key) {
188 return isFinite(this.valueOf()) ?
189 this.getUTCFullYear() + '-' +
190 f(this.getUTCMonth() + 1) + '-' +
191 f(this.getUTCDate()) + 'T' +
192 f(this.getUTCHours()) + ':' +
193 f(this.getUTCMinutes()) + ':' +
194 f(this.getUTCSeconds()) + 'Z' : null;
197 String.prototype.toJSON =
198 Number.prototype.toJSON =
199 Boolean.prototype.toJSON = function (key) {
200 return this.valueOf();
204 var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
205 escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
208 meta = { // table of character substitutions
220 function quote(string) {
222 // If the string contains no control characters, no quote characters, and no
223 // backslash characters, then we can safely slap some quotes around it.
224 // Otherwise we must also replace the offending characters with safe escape
227 escapable.lastIndex = 0;
228 return escapable.test(string) ?
229 '"' + string.replace(escapable, function (a) {
231 return typeof c === 'string' ? c :
232 '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
238 function str(key, holder) {
240 // Produce a string from holder[key].
242 var i, // The loop counter.
243 k, // The member key.
244 v, // The member value.
250 // If the value has a toJSON method, call it to obtain a replacement value.
252 if (value && typeof value === 'object' &&
253 typeof value.toJSON === 'function') {
254 value = value.toJSON(key);
257 // If we were called with a replacer function, then call the replacer to
258 // obtain a replacement value.
260 if (typeof rep === 'function') {
261 value = rep.call(holder, key, value);
264 // What happens next depends on the value's type.
266 switch (typeof value) {
272 // JSON numbers must be finite. Encode non-finite numbers as null.
274 return isFinite(value) ? String(value) : 'null';
279 // If the value is a boolean or null, convert it to a string. Note:
280 // typeof null does not produce 'null'. The case is included here in
281 // the remote chance that this gets fixed someday.
283 return String(value);
285 // If the type is 'object', we might be dealing with an object or an array or
290 // Due to a specification blunder in ECMAScript, typeof null is 'object',
291 // so watch out for that case.
297 // Make an array to hold the partial results of stringifying this object value.
302 // Is the value an array?
304 if (Object.prototype.toString.apply(value) === '[object Array]') {
306 // The value is an array. Stringify every element. Use null as a placeholder
307 // for non-JSON values.
309 length = value.length;
310 for (i = 0; i < length; i += 1) {
311 partial[i] = str(i, value) || 'null';
314 // Join all of the elements together, separated with commas, and wrap them in
317 v = partial.length === 0 ? '[]' :
319 partial.join(',\n' + gap) + '\n' +
321 '[' + partial.join(',') + ']';
326 // If the replacer is an array, use it to select the members to be stringified.
328 if (rep && typeof rep === 'object') {
330 for (i = 0; i < length; i += 1) {
332 if (typeof k === 'string') {
335 partial.push(quote(k) + (gap ? ': ' : ':') + v);
341 // Otherwise, iterate through all of the keys in the object.
344 if (Object.hasOwnProperty.call(value, k)) {
347 partial.push(quote(k) + (gap ? ': ' : ':') + v);
353 // Join all of the member texts together, separated with commas,
354 // and wrap them in braces.
356 v = partial.length === 0 ? '{}' :
357 gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
358 mind + '}' : '{' + partial.join(',') + '}';
364 // If the JSON object does not yet have a stringify method, give it one.
366 if (typeof JSON.stringify !== 'function') {
367 JSON.stringify = function (value, replacer, space) {
369 // The stringify method takes a value and an optional replacer, and an optional
370 // space parameter, and returns a JSON text. The replacer can be a function
371 // that can replace values, or an array of strings that will select the keys.
372 // A default replacer method can be provided. Use of the space parameter can
373 // produce text that is more easily readable.
379 // If the space parameter is a number, make an indent string containing that
382 if (typeof space === 'number') {
383 for (i = 0; i < space; i += 1) {
387 // If the space parameter is a string, it will be used as the indent string.
389 } else if (typeof space === 'string') {
393 // If there is a replacer, it must be a function or an array.
394 // Otherwise, throw an error.
397 if (replacer && typeof replacer !== 'function' &&
398 (typeof replacer !== 'object' ||
399 typeof replacer.length !== 'number')) {
400 throw new Error('JSON.stringify');
403 // Make a fake root object containing our value under the key of ''.
404 // Return the result of stringifying the value.
406 return str('', {'': value});
411 // If the JSON object does not yet have a parse method, give it one.
413 if (typeof JSON.parse !== 'function') {
414 JSON.parse = function (text, reviver) {
416 // The parse method takes a text and an optional reviver function, and returns
417 // a JavaScript value if the text is a valid JSON text.
421 function walk(holder, key) {
423 // The walk method is used to recursively walk the resulting structure so
424 // that modifications can be made.
426 var k, v, value = holder[key];
427 if (value && typeof value === 'object') {
429 if (Object.hasOwnProperty.call(value, k)) {
431 if (v !== undefined) {
439 return reviver.call(holder, key, value);
443 // Parsing happens in four stages. In the first stage, we replace certain
444 // Unicode characters with escape sequences. JavaScript handles many characters
445 // incorrectly, either silently deleting them, or treating them as line endings.
450 text = text.replace(cx, function (a) {
452 ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
456 // In the second stage, we run the text against regular expressions that look
457 // for non-JSON patterns. We are especially concerned with '()' and 'new'
458 // because they can cause invocation, and '=' because it can cause mutation.
459 // But just to be safe, we want to reject all unexpected forms.
461 // We split the second stage into 4 regexp operations in order to work around
462 // crippling inefficiencies in IE's and Safari's regexp engines. First we
463 // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
464 // replace all simple value tokens with ']' characters. Third, we delete all
465 // open brackets that follow a colon or comma or that begin the text. Finally,
466 // we look to see that the remaining characters are only whitespace or ']' or
467 // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
470 .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
471 .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
472 .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
474 // In the third stage we use the eval function to compile the text into a
475 // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
476 // in JavaScript: it can begin a block or an object literal. We wrap the text
477 // in parens to eliminate the ambiguity.
479 j = eval('(' + text + ')');
481 // In the optional fourth stage, we recursively walk the new structure, passing
482 // each name/value pair to a reviver function for possible transformation.
484 return typeof reviver === 'function' ?
485 walk({'': j}, '') : j;
488 // If the text is not JSON parseable, then a SyntaxError is thrown.
490 throw new SyntaxError('JSON.parse');
494 var assert = this.assert = {};
499 /*global setTimeout: false, console: false */
504 // global on the server, window in the browser
506 previous_async = root.async;
508 if (typeof module !== 'undefined' && module.exports) {
509 module.exports = async;
515 async.noConflict = function () {
516 root.async = previous_async;
520 //// cross-browser compatiblity functions ////
522 var _forEach = function (arr, iterator) {
524 return arr.forEach(iterator);
526 for (var i = 0; i < arr.length; i += 1) {
527 iterator(arr[i], i, arr);
531 var _map = function (arr, iterator) {
533 return arr.map(iterator);
536 _forEach(arr, function (x, i, a) {
537 results.push(iterator(x, i, a));
542 var _reduce = function (arr, iterator, memo) {
544 return arr.reduce(iterator, memo);
546 _forEach(arr, function (x, i, a) {
547 memo = iterator(memo, x, i, a);
552 var _keys = function (obj) {
554 return Object.keys(obj);
558 if (obj.hasOwnProperty(k)) {
565 var _indexOf = function (arr, item) {
567 return arr.indexOf(item);
569 for (var i = 0; i < arr.length; i += 1) {
570 if (arr[i] === item) {
577 //// exported async module functions ////
579 //// nextTick implementation with browser-compatible fallback ////
580 if (typeof process === 'undefined' || !(process.nextTick)) {
581 async.nextTick = function (fn) {
586 async.nextTick = process.nextTick;
589 async.forEach = function (arr, iterator, callback) {
594 _forEach(arr, function (x) {
595 iterator(x, function (err) {
598 callback = function () {};
602 if (completed === arr.length) {
610 async.forEachSeries = function (arr, iterator, callback) {
615 var iterate = function () {
616 iterator(arr[completed], function (err) {
619 callback = function () {};
623 if (completed === arr.length) {
636 var doParallel = function (fn) {
638 var args = Array.prototype.slice.call(arguments);
639 return fn.apply(null, [async.forEach].concat(args));
642 var doSeries = function (fn) {
644 var args = Array.prototype.slice.call(arguments);
645 return fn.apply(null, [async.forEachSeries].concat(args));
650 var _asyncMap = function (eachfn, arr, iterator, callback) {
652 arr = _map(arr, function (x, i) {
653 return {index: i, value: x};
655 eachfn(arr, function (x, callback) {
656 iterator(x.value, function (err, v) {
657 results[x.index] = v;
661 callback(err, results);
664 async.map = doParallel(_asyncMap);
665 async.mapSeries = doSeries(_asyncMap);
668 // reduce only has a series version, as doing reduce in parallel won't
669 // work in many situations.
670 async.reduce = function (arr, memo, iterator, callback) {
671 async.forEachSeries(arr, function (x, callback) {
672 iterator(memo, x, function (err, v) {
681 async.inject = async.reduce;
683 async.foldl = async.reduce;
685 async.reduceRight = function (arr, memo, iterator, callback) {
686 var reversed = _map(arr, function (x) {
689 async.reduce(reversed, memo, iterator, callback);
692 async.foldr = async.reduceRight;
694 var _filter = function (eachfn, arr, iterator, callback) {
696 arr = _map(arr, function (x, i) {
697 return {index: i, value: x};
699 eachfn(arr, function (x, callback) {
700 iterator(x.value, function (v) {
707 callback(_map(results.sort(function (a, b) {
708 return a.index - b.index;
714 async.filter = doParallel(_filter);
715 async.filterSeries = doSeries(_filter);
717 async.select = async.filter;
718 async.selectSeries = async.filterSeries;
720 var _reject = function (eachfn, arr, iterator, callback) {
722 arr = _map(arr, function (x, i) {
723 return {index: i, value: x};
725 eachfn(arr, function (x, callback) {
726 iterator(x.value, function (v) {
733 callback(_map(results.sort(function (a, b) {
734 return a.index - b.index;
740 async.reject = doParallel(_reject);
741 async.rejectSeries = doSeries(_reject);
743 var _detect = function (eachfn, arr, iterator, main_callback) {
744 eachfn(arr, function (x, callback) {
745 iterator(x, function (result) {
757 async.detect = doParallel(_detect);
758 async.detectSeries = doSeries(_detect);
760 async.some = function (arr, iterator, main_callback) {
761 async.forEach(arr, function (x, callback) {
762 iterator(x, function (v) {
765 main_callback = function () {};
770 main_callback(false);
774 async.any = async.some;
776 async.every = function (arr, iterator, main_callback) {
777 async.forEach(arr, function (x, callback) {
778 iterator(x, function (v) {
780 main_callback(false);
781 main_callback = function () {};
790 async.all = async.every;
792 async.sortBy = function (arr, iterator, callback) {
793 async.map(arr, function (x, callback) {
794 iterator(x, function (err, criteria) {
799 callback(null, {value: x, criteria: criteria});
802 }, function (err, results) {
804 return callback(err);
807 var fn = function (left, right) {
808 var a = left.criteria, b = right.criteria;
809 return a < b ? -1 : a > b ? 1 : 0;
811 callback(null, _map(results.sort(fn), function (x) {
818 async.auto = function (tasks, callback) {
819 callback = callback || function () {};
820 var keys = _keys(tasks);
822 return callback(null);
828 var addListener = function (fn) {
829 listeners.unshift(fn);
831 var removeListener = function (fn) {
832 for (var i = 0; i < listeners.length; i += 1) {
833 if (listeners[i] === fn) {
834 listeners.splice(i, 1);
839 var taskComplete = function () {
840 _forEach(listeners, function (fn) {
845 addListener(function () {
846 if (completed.length === keys.length) {
851 _forEach(keys, function (k) {
852 var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k];
853 var taskCallback = function (err) {
856 // stop subsequent errors hitting callback multiple times
857 callback = function () {};
864 var requires = task.slice(0, Math.abs(task.length - 1)) || [];
865 var ready = function () {
866 return _reduce(requires, function (a, x) {
867 return (a && _indexOf(completed, x) !== -1);
871 task[task.length - 1](taskCallback);
874 var listener = function () {
876 removeListener(listener);
877 task[task.length - 1](taskCallback);
880 addListener(listener);
885 async.waterfall = function (tasks, callback) {
889 callback = callback || function () {};
890 var wrapIterator = function (iterator) {
891 return function (err) {
894 callback = function () {};
897 var args = Array.prototype.slice.call(arguments, 1);
898 var next = iterator.next();
900 args.push(wrapIterator(next));
905 async.nextTick(function () {
906 iterator.apply(null, args);
911 wrapIterator(async.iterator(tasks))();
914 async.parallel = function (tasks, callback) {
915 callback = callback || function () {};
916 if (tasks.constructor === Array) {
917 async.map(tasks, function (fn, callback) {
920 var args = Array.prototype.slice.call(arguments, 1);
921 if (args.length <= 1) {
924 callback.call(null, err, args || null);
931 async.forEach(_keys(tasks), function (k, callback) {
932 tasks[k](function (err) {
933 var args = Array.prototype.slice.call(arguments, 1);
934 if (args.length <= 1) {
941 callback(err, results);
946 async.series = function (tasks, callback) {
947 callback = callback || function () {};
948 if (tasks.constructor === Array) {
949 async.mapSeries(tasks, function (fn, callback) {
952 var args = Array.prototype.slice.call(arguments, 1);
953 if (args.length <= 1) {
956 callback.call(null, err, args || null);
963 async.forEachSeries(_keys(tasks), function (k, callback) {
964 tasks[k](function (err) {
965 var args = Array.prototype.slice.call(arguments, 1);
966 if (args.length <= 1) {
973 callback(err, results);
978 async.iterator = function (tasks) {
979 var makeCallback = function (index) {
980 var fn = function () {
982 tasks[index].apply(null, arguments);
986 fn.next = function () {
987 return (index < tasks.length - 1) ? makeCallback(index + 1): null;
991 return makeCallback(0);
994 async.apply = function (fn) {
995 var args = Array.prototype.slice.call(arguments, 1);
998 null, args.concat(Array.prototype.slice.call(arguments))
1003 var _concat = function (eachfn, arr, fn, callback) {
1005 eachfn(arr, function (x, cb) {
1006 fn(x, function (err, y) {
1007 r = r.concat(y || []);
1014 async.concat = doParallel(_concat);
1015 async.concatSeries = doSeries(_concat);
1017 async.whilst = function (test, iterator, callback) {
1019 iterator(function (err) {
1021 return callback(err);
1023 async.whilst(test, iterator, callback);
1031 async.until = function (test, iterator, callback) {
1033 iterator(function (err) {
1035 return callback(err);
1037 async.until(test, iterator, callback);
1045 async.queue = function (worker, concurrency) {
1049 concurrency: concurrency,
1050 push: function (data, callback) {
1051 tasks.push({data: data, callback: callback});
1052 async.nextTick(q.process);
1054 process: function () {
1055 if (workers < q.concurrency && tasks.length) {
1056 var task = tasks.splice(0, 1)[0];
1058 worker(task.data, function () {
1060 if (task.callback) {
1061 task.callback.apply(task, arguments);
1067 length: function () {
1068 return tasks.length;
1074 var _console_fn = function (name) {
1075 return function (fn) {
1076 var args = Array.prototype.slice.call(arguments, 1);
1077 fn.apply(null, args.concat([function (err) {
1078 var args = Array.prototype.slice.call(arguments, 1);
1079 if (typeof console !== 'undefined') {
1081 if (console.error) {
1085 else if (console[name]) {
1086 _forEach(args, function (x) {
1094 async.log = _console_fn('log');
1095 async.dir = _console_fn('dir');
1096 /*async.info = _console_fn('info');
1097 async.warn = _console_fn('warn');
1098 async.error = _console_fn('error');*/
1100 async.memoize = function (fn, hasher) {
1102 hasher = hasher || function (x) {
1105 return function () {
1106 var args = Array.prototype.slice.call(arguments);
1107 var callback = args.pop();
1108 var key = hasher.apply(null, args);
1110 callback.apply(null, memo[key]);
1113 fn.apply(null, args.concat([function () {
1114 memo[key] = arguments;
1115 callback.apply(null, arguments);
1124 * This file is based on the node.js assert module, but with some small
1125 * changes for browser-compatibility
1126 * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS!
1131 * Added for browser compatibility
1134 var _keys = function(obj){
1135 if(Object.keys) return Object.keys(obj);
1136 if (typeof obj != 'object' && typeof obj != 'function') {
1137 throw new TypeError('-');
1141 if(obj.hasOwnProperty(k)) keys.push(k);
1148 // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
1150 // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
1152 // Originally from narwhal.js (http://narwhaljs.org)
1153 // Copyright (c) 2009 Thomas Robinson <280north.com>
1155 // Permission is hereby granted, free of charge, to any person obtaining a copy
1156 // of this software and associated documentation files (the 'Software'), to
1157 // deal in the Software without restriction, including without limitation the
1158 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
1159 // sell copies of the Software, and to permit persons to whom the Software is
1160 // furnished to do so, subject to the following conditions:
1162 // The above copyright notice and this permission notice shall be included in
1163 // all copies or substantial portions of the Software.
1165 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1166 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1167 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1168 // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1169 // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
1170 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1173 var pSlice = Array.prototype.slice;
1175 // 1. The assert module provides functions that throw
1176 // AssertionError's when particular conditions are not met. The
1177 // assert module must conform to the following interface.
1179 var assert = exports;
1181 // 2. The AssertionError is defined in assert.
1182 // new assert.AssertionError({message: message, actual: actual, expected: expected})
1184 assert.AssertionError = function AssertionError (options) {
1185 this.name = "AssertionError";
1186 this.message = options.message;
1187 this.actual = options.actual;
1188 this.expected = options.expected;
1189 this.operator = options.operator;
1190 var stackStartFunction = options.stackStartFunction || fail;
1192 if (Error.captureStackTrace) {
1193 Error.captureStackTrace(this, stackStartFunction);
1196 // code from util.inherits in node
1197 assert.AssertionError.super_ = Error;
1200 // EDITED FOR BROWSER COMPATIBILITY: replaced Object.create call
1201 // TODO: test what effect this may have
1202 var ctor = function () { this.constructor = assert.AssertionError; };
1203 ctor.prototype = Error.prototype;
1204 assert.AssertionError.prototype = new ctor();
1207 assert.AssertionError.prototype.toString = function() {
1209 return [this.name+":", this.message].join(' ');
1211 return [ this.name+":"
1212 , JSON.stringify(this.expected )
1214 , JSON.stringify(this.actual)
1219 // assert.AssertionError instanceof Error
1221 assert.AssertionError.__proto__ = Error.prototype;
1223 // At present only the three keys mentioned above are used and
1224 // understood by the spec. Implementations or sub modules can pass
1225 // other keys to the AssertionError's constructor - they will be
1228 // 3. All of the following functions must throw an AssertionError
1229 // when a corresponding condition is not met, with a message that
1230 // may be undefined if not provided. All assertion methods provide
1231 // both the actual and expected values to the assertion error for
1232 // display purposes.
1234 function fail(actual, expected, message, operator, stackStartFunction) {
1235 throw new assert.AssertionError({
1240 stackStartFunction: stackStartFunction
1244 // EXTENSION! allows for well behaved errors defined elsewhere.
1247 // 4. Pure assertion tests whether a value is truthy, as determined
1249 // assert.ok(guard, message_opt);
1250 // This statement is equivalent to assert.equal(true, guard,
1251 // message_opt);. To test strictly for the value true, use
1252 // assert.strictEqual(true, guard, message_opt);.
1254 assert.ok = function ok(value, message) {
1255 if (!!!value) fail(value, true, message, "==", assert.ok);
1258 // 5. The equality assertion tests shallow, coercive equality with
1260 // assert.equal(actual, expected, message_opt);
1262 assert.equal = function equal(actual, expected, message) {
1263 if (actual != expected) fail(actual, expected, message, "==", assert.equal);
1266 // 6. The non-equality assertion tests for whether two objects are not equal
1267 // with != assert.notEqual(actual, expected, message_opt);
1269 assert.notEqual = function notEqual(actual, expected, message) {
1270 if (actual == expected) {
1271 fail(actual, expected, message, "!=", assert.notEqual);
1275 // 7. The equivalence assertion tests a deep equality relation.
1276 // assert.deepEqual(actual, expected, message_opt);
1278 assert.deepEqual = function deepEqual(actual, expected, message) {
1279 if (!_deepEqual(actual, expected)) {
1280 fail(actual, expected, message, "deepEqual", assert.deepEqual);
1284 function _deepEqual(actual, expected) {
1285 // 7.1. All identical values are equivalent, as determined by ===.
1286 if (actual === expected) {
1288 // 7.2. If the expected value is a Date object, the actual value is
1289 // equivalent if it is also a Date object that refers to the same time.
1290 } else if (actual instanceof Date && expected instanceof Date) {
1291 return actual.getTime() === expected.getTime();
1293 // 7.3. Other pairs that do not both pass typeof value == "object",
1294 // equivalence is determined by ==.
1295 } else if (typeof actual != 'object' && typeof expected != 'object') {
1296 return actual == expected;
1298 // 7.4. For all other Object pairs, including Array objects, equivalence is
1299 // determined by having the same number of owned properties (as verified
1300 // with Object.prototype.hasOwnProperty.call), the same set of keys
1301 // (although not necessarily the same order), equivalent values for every
1302 // corresponding key, and an identical "prototype" property. Note: this
1303 // accounts for both named and indexed properties on Arrays.
1305 return objEquiv(actual, expected);
1309 function isUndefinedOrNull (value) {
1310 return value === null || value === undefined;
1313 function isArguments (object) {
1314 return Object.prototype.toString.call(object) == '[object Arguments]';
1317 function objEquiv (a, b) {
1318 if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
1320 // an identical "prototype" property.
1321 if (a.prototype !== b.prototype) return false;
1322 //~~~I've managed to break Object.keys through screwy arguments passing.
1323 // Converting to array solves the problem.
1324 if (isArguments(a)) {
1325 if (!isArguments(b)) {
1330 return _deepEqual(a, b);
1336 } catch (e) {//happens when one is a string literal and the other isn't
1339 // having the same number of owned properties (keys incorporates hasOwnProperty)
1340 if (ka.length != kb.length)
1342 //the same set of keys (although not necessarily the same order),
1346 for (i = ka.length - 1; i >= 0; i--) {
1350 //equivalent values for every corresponding key, and
1351 //~~~possibly expensive deep test
1352 for (i = ka.length - 1; i >= 0; i--) {
1354 if (!_deepEqual(a[key], b[key] ))
1360 // 8. The non-equivalence assertion tests for any deep inequality.
1361 // assert.notDeepEqual(actual, expected, message_opt);
1363 assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
1364 if (_deepEqual(actual, expected)) {
1365 fail(actual, expected, message, "notDeepEqual", assert.notDeepEqual);
1369 // 9. The strict equality assertion tests strict equality, as determined by ===.
1370 // assert.strictEqual(actual, expected, message_opt);
1372 assert.strictEqual = function strictEqual(actual, expected, message) {
1373 if (actual !== expected) {
1374 fail(actual, expected, message, "===", assert.strictEqual);
1378 // 10. The strict non-equality assertion tests for strict inequality, as determined by !==.
1379 // assert.notStrictEqual(actual, expected, message_opt);
1381 assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
1382 if (actual === expected) {
1383 fail(actual, expected, message, "!==", assert.notStrictEqual);
1387 function _throws (shouldThrow, block, err, message) {
1388 var exception = null,
1392 message = message || "";
1394 //handle optional arguments
1395 if (arguments.length == 3) {
1396 if (typeof(err) == "string") {
1398 typematters = false;
1400 } else if (arguments.length == 2) {
1401 typematters = false;
1411 if (shouldThrow && !threw) {
1412 fail( "Missing expected exception"
1413 + (err && err.name ? " ("+err.name+")." : '.')
1414 + (message ? " " + message : "")
1417 if (!shouldThrow && threw && typematters && exception instanceof err) {
1418 fail( "Got unwanted exception"
1419 + (err && err.name ? " ("+err.name+")." : '.')
1420 + (message ? " " + message : "")
1423 if ((shouldThrow && threw && typematters && !(exception instanceof err)) ||
1424 (!shouldThrow && threw)) {
1429 // 11. Expected to throw an error:
1430 // assert.throws(block, Error_opt, message_opt);
1432 assert.throws = function(block, /*optional*/error, /*optional*/message) {
1433 _throws.apply(this, [true].concat(pSlice.call(arguments)));
1436 // EXTENSION! This is annoying to write outside this module.
1437 assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
1438 _throws.apply(this, [false].concat(pSlice.call(arguments)));
1441 assert.ifError = function (err) { if (err) {throw err;}};
1446 * Copyright (c) 2010 Caolan McMahon
1449 * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS!
1450 * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build.
1451 * Only code on that line will be removed, its mostly to avoid requiring code
1452 * that is node specific
1456 * Module dependencies
1459 //var assert = require('./assert'), //@REMOVE_LINE_FOR_BROWSER
1460 // async = require('../deps/async'); //@REMOVE_LINE_FOR_BROWSER
1464 * Creates assertion objects representing the result of an assert call.
1465 * Accepts an object or AssertionError as its argument.
1467 * @param {object} obj
1471 exports.assertion = function (obj) {
1473 method: obj.method || '',
1474 message: obj.message || (obj.error && obj.error.message) || '',
1476 passed: function () {
1479 failed: function () {
1480 return Boolean(this.error);
1486 * Creates an assertion list object representing a group of assertions.
1487 * Accepts an array of assertion objects.
1489 * @param {Array} arr
1490 * @param {Number} duration
1494 exports.assertionList = function (arr, duration) {
1495 var that = arr || [];
1496 that.failures = function () {
1498 for (var i = 0; i < this.length; i += 1) {
1499 if (this[i].failed()) {
1505 that.passes = function () {
1506 return that.length - that.failures();
1508 that.duration = duration || 0;
1513 * Create a wrapper function for assert module methods. Executes a callback
1514 * after the it's complete with an assertion object representing the result.
1516 * @param {Function} callback
1520 var assertWrapper = function (callback) {
1521 return function (new_method, assert_method, arity) {
1522 return function () {
1523 var message = arguments[arity - 1];
1524 var a = exports.assertion({method: new_method, message: message});
1526 assert[assert_method].apply(null, arguments);
1537 * Creates the 'test' object that gets passed to every test function.
1538 * Accepts the name of the test function as its first argument, followed by
1539 * the start time in ms, the options object and a callback function.
1541 * @param {String} name
1542 * @param {Number} start
1543 * @param {Object} options
1544 * @param {Function} callback
1548 exports.test = function (name, start, options, callback) {
1552 var wrapAssert = assertWrapper(function (a) {
1555 async.nextTick(function () {
1562 done: function (err) {
1563 if (expecting !== undefined && expecting !== a_list.length) {
1565 'Expected ' + expecting + ' assertions, ' +
1566 a_list.length + ' ran'
1568 var a1 = exports.assertion({method: 'expect', error: e});
1571 async.nextTick(function () {
1577 var a2 = exports.assertion({error: err});
1580 async.nextTick(function () {
1585 var end = new Date().getTime();
1586 async.nextTick(function () {
1587 var assertion_list = exports.assertionList(a_list, end - start);
1588 options.testDone(name, assertion_list);
1589 callback(null, a_list);
1592 ok: wrapAssert('ok', 'ok', 2),
1593 same: wrapAssert('same', 'deepEqual', 3),
1594 equals: wrapAssert('equals', 'equal', 3),
1595 expect: function (num) {
1598 _assertion_list: a_list
1600 // add all functions from the assert module
1601 for (var k in assert) {
1602 if (assert.hasOwnProperty(k)) {
1603 test[k] = wrapAssert(k, k, assert[k].length);
1610 * Ensures an options object has all callbacks, adding empty callback functions
1611 * if any are missing.
1613 * @param {Object} opt
1618 exports.options = function (opt) {
1619 var optionalCallback = function (name) {
1620 opt[name] = opt[name] || function () {};
1623 optionalCallback('moduleStart');
1624 optionalCallback('moduleDone');
1625 optionalCallback('testStart');
1626 optionalCallback('testDone');
1627 //optionalCallback('log');
1629 // 'done' callback is not optional.
1637 * Copyright (c) 2010 Caolan McMahon
1640 * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS!
1641 * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build.
1642 * Only code on that line will be removed, its mostly to avoid requiring code
1643 * that is node specific
1647 * Module dependencies
1650 //var async = require('../deps/async'), //@REMOVE_LINE_FOR_BROWSER
1651 // types = require('./types'); //@REMOVE_LINE_FOR_BROWSER
1655 * Added for browser compatibility
1658 var _keys = function (obj) {
1660 return Object.keys(obj);
1663 for (var k in obj) {
1664 if (obj.hasOwnProperty(k)) {
1672 var _copy = function (obj) {
1674 var keys = _keys(obj);
1675 for (var i = 0; i < keys.length; i += 1) {
1676 nobj[keys[i]] = obj[keys[i]];
1683 * Runs a test function (fn) from a loaded module. After the test function
1684 * calls test.done(), the callback is executed with an assertionList as its
1687 * @param {String} name
1688 * @param {Function} fn
1689 * @param {Object} opt
1690 * @param {Function} callback
1694 exports.runTest = function (name, fn, opt, callback) {
1695 var options = types.options(opt);
1697 options.testStart(name);
1698 var start = new Date().getTime();
1699 var test = types.test(name, start, options, callback);
1710 * Takes an object containing test functions or other test suites as properties
1711 * and runs each in series. After all tests have completed, the callback is
1712 * called with a list of all assertions as the second argument.
1714 * If a name is passed to this function it is prepended to all test and suite
1715 * names that run within it.
1717 * @param {String} name
1718 * @param {Object} suite
1719 * @param {Object} opt
1720 * @param {Function} callback
1724 exports.runSuite = function (name, suite, opt, callback) {
1725 var keys = _keys(suite);
1727 async.concatSeries(keys, function (k, cb) {
1728 var prop = suite[k], _name;
1730 _name = name ? [].concat(name, k) : [k];
1732 _name.toString = function () {
1733 // fallback for old one
1734 return this.join(' - ');
1737 if (typeof prop === 'function') {
1738 var in_name = false;
1739 for (var i = 0; i < _name.length; i += 1) {
1740 if (_name[i] === opt.testspec) {
1744 if (!opt.testspec || in_name) {
1745 if (opt.moduleStart) {
1748 exports.runTest(_name, suite[k], opt, cb);
1755 exports.runSuite(_name, suite[k], opt, cb);
1761 * Run each exported test function or test suite from a loaded module.
1763 * @param {String} name
1764 * @param {Object} mod
1765 * @param {Object} opt
1766 * @param {Function} callback
1770 exports.runModule = function (name, mod, opt, callback) {
1771 var options = _copy(types.options(opt));
1774 var _moduleStart = options.moduleStart;
1775 function run_once() {
1781 options.moduleStart = run_once;
1783 var start = new Date().getTime();
1785 exports.runSuite(null, mod, options, function (err, a_list) {
1786 var end = new Date().getTime();
1787 var assertion_list = types.assertionList(a_list, end - start);
1788 options.moduleDone(name, assertion_list);
1789 callback(null, a_list);
1794 * Treats an object literal as a list of modules keyed by name. Runs each
1795 * module and finished with calling 'done'. You can think of this as a browser
1796 * safe alternative to runFiles in the nodeunit module.
1798 * @param {Object} modules
1799 * @param {Object} opt
1803 // TODO: add proper unit tests for this function
1804 exports.runModules = function (modules, opt) {
1805 var all_assertions = [];
1806 var options = types.options(opt);
1807 var start = new Date().getTime();
1809 async.concatSeries(_keys(modules), function (k, cb) {
1810 exports.runModule(k, modules[k], options, cb);
1812 function (err, all_assertions) {
1813 var end = new Date().getTime();
1814 options.done(types.assertionList(all_assertions, end - start));
1820 * Wraps a test function with setUp and tearDown functions.
1823 * @param {Function} setUp
1824 * @param {Function} tearDown
1825 * @param {Function} fn
1829 var wrapTest = function (setUp, tearDown, fn) {
1830 return function (test) {
1833 var done = test.done;
1834 test.done = function (err) {
1836 tearDown.call(context, function (err2) {
1838 test._assertion_list.push(
1839 types.assertion({error: err})
1852 setUp.call(context, function (err) {
1854 return test.done(err);
1856 fn.call(context, test);
1860 fn.call(context, test);
1867 * Wraps a group of tests with setUp and tearDown functions.
1870 * @param {Function} setUp
1871 * @param {Function} tearDown
1872 * @param {Object} group
1876 var wrapGroup = function (setUp, tearDown, group) {
1878 var keys = _keys(group);
1879 for (var i = 0; i < keys.length; i += 1) {
1881 if (typeof group[k] === 'function') {
1882 tests[k] = wrapTest(setUp, tearDown, group[k]);
1884 else if (typeof group[k] === 'object') {
1885 tests[k] = wrapGroup(setUp, tearDown, group[k]);
1893 * Utility for wrapping a suite of test functions with setUp and tearDown
1896 * @param {Object} suite
1901 exports.testCase = function (suite) {
1902 var setUp = suite.setUp;
1903 var tearDown = suite.tearDown;
1905 delete suite.tearDown;
1906 return wrapGroup(setUp, tearDown, suite);
1912 * Copyright (c) 2010 Caolan McMahon
1915 * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS!
1916 * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build.
1917 * Only code on that line will be removed, its mostly to avoid requiring code
1918 * that is node specific
1923 * NOTE: this test runner is not listed in index.js because it cannot be
1924 * used with the command-line tool, only inside the browser.
1929 * Reporter info string
1932 exports.info = "Browser-based test reporter";
1936 * Run all tests within each module, reporting the results
1938 * @param {Array} files
1942 exports.run = function (modules, options) {
1943 var start = new Date().getTime();
1945 function setText(el, txt) {
1946 if ('innerText' in el) {
1949 else if ('textContent' in el){
1950 el.textContent = txt;
1954 function getOrCreate(tag, id) {
1955 var el = document.getElementById(id);
1957 el = document.createElement(tag);
1959 document.body.appendChild(el);
1964 var header = getOrCreate('h1', 'nodeunit-header');
1965 var banner = getOrCreate('h2', 'nodeunit-banner');
1966 var userAgent = getOrCreate('h2', 'nodeunit-userAgent');
1967 var tests = getOrCreate('ol', 'nodeunit-tests');
1968 var result = getOrCreate('p', 'nodeunit-testresult');
1970 setText(userAgent, navigator.userAgent);
1972 nodeunit.runModules(modules, {
1973 moduleStart: function (name) {
1974 /*var mheading = document.createElement('h2');
1975 mheading.innerText = name;
1976 results.appendChild(mheading);
1977 module = document.createElement('ol');
1978 results.appendChild(module);*/
1980 testDone: function (name, assertions) {
1981 var test = document.createElement('li');
1982 var strong = document.createElement('strong');
1983 strong.innerHTML = name + ' <b style="color: black;">(' +
1984 '<b class="fail">' + assertions.failures() + '</b>, ' +
1985 '<b class="pass">' + assertions.passes() + '</b>, ' +
1988 test.className = assertions.failures() ? 'fail': 'pass';
1989 test.appendChild(strong);
1991 var aList = document.createElement('ol');
1992 aList.style.display = 'none';
1993 test.onclick = function () {
1994 var d = aList.style.display;
1995 aList.style.display = (d == 'none') ? 'block': 'none';
1997 for (var i=0; i<assertions.length; i++) {
1998 var li = document.createElement('li');
1999 var a = assertions[i];
2001 li.innerHTML = (a.message || a.method || 'no message') +
2002 '<pre>' + (a.error.stack || a.error) + '</pre>';
2003 li.className = 'fail';
2006 li.innerHTML = a.message || a.method || 'no message';
2007 li.className = 'pass';
2009 aList.appendChild(li);
2011 test.appendChild(aList);
2012 tests.appendChild(test);
2014 done: function (assertions) {
2015 var end = new Date().getTime();
2016 var duration = end - start;
2018 var failures = assertions.failures();
2019 banner.className = failures ? 'fail': 'pass';
2021 result.innerHTML = 'Tests completed in ' + duration +
2022 ' milliseconds.<br/><span class="passed">' +
2023 assertions.passes() + '</span> assertions of ' +
2024 '<span class="all">' + assertions.length + '<span> passed, ' +
2025 assertions.failures() + ' failed.';
2031 nodeunit.assert = assert;
2032 nodeunit.reporter = reporter;
2033 nodeunit.run = reporter.run;
2034 return nodeunit; })();