2 * Sinon.JS 1.10.0, 2014/05/19
4 * @author Christian Johansen (christian@cjohansen.no)
5 * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS
9 * Copyright (c) 2010-2014, Christian Johansen, christian@cjohansen.no
10 * All rights reserved.
12 * Redistribution and use in source and binary forms, with or without modification,
13 * are permitted provided that the following conditions are met:
15 * * Redistributions of source code must retain the above copyright notice,
16 * this list of conditions and the following disclaimer.
17 * * Redistributions in binary form must reproduce the above copyright notice,
18 * this list of conditions and the following disclaimer in the documentation
19 * and/or other materials provided with the distribution.
20 * * Neither the name of Christian Johansen nor the names of his contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 this.sinon = (function () {
38 function define(mod, deps, fn) { if (mod == "samsam") { samsam = deps(); } else if (typeof fn === "function") { formatio = fn(samsam); } }
40 ((typeof define === "function" && define.amd && function (m) { define("samsam", m); }) ||
41 (typeof module === "object" &&
42 function (m) { module.exports = m(); }) || // Node
43 function (m) { this.samsam = m(); } // Browser globals
45 var o = Object.prototype;
46 var div = typeof document !== "undefined" && document.createElement("div");
48 function isNaN(value) {
49 // Unlike global isNaN, this avoids type coercion
50 // typeof check avoids IE host object issues, hat tip to
52 var val = value; // JsLint thinks value !== value is "weird"
53 return typeof value === "number" && value !== val;
56 function getClass(value) {
57 // Returns the internal [[Class]] by calling Object.prototype.toString
58 // with the provided value as this. Return value is a string, naming the
59 // internal class, e.g. "Array"
60 return o.toString.call(value).split(/[ \]]/)[1];
64 * @name samsam.isArguments
65 * @param Object object
67 * Returns ``true`` if ``object`` is an ``arguments`` object,
68 * ``false`` otherwise.
70 function isArguments(object) {
71 if (typeof object !== "object" || typeof object.length !== "number" ||
72 getClass(object) === "Array") {
75 if (typeof object.callee == "function") { return true; }
77 object[object.length] = 6;
78 delete object[object.length];
86 * @name samsam.isElement
87 * @param Object object
89 * Returns ``true`` if ``object`` is a DOM element node. Unlike
90 * Underscore.js/lodash, this function will return ``false`` if ``object``
91 * is an *element-like* object, i.e. a regular object with a ``nodeType``
92 * property that holds the value ``1``.
94 function isElement(object) {
95 if (!object || object.nodeType !== 1 || !div) { return false; }
97 object.appendChild(div);
98 object.removeChild(div);
107 * @param Object object
109 * Return an array of own property names.
111 function keys(object) {
113 for (prop in object) {
114 if (o.hasOwnProperty.call(object, prop)) { ks.push(prop); }
120 * @name samsam.isDate
121 * @param Object value
123 * Returns true if the object is a ``Date``, or *date-like*. Duck typing
124 * of date objects work by checking that the object has a ``getTime``
125 * function whose return value equals the return value from the object's
128 function isDate(value) {
129 return typeof value.getTime == "function" &&
130 value.getTime() == value.valueOf();
134 * @name samsam.isNegZero
135 * @param Object value
137 * Returns ``true`` if ``value`` is ``-0``.
139 function isNegZero(value) {
140 return value === 0 && 1 / value === -Infinity;
148 * Returns ``true`` if two objects are strictly equal. Compared to
149 * ``===`` there are two exceptions:
151 * - NaN is considered equal to NaN
152 * - -0 and +0 are not considered equal
154 function identical(obj1, obj2) {
155 if (obj1 === obj2 || (isNaN(obj1) && isNaN(obj2))) {
156 return obj1 !== 0 || isNegZero(obj1) === isNegZero(obj2);
162 * @name samsam.deepEqual
166 * Deep equal comparison. Two values are "deep equal" if:
168 * - They are equal, according to samsam.identical
169 * - They are both date objects representing the same time
170 * - They are both arrays containing elements that are all deepEqual
171 * - They are objects with the same set of properties, and each property
172 * in ``obj1`` is deepEqual to the corresponding property in ``obj2``
174 * Supports cyclic objects.
176 function deepEqualCyclic(obj1, obj2) {
178 // used for cyclic comparison
179 // contain already visited objects
182 // contain pathes (position in the object structure)
183 // of the already visited objects
184 // indexes same as in objects arrays
187 // contains combinations of already compared objects
188 // in the manner: { "$1['ref']$2['ref']": true }
192 * used to check, if the value of a property is an object
193 * (cyclic logic is only needed for objects)
194 * only needed for cyclic logic
196 function isObject(value) {
198 if (typeof value === 'object' && value !== null &&
199 !(value instanceof Boolean) &&
200 !(value instanceof Date) &&
201 !(value instanceof Number) &&
202 !(value instanceof RegExp) &&
203 !(value instanceof String)) {
212 * returns the index of the given object in the
213 * given objects array, -1 if not contained
214 * only needed for cyclic logic
216 function getIndex(objects, obj) {
219 for (i = 0; i < objects.length; i++) {
220 if (objects[i] === obj) {
228 // does the recursion for the deep equal check
229 return (function deepEqual(obj1, obj2, path1, path2) {
230 var type1 = typeof obj1;
231 var type2 = typeof obj2;
233 // == null also matches undefined
235 isNaN(obj1) || isNaN(obj2) ||
236 obj1 == null || obj2 == null ||
237 type1 !== "object" || type2 !== "object") {
239 return identical(obj1, obj2);
242 // Elements are only equal if identical(expected, actual)
243 if (isElement(obj1) || isElement(obj2)) { return false; }
245 var isDate1 = isDate(obj1), isDate2 = isDate(obj2);
246 if (isDate1 || isDate2) {
247 if (!isDate1 || !isDate2 || obj1.getTime() !== obj2.getTime()) {
252 if (obj1 instanceof RegExp && obj2 instanceof RegExp) {
253 if (obj1.toString() !== obj2.toString()) { return false; }
256 var class1 = getClass(obj1);
257 var class2 = getClass(obj2);
258 var keys1 = keys(obj1);
259 var keys2 = keys(obj2);
261 if (isArguments(obj1) || isArguments(obj2)) {
262 if (obj1.length !== obj2.length) { return false; }
264 if (type1 !== type2 || class1 !== class2 ||
265 keys1.length !== keys2.length) {
271 // following vars are used for the cyclic logic
273 isObject1, isObject2,
277 for (i = 0, l = keys1.length; i < l; i++) {
279 if (!o.hasOwnProperty.call(obj2, key)) {
283 // Start of the cyclic logic
288 isObject1 = isObject(value1);
289 isObject2 = isObject(value2);
291 // determine, if the objects were already visited
292 // (it's faster to check for isObject first, than to
293 // get -1 from getIndex for non objects)
294 index1 = isObject1 ? getIndex(objects1, value1) : -1;
295 index2 = isObject2 ? getIndex(objects2, value2) : -1;
297 // determine the new pathes of the objects
298 // - for non cyclic objects the current path will be extended
299 // by current property name
300 // - for cyclic objects the stored path is taken
301 newPath1 = index1 !== -1
303 : path1 + '[' + JSON.stringify(key) + ']';
304 newPath2 = index2 !== -1
306 : path2 + '[' + JSON.stringify(key) + ']';
308 // stop recursion if current objects are already compared
309 if (compared[newPath1 + newPath2]) {
313 // remember the current objects and their pathes
314 if (index1 === -1 && isObject1) {
315 objects1.push(value1);
316 paths1.push(newPath1);
318 if (index2 === -1 && isObject2) {
319 objects2.push(value2);
320 paths2.push(newPath2);
323 // remember that the current objects are already compared
324 if (isObject1 && isObject2) {
325 compared[newPath1 + newPath2] = true;
328 // End of cyclic logic
330 // neither value1 nor value2 is a cycle
331 // continue with next level
332 if (!deepEqual(value1, value2, newPath1, newPath2)) {
339 }(obj1, obj2, '$1', '$2'));
344 function arrayContains(array, subset) {
345 if (subset.length === 0) { return true; }
347 for (i = 0, l = array.length; i < l; ++i) {
348 if (match(array[i], subset[0])) {
349 for (j = 0, k = subset.length; j < k; ++j) {
350 if (!match(array[i + j], subset[j])) { return false; }
360 * @param Object object
361 * @param Object matcher
363 * Compare arbitrary value ``object`` with matcher.
365 match = function match(object, matcher) {
366 if (matcher && typeof matcher.test === "function") {
367 return matcher.test(object);
370 if (typeof matcher === "function") {
371 return matcher(object) === true;
374 if (typeof matcher === "string") {
375 matcher = matcher.toLowerCase();
376 var notNull = typeof object === "string" || !!object;
378 (String(object)).toLowerCase().indexOf(matcher) >= 0;
381 if (typeof matcher === "number") {
382 return matcher === object;
385 if (typeof matcher === "boolean") {
386 return matcher === object;
389 if (getClass(object) === "Array" && getClass(matcher) === "Array") {
390 return arrayContains(object, matcher);
393 if (matcher && typeof matcher === "object") {
395 for (prop in matcher) {
396 if (!match(object[prop], matcher[prop])) {
403 throw new Error("Matcher was not a string, a number, a " +
404 "function, a boolean or an object");
408 isArguments: isArguments,
409 isElement: isElement,
411 isNegZero: isNegZero,
412 identical: identical,
413 deepEqual: deepEqualCyclic,
418 ((typeof define === "function" && define.amd && function (m) {
419 define("formatio", ["samsam"], m);
420 }) || (typeof module === "object" && function (m) {
421 module.exports = m(require("samsam"));
422 }) || function (m) { this.formatio = m(this.samsam); }
423 )(function (samsam) {
426 excludeConstructors: ["Object", /^.$/],
430 var hasOwn = Object.prototype.hasOwnProperty;
432 var specialObjects = [];
433 if (typeof global !== "undefined") {
434 specialObjects.push({ object: global, value: "[object global]" });
436 if (typeof document !== "undefined") {
437 specialObjects.push({
439 value: "[object HTMLDocument]"
442 if (typeof window !== "undefined") {
443 specialObjects.push({ object: window, value: "[object Window]" });
446 function functionName(func) {
447 if (!func) { return ""; }
448 if (func.displayName) { return func.displayName; }
449 if (func.name) { return func.name; }
450 var matches = func.toString().match(/function\s+([^\(]+)/m);
451 return (matches && matches[1]) || "";
454 function constructorName(f, object) {
455 var name = functionName(object && object.constructor);
456 var excludes = f.excludeConstructors ||
457 formatio.excludeConstructors || [];
460 for (i = 0, l = excludes.length; i < l; ++i) {
461 if (typeof excludes[i] === "string" && excludes[i] === name) {
463 } else if (excludes[i].test && excludes[i].test(name)) {
471 function isCircular(object, objects) {
472 if (typeof object !== "object") { return false; }
474 for (i = 0, l = objects.length; i < l; ++i) {
475 if (objects[i] === object) { return true; }
480 function ascii(f, object, processed, indent) {
481 if (typeof object === "string") {
482 var qs = f.quoteStrings;
483 var quote = typeof qs !== "boolean" || qs;
484 return processed || quote ? '"' + object + '"' : object;
487 if (typeof object === "function" && !(object instanceof RegExp)) {
488 return ascii.func(object);
491 processed = processed || [];
493 if (isCircular(object, processed)) { return "[Circular]"; }
495 if (Object.prototype.toString.call(object) === "[object Array]") {
496 return ascii.array.call(f, object, processed);
499 if (!object) { return String((1/object) === -Infinity ? "-0" : object); }
500 if (samsam.isElement(object)) { return ascii.element(object); }
502 if (typeof object.toString === "function" &&
503 object.toString !== Object.prototype.toString) {
504 return object.toString();
508 for (i = 0, l = specialObjects.length; i < l; i++) {
509 if (object === specialObjects[i].object) {
510 return specialObjects[i].value;
514 return ascii.object.call(f, object, processed, indent);
517 ascii.func = function (func) {
518 return "function " + functionName(func) + "() {}";
521 ascii.array = function (array, processed) {
522 processed = processed || [];
523 processed.push(array);
524 var i, l, pieces = [];
525 for (i = 0, l = array.length; i < l; ++i) {
526 pieces.push(ascii(this, array[i], processed));
528 return "[" + pieces.join(", ") + "]";
531 ascii.object = function (object, processed, indent) {
532 processed = processed || [];
533 processed.push(object);
534 indent = indent || 0;
535 var pieces = [], properties = samsam.keys(object).sort();
537 var prop, str, obj, i, l;
539 for (i = 0, l = properties.length; i < l; ++i) {
540 prop = properties[i];
543 if (isCircular(obj, processed)) {
546 str = ascii(this, obj, processed, indent + 2);
549 str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str;
550 length += str.length;
554 var cons = constructorName(this, object);
555 var prefix = cons ? "[" + cons + "] " : "";
557 for (i = 0, l = indent; i < l; ++i) { is += " "; }
559 if (length + indent > 80) {
560 return prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" +
563 return prefix + "{ " + pieces.join(", ") + " }";
566 ascii.element = function (element) {
567 var tagName = element.tagName.toLowerCase();
568 var attrs = element.attributes, attr, pairs = [], attrName, i, l, val;
570 for (i = 0, l = attrs.length; i < l; ++i) {
571 attr = attrs.item(i);
572 attrName = attr.nodeName.toLowerCase().replace("html:", "");
573 val = attr.nodeValue;
574 if (attrName !== "contenteditable" || val !== "inherit") {
575 if (!!val) { pairs.push(attrName + "=\"" + val + "\""); }
579 var formatted = "<" + tagName + (pairs.length > 0 ? " " : "");
580 var content = element.innerHTML;
582 if (content.length > 20) {
583 content = content.substr(0, 20) + "[...]";
586 var res = formatted + pairs.join(" ") + ">" + content +
587 "</" + tagName + ">";
589 return res.replace(/ contentEditable="inherit"/, "");
592 function Formatio(options) {
593 for (var opt in options) {
594 this[opt] = options[opt];
598 Formatio.prototype = {
599 functionName: functionName,
601 configure: function (options) {
602 return new Formatio(options);
605 constructorName: function (object) {
606 return constructorName(this, object);
609 ascii: function (object, processed, indent) {
610 return ascii(this, object, processed, indent);
614 return Formatio.prototype;
616 /*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/
617 /*global module, require, __dirname, document*/
619 * Sinon core utilities. For internal use only.
621 * @author Christian Johansen (christian@cjohansen.no)
624 * Copyright (c) 2010-2013 Christian Johansen
627 var sinon = (function (formatio) {
628 var div = typeof document != "undefined" && document.createElement("div");
629 var hasOwn = Object.prototype.hasOwnProperty;
631 function isDOMNode(obj) {
635 obj.appendChild(div);
636 success = div.parentNode == obj;
641 obj.removeChild(div);
643 // Remove failed, not much we can do about that
650 function isElement(obj) {
651 return div && obj && obj.nodeType === 1 && isDOMNode(obj);
654 function isFunction(obj) {
655 return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply);
658 function isReallyNaN(val) {
659 return typeof val === 'number' && isNaN(val);
662 function mirrorProperties(target, source) {
663 for (var prop in source) {
664 if (!hasOwn.call(target, prop)) {
665 target[prop] = source[prop];
670 function isRestorable (obj) {
671 return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon;
675 wrapMethod: function wrapMethod(object, property, method) {
677 throw new TypeError("Should wrap property of object");
680 if (typeof method != "function") {
681 throw new TypeError("Method wrapper should be function");
684 var wrappedMethod = object[property],
687 if (!isFunction(wrappedMethod)) {
688 error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " +
689 property + " as function");
690 } else if (wrappedMethod.restore && wrappedMethod.restore.sinon) {
691 error = new TypeError("Attempted to wrap " + property + " which is already wrapped");
692 } else if (wrappedMethod.calledBefore) {
693 var verb = !!wrappedMethod.returns ? "stubbed" : "spied on";
694 error = new TypeError("Attempted to wrap " + property + " which is already " + verb);
698 if (wrappedMethod && wrappedMethod._stack) {
699 error.stack += '\n--------------\n' + wrappedMethod._stack;
704 // IE 8 does not support hasOwnProperty on the window object and Firefox has a problem
705 // when using hasOwn.call on objects from other frames.
706 var owned = object.hasOwnProperty ? object.hasOwnProperty(property) : hasOwn.call(object, property);
707 object[property] = method;
708 method.displayName = property;
709 // Set up a stack trace which can be used later to find what line of
710 // code the original method was created on.
711 method._stack = (new Error('Stack Trace for original')).stack;
713 method.restore = function () {
714 // For prototype properties try to reset by delete first.
715 // If this fails (ex: localStorage on mobile safari) then force a reset
716 // via direct assignment.
718 delete object[property];
720 if (object[property] === method) {
721 object[property] = wrappedMethod;
725 method.restore.sinon = true;
726 mirrorProperties(method, wrappedMethod);
731 extend: function extend(target) {
732 for (var i = 1, l = arguments.length; i < l; i += 1) {
733 for (var prop in arguments[i]) {
734 if (arguments[i].hasOwnProperty(prop)) {
735 target[prop] = arguments[i][prop];
738 // DONT ENUM bug, only care about toString
739 if (arguments[i].hasOwnProperty("toString") &&
740 arguments[i].toString != target.toString) {
741 target.toString = arguments[i].toString;
749 create: function create(proto) {
750 var F = function () {};
755 deepEqual: function deepEqual(a, b) {
756 if (sinon.match && sinon.match.isMatcher(a)) {
760 if (typeof a != 'object' || typeof b != 'object') {
761 if (isReallyNaN(a) && isReallyNaN(b)) {
768 if (isElement(a) || isElement(b)) {
776 if ((a === null && b !== null) || (a !== null && b === null)) {
780 if (a instanceof RegExp && b instanceof RegExp) {
781 return (a.source === b.source) && (a.global === b.global) &&
782 (a.ignoreCase === b.ignoreCase) && (a.multiline === b.multiline);
785 var aString = Object.prototype.toString.call(a);
786 if (aString != Object.prototype.toString.call(b)) {
790 if (aString == "[object Date]") {
791 return a.valueOf() === b.valueOf();
794 var prop, aLength = 0, bLength = 0;
796 if (aString == "[object Array]" && a.length !== b.length) {
807 if (!deepEqual(a[prop], b[prop])) {
816 return aLength == bLength;
819 functionName: function functionName(func) {
820 var name = func.displayName || func.name;
822 // Use function decomposition as a last resort to get function
823 // name. Does not rely on function decomposition to work - if it
824 // doesn't debugging will be slightly less informative
825 // (i.e. toString will say 'spy' rather than 'myFunc').
827 var matches = func.toString().match(/function ([^\s\(]+)/);
828 name = matches && matches[1];
834 functionToString: function toString() {
835 if (this.getCall && this.callCount) {
836 var thisValue, prop, i = this.callCount;
839 thisValue = this.getCall(i).thisValue;
841 for (prop in thisValue) {
842 if (thisValue[prop] === this) {
849 return this.displayName || "sinon fake";
852 getConfig: function (custom) {
854 custom = custom || {};
855 var defaults = sinon.defaultConfig;
857 for (var prop in defaults) {
858 if (defaults.hasOwnProperty(prop)) {
859 config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop];
866 format: function (val) {
871 injectIntoThis: true,
873 properties: ["spy", "stub", "mock", "clock", "server", "requests"],
878 timesInWords: function timesInWords(count) {
879 return count == 1 && "once" ||
880 count == 2 && "twice" ||
881 count == 3 && "thrice" ||
882 (count || 0) + " times";
885 calledInOrder: function (spies) {
886 for (var i = 1, l = spies.length; i < l; i++) {
887 if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) {
895 orderByFirstCall: function (spies) {
896 return spies.sort(function (a, b) {
897 // uuid, won't ever be equal
898 var aCall = a.getCall(0);
899 var bCall = b.getCall(0);
900 var aId = aCall && aCall.callId || -1;
901 var bId = bCall && bCall.callId || -1;
903 return aId < bId ? -1 : 1;
909 logError: function (label, err) {
910 var msg = label + " threw exception: ";
911 sinon.log(msg + "[" + err.name + "] " + err.message);
912 if (err.stack) { sinon.log(err.stack); }
914 setTimeout(function () {
915 err.message = msg + err.message;
920 typeOf: function (value) {
921 if (value === null) {
924 else if (value === undefined) {
927 var string = Object.prototype.toString.call(value);
928 return string.substring(8, string.length - 1).toLowerCase();
931 createStubInstance: function (constructor) {
932 if (typeof constructor !== "function") {
933 throw new TypeError("The constructor should be a function.");
935 return sinon.stub(sinon.create(constructor.prototype));
938 restore: function (object) {
939 if (object !== null && typeof object === "object") {
940 for (var prop in object) {
941 if (isRestorable(object[prop])) {
942 object[prop].restore();
946 else if (isRestorable(object)) {
952 var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
953 var isAMD = typeof define === 'function' && typeof define.amd === 'object' && define.amd;
955 function makePublicAPI(require, exports, module) {
956 module.exports = sinon;
957 sinon.spy = require("./sinon/spy");
958 sinon.spyCall = require("./sinon/call");
959 sinon.behavior = require("./sinon/behavior");
960 sinon.stub = require("./sinon/stub");
961 sinon.mock = require("./sinon/mock");
962 sinon.collection = require("./sinon/collection");
963 sinon.assert = require("./sinon/assert");
964 sinon.sandbox = require("./sinon/sandbox");
965 sinon.test = require("./sinon/test");
966 sinon.testCase = require("./sinon/test_case");
967 sinon.match = require("./sinon/match");
971 define(makePublicAPI);
974 formatio = require("formatio");
976 makePublicAPI(require, exports, module);
980 var formatter = formatio.configure({ quoteStrings: false });
981 sinon.format = function () {
982 return formatter.ascii.apply(formatter, arguments);
986 var util = require("util");
987 sinon.format = function (value) {
988 return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value;
991 /* Node, but no util module - would be very old, but better safe than
997 }(typeof formatio == "object" && formatio));
999 /* @depend ../sinon.js */
1000 /*jslint eqeqeq: false, onevar: false, plusplus: false*/
1001 /*global module, require, sinon*/
1005 * @author Maximilian Antoni (mail@maxantoni.de)
1008 * Copyright (c) 2012 Maximilian Antoni
1012 var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function";
1014 if (!sinon && commonJSModule) {
1015 sinon = require("../sinon");
1022 function assertType(value, type, name) {
1023 var actual = sinon.typeOf(value);
1024 if (actual !== type) {
1025 throw new TypeError("Expected type of " + name + " to be " +
1026 type + ", but was " + actual);
1031 toString: function () {
1032 return this.message;
1036 function isMatcher(object) {
1037 return matcher.isPrototypeOf(object);
1040 function matchObject(expectation, actual) {
1041 if (actual === null || actual === undefined) {
1044 for (var key in expectation) {
1045 if (expectation.hasOwnProperty(key)) {
1046 var exp = expectation[key];
1047 var act = actual[key];
1048 if (match.isMatcher(exp)) {
1049 if (!exp.test(act)) {
1052 } else if (sinon.typeOf(exp) === "object") {
1053 if (!matchObject(exp, act)) {
1056 } else if (!sinon.deepEqual(exp, act)) {
1064 matcher.or = function (m2) {
1065 if (!arguments.length) {
1066 throw new TypeError("Matcher expected");
1067 } else if (!isMatcher(m2)) {
1071 var or = sinon.create(matcher);
1072 or.test = function (actual) {
1073 return m1.test(actual) || m2.test(actual);
1075 or.message = m1.message + ".or(" + m2.message + ")";
1079 matcher.and = function (m2) {
1080 if (!arguments.length) {
1081 throw new TypeError("Matcher expected");
1082 } else if (!isMatcher(m2)) {
1086 var and = sinon.create(matcher);
1087 and.test = function (actual) {
1088 return m1.test(actual) && m2.test(actual);
1090 and.message = m1.message + ".and(" + m2.message + ")";
1094 var match = function (expectation, message) {
1095 var m = sinon.create(matcher);
1096 var type = sinon.typeOf(expectation);
1099 if (typeof expectation.test === "function") {
1100 m.test = function (actual) {
1101 return expectation.test(actual) === true;
1103 m.message = "match(" + sinon.functionName(expectation.test) + ")";
1107 for (var key in expectation) {
1108 if (expectation.hasOwnProperty(key)) {
1109 str.push(key + ": " + expectation[key]);
1112 m.test = function (actual) {
1113 return matchObject(expectation, actual);
1115 m.message = "match(" + str.join(", ") + ")";
1118 m.test = function (actual) {
1119 return expectation == actual;
1123 m.test = function (actual) {
1124 if (typeof actual !== "string") {
1127 return actual.indexOf(expectation) !== -1;
1129 m.message = "match(\"" + expectation + "\")";
1132 m.test = function (actual) {
1133 if (typeof actual !== "string") {
1136 return expectation.test(actual);
1140 m.test = expectation;
1142 m.message = message;
1144 m.message = "match(" + sinon.functionName(expectation) + ")";
1148 m.test = function (actual) {
1149 return sinon.deepEqual(expectation, actual);
1153 m.message = "match(" + expectation + ")";
1158 match.isMatcher = isMatcher;
1160 match.any = match(function () {
1164 match.defined = match(function (actual) {
1165 return actual !== null && actual !== undefined;
1168 match.truthy = match(function (actual) {
1172 match.falsy = match(function (actual) {
1176 match.same = function (expectation) {
1177 return match(function (actual) {
1178 return expectation === actual;
1179 }, "same(" + expectation + ")");
1182 match.typeOf = function (type) {
1183 assertType(type, "string", "type");
1184 return match(function (actual) {
1185 return sinon.typeOf(actual) === type;
1186 }, "typeOf(\"" + type + "\")");
1189 match.instanceOf = function (type) {
1190 assertType(type, "function", "type");
1191 return match(function (actual) {
1192 return actual instanceof type;
1193 }, "instanceOf(" + sinon.functionName(type) + ")");
1196 function createPropertyMatcher(propertyTest, messagePrefix) {
1197 return function (property, value) {
1198 assertType(property, "string", "property");
1199 var onlyProperty = arguments.length === 1;
1200 var message = messagePrefix + "(\"" + property + "\"";
1201 if (!onlyProperty) {
1202 message += ", " + value;
1205 return match(function (actual) {
1206 if (actual === undefined || actual === null ||
1207 !propertyTest(actual, property)) {
1210 return onlyProperty || sinon.deepEqual(value, actual[property]);
1215 match.has = createPropertyMatcher(function (actual, property) {
1216 if (typeof actual === "object") {
1217 return property in actual;
1219 return actual[property] !== undefined;
1222 match.hasOwn = createPropertyMatcher(function (actual, property) {
1223 return actual.hasOwnProperty(property);
1226 match.bool = match.typeOf("boolean");
1227 match.number = match.typeOf("number");
1228 match.string = match.typeOf("string");
1229 match.object = match.typeOf("object");
1230 match.func = match.typeOf("function");
1231 match.array = match.typeOf("array");
1232 match.regexp = match.typeOf("regexp");
1233 match.date = match.typeOf("date");
1235 sinon.match = match;
1237 if (typeof define === "function" && define.amd) {
1238 define(["module"], function(module) { module.exports = match; });
1239 } else if (commonJSModule) {
1240 module.exports = match;
1242 }(typeof sinon == "object" && sinon || null));
1245 * @depend ../sinon.js
1248 /*jslint eqeqeq: false, onevar: false, plusplus: false*/
1249 /*global module, require, sinon*/
1253 * @author Christian Johansen (christian@cjohansen.no)
1254 * @author Maximilian Antoni (mail@maxantoni.de)
1257 * Copyright (c) 2010-2013 Christian Johansen
1258 * Copyright (c) 2013 Maximilian Antoni
1262 var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function";
1263 if (!sinon && commonJSModule) {
1264 sinon = require("../sinon");
1271 function throwYieldError(proxy, text, args) {
1272 var msg = sinon.functionName(proxy) + text;
1274 msg += " Received [" + slice.call(args).join(", ") + "]";
1276 throw new Error(msg);
1279 var slice = Array.prototype.slice;
1282 calledOn: function calledOn(thisValue) {
1283 if (sinon.match && sinon.match.isMatcher(thisValue)) {
1284 return thisValue.test(this.thisValue);
1286 return this.thisValue === thisValue;
1289 calledWith: function calledWith() {
1290 for (var i = 0, l = arguments.length; i < l; i += 1) {
1291 if (!sinon.deepEqual(arguments[i], this.args[i])) {
1299 calledWithMatch: function calledWithMatch() {
1300 for (var i = 0, l = arguments.length; i < l; i += 1) {
1301 var actual = this.args[i];
1302 var expectation = arguments[i];
1303 if (!sinon.match || !sinon.match(expectation).test(actual)) {
1310 calledWithExactly: function calledWithExactly() {
1311 return arguments.length == this.args.length &&
1312 this.calledWith.apply(this, arguments);
1315 notCalledWith: function notCalledWith() {
1316 return !this.calledWith.apply(this, arguments);
1319 notCalledWithMatch: function notCalledWithMatch() {
1320 return !this.calledWithMatch.apply(this, arguments);
1323 returned: function returned(value) {
1324 return sinon.deepEqual(value, this.returnValue);
1327 threw: function threw(error) {
1328 if (typeof error === "undefined" || !this.exception) {
1329 return !!this.exception;
1332 return this.exception === error || this.exception.name === error;
1335 calledWithNew: function calledWithNew() {
1336 return this.proxy.prototype && this.thisValue instanceof this.proxy;
1339 calledBefore: function (other) {
1340 return this.callId < other.callId;
1343 calledAfter: function (other) {
1344 return this.callId > other.callId;
1347 callArg: function (pos) {
1351 callArgOn: function (pos, thisValue) {
1352 this.args[pos].apply(thisValue);
1355 callArgWith: function (pos) {
1356 this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1)));
1359 callArgOnWith: function (pos, thisValue) {
1360 var args = slice.call(arguments, 2);
1361 this.args[pos].apply(thisValue, args);
1364 "yield": function () {
1365 this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0)));
1368 yieldOn: function (thisValue) {
1369 var args = this.args;
1370 for (var i = 0, l = args.length; i < l; ++i) {
1371 if (typeof args[i] === "function") {
1372 args[i].apply(thisValue, slice.call(arguments, 1));
1376 throwYieldError(this.proxy, " cannot yield since no callback was passed.", args);
1379 yieldTo: function (prop) {
1380 this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1)));
1383 yieldToOn: function (prop, thisValue) {
1384 var args = this.args;
1385 for (var i = 0, l = args.length; i < l; ++i) {
1386 if (args[i] && typeof args[i][prop] === "function") {
1387 args[i][prop].apply(thisValue, slice.call(arguments, 2));
1391 throwYieldError(this.proxy, " cannot yield to '" + prop +
1392 "' since no callback was passed.", args);
1395 toString: function () {
1396 var callStr = this.proxy.toString() + "(";
1399 for (var i = 0, l = this.args.length; i < l; ++i) {
1400 args.push(sinon.format(this.args[i]));
1403 callStr = callStr + args.join(", ") + ")";
1405 if (typeof this.returnValue != "undefined") {
1406 callStr += " => " + sinon.format(this.returnValue);
1409 if (this.exception) {
1410 callStr += " !" + this.exception.name;
1412 if (this.exception.message) {
1413 callStr += "(" + this.exception.message + ")";
1421 callProto.invokeCallback = callProto.yield;
1423 function createSpyCall(spy, thisValue, args, returnValue, exception, id) {
1424 if (typeof id !== "number") {
1425 throw new TypeError("Call id is not a number");
1427 var proxyCall = sinon.create(callProto);
1428 proxyCall.proxy = spy;
1429 proxyCall.thisValue = thisValue;
1430 proxyCall.args = args;
1431 proxyCall.returnValue = returnValue;
1432 proxyCall.exception = exception;
1433 proxyCall.callId = id;
1437 createSpyCall.toString = callProto.toString; // used by mocks
1439 sinon.spyCall = createSpyCall;
1441 if (typeof define === "function" && define.amd) {
1442 define(["module"], function(module) { module.exports = createSpyCall; });
1443 } else if (commonJSModule) {
1444 module.exports = createSpyCall;
1446 }(typeof sinon == "object" && sinon || null));
1450 * @depend ../sinon.js
1453 /*jslint eqeqeq: false, onevar: false, plusplus: false*/
1454 /*global module, require, sinon*/
1458 * @author Christian Johansen (christian@cjohansen.no)
1461 * Copyright (c) 2010-2013 Christian Johansen
1465 var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function";
1466 var push = Array.prototype.push;
1467 var slice = Array.prototype.slice;
1470 if (!sinon && commonJSModule) {
1471 sinon = require("../sinon");
1478 function spy(object, property) {
1479 if (!property && typeof object == "function") {
1480 return spy.create(object);
1483 if (!object && !property) {
1484 return spy.create(function () { });
1487 var method = object[property];
1488 return sinon.wrapMethod(object, property, spy.create(method));
1491 function matchingFake(fakes, args, strict) {
1496 for (var i = 0, l = fakes.length; i < l; i++) {
1497 if (fakes[i].matches(args, strict)) {
1503 function incrementCallCount() {
1505 this.callCount += 1;
1506 this.notCalled = false;
1507 this.calledOnce = this.callCount == 1;
1508 this.calledTwice = this.callCount == 2;
1509 this.calledThrice = this.callCount == 3;
1512 function createCallProperties() {
1513 this.firstCall = this.getCall(0);
1514 this.secondCall = this.getCall(1);
1515 this.thirdCall = this.getCall(2);
1516 this.lastCall = this.getCall(this.callCount - 1);
1519 var vars = "a,b,c,d,e,f,g,h,i,j,k,l";
1520 function createProxy(func) {
1521 // Retain the function length:
1524 eval("p = (function proxy(" + vars.substring(0, func.length * 2 - 1) +
1525 ") { return p.invoke(func, this, slice.call(arguments)); });");
1528 p = function proxy() {
1529 return p.invoke(func, this, slice.call(arguments));
1539 reset: function () {
1540 this.called = false;
1541 this.notCalled = true;
1542 this.calledOnce = false;
1543 this.calledTwice = false;
1544 this.calledThrice = false;
1546 this.firstCall = null;
1547 this.secondCall = null;
1548 this.thirdCall = null;
1549 this.lastCall = null;
1551 this.returnValues = [];
1552 this.thisValues = [];
1553 this.exceptions = [];
1556 for (var i = 0; i < this.fakes.length; i++) {
1557 this.fakes[i].reset();
1562 create: function create(func) {
1565 if (typeof func != "function") {
1566 func = function () { };
1568 name = sinon.functionName(func);
1571 var proxy = createProxy(func);
1573 sinon.extend(proxy, spy);
1574 delete proxy.create;
1575 sinon.extend(proxy, func);
1578 proxy.prototype = func.prototype;
1579 proxy.displayName = name || "spy";
1580 proxy.toString = sinon.functionToString;
1581 proxy._create = sinon.spy.create;
1582 proxy.id = "spy#" + uuid++;
1587 invoke: function invoke(func, thisValue, args) {
1588 var matching = matchingFake(this.fakes, args);
1589 var exception, returnValue;
1591 incrementCallCount.call(this);
1592 push.call(this.thisValues, thisValue);
1593 push.call(this.args, args);
1594 push.call(this.callIds, callId++);
1596 createCallProperties.call(this);
1600 returnValue = matching.invoke(func, thisValue, args);
1602 returnValue = (this.func || func).apply(thisValue, args);
1605 var thisCall = this.getCall(this.callCount - 1);
1606 if (thisCall.calledWithNew() && typeof returnValue !== 'object') {
1607 returnValue = thisValue;
1613 push.call(this.exceptions, exception);
1614 push.call(this.returnValues, returnValue);
1616 if (exception !== undefined) {
1623 named: function named(name) {
1624 this.displayName = name;
1628 getCall: function getCall(i) {
1629 if (i < 0 || i >= this.callCount) {
1633 return sinon.spyCall(this, this.thisValues[i], this.args[i],
1634 this.returnValues[i], this.exceptions[i],
1638 getCalls: function () {
1642 for (i = 0; i < this.callCount; i++) {
1643 calls.push(this.getCall(i));
1649 calledBefore: function calledBefore(spyFn) {
1654 if (!spyFn.called) {
1658 return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1];
1661 calledAfter: function calledAfter(spyFn) {
1662 if (!this.called || !spyFn.called) {
1666 return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1];
1669 withArgs: function () {
1670 var args = slice.call(arguments);
1673 var match = matchingFake(this.fakes, args, true);
1682 var original = this;
1683 var fake = this._create();
1684 fake.matchingAguments = args;
1686 push.call(this.fakes, fake);
1688 fake.withArgs = function () {
1689 return original.withArgs.apply(original, arguments);
1692 for (var i = 0; i < this.args.length; i++) {
1693 if (fake.matches(this.args[i])) {
1694 incrementCallCount.call(fake);
1695 push.call(fake.thisValues, this.thisValues[i]);
1696 push.call(fake.args, this.args[i]);
1697 push.call(fake.returnValues, this.returnValues[i]);
1698 push.call(fake.exceptions, this.exceptions[i]);
1699 push.call(fake.callIds, this.callIds[i]);
1702 createCallProperties.call(fake);
1707 matches: function (args, strict) {
1708 var margs = this.matchingAguments;
1710 if (margs.length <= args.length &&
1711 sinon.deepEqual(margs, args.slice(0, margs.length))) {
1712 return !strict || margs.length == args.length;
1716 printf: function (format) {
1718 var args = slice.call(arguments, 1);
1721 return (format || "").replace(/%(.)/g, function (match, specifyer) {
1722 formatter = spyApi.formatters[specifyer];
1724 if (typeof formatter == "function") {
1725 return formatter.call(null, spy, args);
1726 } else if (!isNaN(parseInt(specifyer, 10))) {
1727 return sinon.format(args[specifyer - 1]);
1730 return "%" + specifyer;
1735 function delegateToCalls(method, matchAny, actual, notCalled) {
1736 spyApi[method] = function () {
1739 return notCalled.apply(this, arguments);
1747 for (var i = 0, l = this.callCount; i < l; i += 1) {
1748 currentCall = this.getCall(i);
1750 if (currentCall[actual || method].apply(currentCall, arguments)) {
1759 return matches === this.callCount;
1763 delegateToCalls("calledOn", true);
1764 delegateToCalls("alwaysCalledOn", false, "calledOn");
1765 delegateToCalls("calledWith", true);
1766 delegateToCalls("calledWithMatch", true);
1767 delegateToCalls("alwaysCalledWith", false, "calledWith");
1768 delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch");
1769 delegateToCalls("calledWithExactly", true);
1770 delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly");
1771 delegateToCalls("neverCalledWith", false, "notCalledWith",
1772 function () { return true; });
1773 delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch",
1774 function () { return true; });
1775 delegateToCalls("threw", true);
1776 delegateToCalls("alwaysThrew", false, "threw");
1777 delegateToCalls("returned", true);
1778 delegateToCalls("alwaysReturned", false, "returned");
1779 delegateToCalls("calledWithNew", true);
1780 delegateToCalls("alwaysCalledWithNew", false, "calledWithNew");
1781 delegateToCalls("callArg", false, "callArgWith", function () {
1782 throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
1784 spyApi.callArgWith = spyApi.callArg;
1785 delegateToCalls("callArgOn", false, "callArgOnWith", function () {
1786 throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
1788 spyApi.callArgOnWith = spyApi.callArgOn;
1789 delegateToCalls("yield", false, "yield", function () {
1790 throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
1792 // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode.
1793 spyApi.invokeCallback = spyApi.yield;
1794 delegateToCalls("yieldOn", false, "yieldOn", function () {
1795 throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
1797 delegateToCalls("yieldTo", false, "yieldTo", function (property) {
1798 throw new Error(this.toString() + " cannot yield to '" + property +
1799 "' since it was not yet invoked.");
1801 delegateToCalls("yieldToOn", false, "yieldToOn", function (property) {
1802 throw new Error(this.toString() + " cannot yield to '" + property +
1803 "' since it was not yet invoked.");
1806 spyApi.formatters = {
1807 "c": function (spy) {
1808 return sinon.timesInWords(spy.callCount);
1811 "n": function (spy) {
1812 return spy.toString();
1815 "C": function (spy) {
1818 for (var i = 0, l = spy.callCount; i < l; ++i) {
1819 var stringifiedCall = " " + spy.getCall(i).toString();
1820 if (/\n/.test(calls[i - 1])) {
1821 stringifiedCall = "\n" + stringifiedCall;
1823 push.call(calls, stringifiedCall);
1826 return calls.length > 0 ? "\n" + calls.join("\n") : "";
1829 "t": function (spy) {
1832 for (var i = 0, l = spy.callCount; i < l; ++i) {
1833 push.call(objects, sinon.format(spy.thisValues[i]));
1836 return objects.join(", ");
1839 "*": function (spy, args) {
1842 for (var i = 0, l = args.length; i < l; ++i) {
1843 push.call(formatted, sinon.format(args[i]));
1846 return formatted.join(", ");
1850 sinon.extend(spy, spyApi);
1852 spy.spyCall = sinon.spyCall;
1855 if (typeof define === "function" && define.amd) {
1856 define(["module"], function(module) { module.exports = spy; });
1857 } else if (commonJSModule) {
1858 module.exports = spy;
1860 }(typeof sinon == "object" && sinon || null));
1863 * @depend ../sinon.js
1865 /*jslint eqeqeq: false, onevar: false*/
1866 /*global module, require, sinon, process, setImmediate, setTimeout*/
1870 * @author Christian Johansen (christian@cjohansen.no)
1871 * @author Tim Fischbach (mail@timfischbach.de)
1874 * Copyright (c) 2010-2013 Christian Johansen
1878 var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function";
1880 if (!sinon && commonJSModule) {
1881 sinon = require("../sinon");
1888 var slice = Array.prototype.slice;
1889 var join = Array.prototype.join;
1892 var nextTick = (function () {
1893 if (typeof process === "object" && typeof process.nextTick === "function") {
1894 return process.nextTick;
1895 } else if (typeof setImmediate === "function") {
1896 return setImmediate;
1898 return function (callback) {
1899 setTimeout(callback, 0);
1904 function throwsException(error, message) {
1905 if (typeof error == "string") {
1906 this.exception = new Error(message || "");
1907 this.exception.name = error;
1908 } else if (!error) {
1909 this.exception = new Error("Error");
1911 this.exception = error;
1917 function getCallback(behavior, args) {
1918 var callArgAt = behavior.callArgAt;
1920 if (callArgAt < 0) {
1921 var callArgProp = behavior.callArgProp;
1923 for (var i = 0, l = args.length; i < l; ++i) {
1924 if (!callArgProp && typeof args[i] == "function") {
1928 if (callArgProp && args[i] &&
1929 typeof args[i][callArgProp] == "function") {
1930 return args[i][callArgProp];
1937 return args[callArgAt];
1940 function getCallbackError(behavior, func, args) {
1941 if (behavior.callArgAt < 0) {
1944 if (behavior.callArgProp) {
1945 msg = sinon.functionName(behavior.stub) +
1946 " expected to yield to '" + behavior.callArgProp +
1947 "', but no object with such a property was passed.";
1949 msg = sinon.functionName(behavior.stub) +
1950 " expected to yield, but no callback was passed.";
1953 if (args.length > 0) {
1954 msg += " Received [" + join.call(args, ", ") + "]";
1960 return "argument at index " + behavior.callArgAt + " is not a function: " + func;
1963 function callCallback(behavior, args) {
1964 if (typeof behavior.callArgAt == "number") {
1965 var func = getCallback(behavior, args);
1967 if (typeof func != "function") {
1968 throw new TypeError(getCallbackError(behavior, func, args));
1971 if (behavior.callbackAsync) {
1972 nextTick(function() {
1973 func.apply(behavior.callbackContext, behavior.callbackArguments);
1976 func.apply(behavior.callbackContext, behavior.callbackArguments);
1982 create: function(stub) {
1983 var behavior = sinon.extend({}, sinon.behavior);
1984 delete behavior.create;
1985 behavior.stub = stub;
1990 isPresent: function() {
1991 return (typeof this.callArgAt == 'number' ||
1993 typeof this.returnArgAt == 'number' ||
1995 this.returnValueDefined);
1998 invoke: function(context, args) {
1999 callCallback(this, args);
2001 if (this.exception) {
2002 throw this.exception;
2003 } else if (typeof this.returnArgAt == 'number') {
2004 return args[this.returnArgAt];
2005 } else if (this.returnThis) {
2009 return this.returnValue;
2012 onCall: function(index) {
2013 return this.stub.onCall(index);
2016 onFirstCall: function() {
2017 return this.stub.onFirstCall();
2020 onSecondCall: function() {
2021 return this.stub.onSecondCall();
2024 onThirdCall: function() {
2025 return this.stub.onThirdCall();
2028 withArgs: function(/* arguments */) {
2029 throw new Error('Defining a stub by invoking "stub.onCall(...).withArgs(...)" is not supported. ' +
2030 'Use "stub.withArgs(...).onCall(...)" to define sequential behavior for calls with certain arguments.');
2033 callsArg: function callsArg(pos) {
2034 if (typeof pos != "number") {
2035 throw new TypeError("argument index is not number");
2038 this.callArgAt = pos;
2039 this.callbackArguments = [];
2040 this.callbackContext = undefined;
2041 this.callArgProp = undefined;
2042 this.callbackAsync = false;
2047 callsArgOn: function callsArgOn(pos, context) {
2048 if (typeof pos != "number") {
2049 throw new TypeError("argument index is not number");
2051 if (typeof context != "object") {
2052 throw new TypeError("argument context is not an object");
2055 this.callArgAt = pos;
2056 this.callbackArguments = [];
2057 this.callbackContext = context;
2058 this.callArgProp = undefined;
2059 this.callbackAsync = false;
2064 callsArgWith: function callsArgWith(pos) {
2065 if (typeof pos != "number") {
2066 throw new TypeError("argument index is not number");
2069 this.callArgAt = pos;
2070 this.callbackArguments = slice.call(arguments, 1);
2071 this.callbackContext = undefined;
2072 this.callArgProp = undefined;
2073 this.callbackAsync = false;
2078 callsArgOnWith: function callsArgWith(pos, context) {
2079 if (typeof pos != "number") {
2080 throw new TypeError("argument index is not number");
2082 if (typeof context != "object") {
2083 throw new TypeError("argument context is not an object");
2086 this.callArgAt = pos;
2087 this.callbackArguments = slice.call(arguments, 2);
2088 this.callbackContext = context;
2089 this.callArgProp = undefined;
2090 this.callbackAsync = false;
2095 yields: function () {
2096 this.callArgAt = -1;
2097 this.callbackArguments = slice.call(arguments, 0);
2098 this.callbackContext = undefined;
2099 this.callArgProp = undefined;
2100 this.callbackAsync = false;
2105 yieldsOn: function (context) {
2106 if (typeof context != "object") {
2107 throw new TypeError("argument context is not an object");
2110 this.callArgAt = -1;
2111 this.callbackArguments = slice.call(arguments, 1);
2112 this.callbackContext = context;
2113 this.callArgProp = undefined;
2114 this.callbackAsync = false;
2119 yieldsTo: function (prop) {
2120 this.callArgAt = -1;
2121 this.callbackArguments = slice.call(arguments, 1);
2122 this.callbackContext = undefined;
2123 this.callArgProp = prop;
2124 this.callbackAsync = false;
2129 yieldsToOn: function (prop, context) {
2130 if (typeof context != "object") {
2131 throw new TypeError("argument context is not an object");
2134 this.callArgAt = -1;
2135 this.callbackArguments = slice.call(arguments, 2);
2136 this.callbackContext = context;
2137 this.callArgProp = prop;
2138 this.callbackAsync = false;
2144 "throws": throwsException,
2145 throwsException: throwsException,
2147 returns: function returns(value) {
2148 this.returnValue = value;
2149 this.returnValueDefined = true;
2154 returnsArg: function returnsArg(pos) {
2155 if (typeof pos != "number") {
2156 throw new TypeError("argument index is not number");
2159 this.returnArgAt = pos;
2164 returnsThis: function returnsThis() {
2165 this.returnThis = true;
2171 // create asynchronous versions of callsArg* and yields* methods
2172 for (var method in proto) {
2173 // need to avoid creating anotherasync versions of the newly added async methods
2174 if (proto.hasOwnProperty(method) &&
2175 method.match(/^(callsArg|yields)/) &&
2176 !method.match(/Async/)) {
2177 proto[method + 'Async'] = (function (syncFnName) {
2178 return function () {
2179 var result = this[syncFnName].apply(this, arguments);
2180 this.callbackAsync = true;
2187 sinon.behavior = proto;
2189 if (typeof define === "function" && define.amd) {
2190 define(["module"], function(module) { module.exports = proto; });
2191 } else if (commonJSModule) {
2192 module.exports = proto;
2194 }(typeof sinon == "object" && sinon || null));
2197 * @depend ../sinon.js
2199 * @depend behavior.js
2201 /*jslint eqeqeq: false, onevar: false*/
2202 /*global module, require, sinon*/
2206 * @author Christian Johansen (christian@cjohansen.no)
2209 * Copyright (c) 2010-2013 Christian Johansen
2213 var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function";
2215 if (!sinon && commonJSModule) {
2216 sinon = require("../sinon");
2223 function stub(object, property, func) {
2224 if (!!func && typeof func != "function") {
2225 throw new TypeError("Custom stub should be function");
2231 wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func;
2233 wrapper = stub.create();
2236 if (!object && typeof property === "undefined") {
2237 return sinon.stub.create();
2240 if (typeof property === "undefined" && typeof object == "object") {
2241 for (var prop in object) {
2242 if (typeof object[prop] === "function") {
2250 return sinon.wrapMethod(object, property, wrapper);
2253 function getDefaultBehavior(stub) {
2254 return stub.defaultBehavior || getParentBehaviour(stub) || sinon.behavior.create(stub);
2257 function getParentBehaviour(stub) {
2258 return (stub.parent && getCurrentBehavior(stub.parent));
2261 function getCurrentBehavior(stub) {
2262 var behavior = stub.behaviors[stub.callCount - 1];
2263 return behavior && behavior.isPresent() ? behavior : getDefaultBehavior(stub);
2268 sinon.extend(stub, (function () {
2270 create: function create() {
2271 var functionStub = function () {
2272 return getCurrentBehavior(functionStub).invoke(this, arguments);
2275 functionStub.id = "stub#" + uuid++;
2276 var orig = functionStub;
2277 functionStub = sinon.spy.create(functionStub);
2278 functionStub.func = orig;
2280 sinon.extend(functionStub, stub);
2281 functionStub._create = sinon.stub.create;
2282 functionStub.displayName = "stub";
2283 functionStub.toString = sinon.functionToString;
2285 functionStub.defaultBehavior = null;
2286 functionStub.behaviors = [];
2288 return functionStub;
2291 resetBehavior: function () {
2294 this.defaultBehavior = null;
2295 this.behaviors = [];
2297 delete this.returnValue;
2298 delete this.returnArgAt;
2299 this.returnThis = false;
2302 for (i = 0; i < this.fakes.length; i++) {
2303 this.fakes[i].resetBehavior();
2308 onCall: function(index) {
2309 if (!this.behaviors[index]) {
2310 this.behaviors[index] = sinon.behavior.create(this);
2313 return this.behaviors[index];
2316 onFirstCall: function() {
2317 return this.onCall(0);
2320 onSecondCall: function() {
2321 return this.onCall(1);
2324 onThirdCall: function() {
2325 return this.onCall(2);
2329 for (var method in sinon.behavior) {
2330 if (sinon.behavior.hasOwnProperty(method) &&
2331 !proto.hasOwnProperty(method) &&
2332 method != 'create' &&
2333 method != 'withArgs' &&
2334 method != 'invoke') {
2335 proto[method] = (function(behaviorMethod) {
2337 this.defaultBehavior = this.defaultBehavior || sinon.behavior.create(this);
2338 this.defaultBehavior[behaviorMethod].apply(this.defaultBehavior, arguments);
2350 if (typeof define === "function" && define.amd) {
2351 define(["module"], function(module) { module.exports = stub; });
2352 } else if (commonJSModule) {
2353 module.exports = stub;
2355 }(typeof sinon == "object" && sinon || null));
2358 * @depend ../sinon.js
2361 /*jslint eqeqeq: false, onevar: false, nomen: false*/
2362 /*global module, require, sinon*/
2366 * @author Christian Johansen (christian@cjohansen.no)
2369 * Copyright (c) 2010-2013 Christian Johansen
2373 var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function";
2377 if (!sinon && commonJSModule) {
2378 sinon = require("../sinon");
2385 match = sinon.match;
2387 if (!match && commonJSModule) {
2388 match = require("./match");
2391 function mock(object) {
2393 return sinon.expectation.create("Anonymous mock");
2396 return mock.create(object);
2401 sinon.extend(mock, (function () {
2402 function each(collection, callback) {
2407 for (var i = 0, l = collection.length; i < l; i += 1) {
2408 callback(collection[i]);
2413 create: function create(object) {
2415 throw new TypeError("object is null");
2418 var mockObject = sinon.extend({}, mock);
2419 mockObject.object = object;
2420 delete mockObject.create;
2425 expects: function expects(method) {
2427 throw new TypeError("method is falsy");
2430 if (!this.expectations) {
2431 this.expectations = {};
2435 if (!this.expectations[method]) {
2436 this.expectations[method] = [];
2437 var mockObject = this;
2439 sinon.wrapMethod(this.object, method, function () {
2440 return mockObject.invokeMethod(method, this, arguments);
2443 push.call(this.proxies, method);
2446 var expectation = sinon.expectation.create(method);
2447 push.call(this.expectations[method], expectation);
2452 restore: function restore() {
2453 var object = this.object;
2455 each(this.proxies, function (proxy) {
2456 if (typeof object[proxy].restore == "function") {
2457 object[proxy].restore();
2462 verify: function verify() {
2463 var expectations = this.expectations || {};
2464 var messages = [], met = [];
2466 each(this.proxies, function (proxy) {
2467 each(expectations[proxy], function (expectation) {
2468 if (!expectation.met()) {
2469 push.call(messages, expectation.toString());
2471 push.call(met, expectation.toString());
2478 if (messages.length > 0) {
2479 sinon.expectation.fail(messages.concat(met).join("\n"));
2481 sinon.expectation.pass(messages.concat(met).join("\n"));
2487 invokeMethod: function invokeMethod(method, thisValue, args) {
2488 var expectations = this.expectations && this.expectations[method];
2489 var length = expectations && expectations.length || 0, i;
2491 for (i = 0; i < length; i += 1) {
2492 if (!expectations[i].met() &&
2493 expectations[i].allowsCall(thisValue, args)) {
2494 return expectations[i].apply(thisValue, args);
2498 var messages = [], available, exhausted = 0;
2500 for (i = 0; i < length; i += 1) {
2501 if (expectations[i].allowsCall(thisValue, args)) {
2502 available = available || expectations[i];
2506 push.call(messages, " " + expectations[i].toString());
2509 if (exhausted === 0) {
2510 return available.apply(thisValue, args);
2513 messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({
2518 sinon.expectation.fail(messages.join("\n"));
2523 var times = sinon.timesInWords;
2525 sinon.expectation = (function () {
2526 var slice = Array.prototype.slice;
2527 var _invoke = sinon.spy.invoke;
2529 function callCountInWords(callCount) {
2530 if (callCount == 0) {
2531 return "never called";
2533 return "called " + times(callCount);
2537 function expectedCallCountInWords(expectation) {
2538 var min = expectation.minCalls;
2539 var max = expectation.maxCalls;
2541 if (typeof min == "number" && typeof max == "number") {
2542 var str = times(min);
2545 str = "at least " + str + " and at most " + times(max);
2551 if (typeof min == "number") {
2552 return "at least " + times(min);
2555 return "at most " + times(max);
2558 function receivedMinCalls(expectation) {
2559 var hasMinLimit = typeof expectation.minCalls == "number";
2560 return !hasMinLimit || expectation.callCount >= expectation.minCalls;
2563 function receivedMaxCalls(expectation) {
2564 if (typeof expectation.maxCalls != "number") {
2568 return expectation.callCount == expectation.maxCalls;
2571 function verifyMatcher(possibleMatcher, arg){
2572 if (match && match.isMatcher(possibleMatcher)) {
2573 return possibleMatcher.test(arg);
2583 create: function create(methodName) {
2584 var expectation = sinon.extend(sinon.stub.create(), sinon.expectation);
2585 delete expectation.create;
2586 expectation.method = methodName;
2591 invoke: function invoke(func, thisValue, args) {
2592 this.verifyCallAllowed(thisValue, args);
2594 return _invoke.apply(this, arguments);
2597 atLeast: function atLeast(num) {
2598 if (typeof num != "number") {
2599 throw new TypeError("'" + num + "' is not number");
2602 if (!this.limitsSet) {
2603 this.maxCalls = null;
2604 this.limitsSet = true;
2607 this.minCalls = num;
2612 atMost: function atMost(num) {
2613 if (typeof num != "number") {
2614 throw new TypeError("'" + num + "' is not number");
2617 if (!this.limitsSet) {
2618 this.minCalls = null;
2619 this.limitsSet = true;
2622 this.maxCalls = num;
2627 never: function never() {
2628 return this.exactly(0);
2631 once: function once() {
2632 return this.exactly(1);
2635 twice: function twice() {
2636 return this.exactly(2);
2639 thrice: function thrice() {
2640 return this.exactly(3);
2643 exactly: function exactly(num) {
2644 if (typeof num != "number") {
2645 throw new TypeError("'" + num + "' is not a number");
2649 return this.atMost(num);
2652 met: function met() {
2653 return !this.failed && receivedMinCalls(this);
2656 verifyCallAllowed: function verifyCallAllowed(thisValue, args) {
2657 if (receivedMaxCalls(this)) {
2659 sinon.expectation.fail(this.method + " already called " + times(this.maxCalls));
2662 if ("expectedThis" in this && this.expectedThis !== thisValue) {
2663 sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " +
2667 if (!("expectedArguments" in this)) {
2672 sinon.expectation.fail(this.method + " received no arguments, expected " +
2673 sinon.format(this.expectedArguments));
2676 if (args.length < this.expectedArguments.length) {
2677 sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) +
2678 "), expected " + sinon.format(this.expectedArguments));
2681 if (this.expectsExactArgCount &&
2682 args.length != this.expectedArguments.length) {
2683 sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) +
2684 "), expected " + sinon.format(this.expectedArguments));
2687 for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
2689 if (!verifyMatcher(this.expectedArguments[i],args[i])) {
2690 sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) +
2691 ", didn't match " + this.expectedArguments.toString());
2694 if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
2695 sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) +
2696 ", expected " + sinon.format(this.expectedArguments));
2701 allowsCall: function allowsCall(thisValue, args) {
2702 if (this.met() && receivedMaxCalls(this)) {
2706 if ("expectedThis" in this && this.expectedThis !== thisValue) {
2710 if (!("expectedArguments" in this)) {
2716 if (args.length < this.expectedArguments.length) {
2720 if (this.expectsExactArgCount &&
2721 args.length != this.expectedArguments.length) {
2725 for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
2726 if (!verifyMatcher(this.expectedArguments[i],args[i])) {
2730 if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
2738 withArgs: function withArgs() {
2739 this.expectedArguments = slice.call(arguments);
2743 withExactArgs: function withExactArgs() {
2744 this.withArgs.apply(this, arguments);
2745 this.expectsExactArgCount = true;
2749 on: function on(thisValue) {
2750 this.expectedThis = thisValue;
2754 toString: function () {
2755 var args = (this.expectedArguments || []).slice();
2757 if (!this.expectsExactArgCount) {
2758 push.call(args, "[...]");
2761 var callStr = sinon.spyCall.toString.call({
2762 proxy: this.method || "anonymous mock expectation",
2766 var message = callStr.replace(", [...", "[, ...") + " " +
2767 expectedCallCountInWords(this);
2770 return "Expectation met: " + message;
2773 return "Expected " + message + " (" +
2774 callCountInWords(this.callCount) + ")";
2777 verify: function verify() {
2779 sinon.expectation.fail(this.toString());
2781 sinon.expectation.pass(this.toString());
2787 pass: function(message) {
2788 sinon.assert.pass(message);
2790 fail: function (message) {
2791 var exception = new Error(message);
2792 exception.name = "ExpectationError";
2801 if (typeof define === "function" && define.amd) {
2802 define(["module"], function(module) { module.exports = mock; });
2803 } else if (commonJSModule) {
2804 module.exports = mock;
2806 }(typeof sinon == "object" && sinon || null));
2809 * @depend ../sinon.js
2813 /*jslint eqeqeq: false, onevar: false, forin: true*/
2814 /*global module, require, sinon*/
2816 * Collections of stubs, spies and mocks.
2818 * @author Christian Johansen (christian@cjohansen.no)
2821 * Copyright (c) 2010-2013 Christian Johansen
2825 var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function";
2827 var hasOwnProperty = Object.prototype.hasOwnProperty;
2829 if (!sinon && commonJSModule) {
2830 sinon = require("../sinon");
2837 function getFakes(fakeCollection) {
2838 if (!fakeCollection.fakes) {
2839 fakeCollection.fakes = [];
2842 return fakeCollection.fakes;
2845 function each(fakeCollection, method) {
2846 var fakes = getFakes(fakeCollection);
2848 for (var i = 0, l = fakes.length; i < l; i += 1) {
2849 if (typeof fakes[i][method] == "function") {
2855 function compact(fakeCollection) {
2856 var fakes = getFakes(fakeCollection);
2858 while (i < fakes.length) {
2864 verify: function resolve() {
2865 each(this, "verify");
2868 restore: function restore() {
2869 each(this, "restore");
2873 verifyAndRestore: function verifyAndRestore() {
2889 add: function add(fake) {
2890 push.call(getFakes(this), fake);
2894 spy: function spy() {
2895 return this.add(sinon.spy.apply(sinon, arguments));
2898 stub: function stub(object, property, value) {
2900 var original = object[property];
2902 if (typeof original != "function") {
2903 if (!hasOwnProperty.call(object, property)) {
2904 throw new TypeError("Cannot stub non-existent own property " + property);
2907 object[property] = value;
2910 restore: function () {
2911 object[property] = original;
2916 if (!property && !!object && typeof object == "object") {
2917 var stubbedObj = sinon.stub.apply(sinon, arguments);
2919 for (var prop in stubbedObj) {
2920 if (typeof stubbedObj[prop] === "function") {
2921 this.add(stubbedObj[prop]);
2928 return this.add(sinon.stub.apply(sinon, arguments));
2931 mock: function mock() {
2932 return this.add(sinon.mock.apply(sinon, arguments));
2935 inject: function inject(obj) {
2938 obj.spy = function () {
2939 return col.spy.apply(col, arguments);
2942 obj.stub = function () {
2943 return col.stub.apply(col, arguments);
2946 obj.mock = function () {
2947 return col.mock.apply(col, arguments);
2954 sinon.collection = collection;
2956 if (typeof define === "function" && define.amd) {
2957 define(["module"], function(module) { module.exports = collection; });
2958 } else if (commonJSModule) {
2959 module.exports = collection;
2961 }(typeof sinon == "object" && sinon || null));
2963 /*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/
2964 /*global module, require, window*/
2975 * Inspired by jsUnitMockTimeOut from JsUnit
2977 * @author Christian Johansen (christian@cjohansen.no)
2980 * Copyright (c) 2010-2013 Christian Johansen
2983 if (typeof sinon == "undefined") {
2987 (function (global) {
2988 // node expects setTimeout/setInterval to return a fn object w/ .ref()/.unref()
2989 // browsers, a number.
2990 // see https://github.com/cjohansen/Sinon.JS/pull/436
2991 var timeoutResult = setTimeout(function() {}, 0);
2992 var addTimerReturnsObject = typeof timeoutResult === 'object';
2993 clearTimeout(timeoutResult);
2997 function addTimer(args, recurring) {
2998 if (args.length === 0) {
2999 throw new Error("Function requires at least 1 parameter");
3002 if (typeof args[0] === "undefined") {
3003 throw new Error("Callback must be provided to timer calls");
3007 var delay = args[1] || 0;
3009 if (!this.timeouts) {
3013 this.timeouts[toId] = {
3016 callAt: this.now + delay,
3017 invokeArgs: Array.prototype.slice.call(args, 2)
3020 if (recurring === true) {
3021 this.timeouts[toId].interval = delay;
3024 if (addTimerReturnsObject) {
3028 unref: function() {}
3036 function parseTime(str) {
3041 var strings = str.split(":");
3042 var l = strings.length, i = l;
3045 if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
3046 throw new Error("tick only understands numbers and 'h:m:s'");
3050 parsed = parseInt(strings[i], 10);
3053 throw new Error("Invalid time " + str);
3056 ms += parsed * Math.pow(60, (l - i - 1));
3062 function createObject(object) {
3065 if (Object.create) {
3066 newObject = Object.create(object);
3068 var F = function () {};
3069 F.prototype = object;
3070 newObject = new F();
3073 newObject.Date.clock = newObject;
3080 create: function create(now) {
3081 var clock = createObject(this);
3083 if (typeof now == "number") {
3087 if (!!now && typeof now == "object") {
3088 throw new TypeError("now should be milliseconds since UNIX epoch");
3094 setTimeout: function setTimeout(callback, timeout) {
3095 return addTimer.call(this, arguments, false);
3098 clearTimeout: function clearTimeout(timerId) {
3099 if (!this.timeouts) {
3102 // in Node, timerId is an object with .ref()/.unref(), and
3103 // its .id field is the actual timer id.
3104 if (typeof timerId === 'object') {
3105 timerId = timerId.id
3107 if (timerId in this.timeouts) {
3108 delete this.timeouts[timerId];
3112 setInterval: function setInterval(callback, timeout) {
3113 return addTimer.call(this, arguments, true);
3116 clearInterval: function clearInterval(timerId) {
3117 this.clearTimeout(timerId);
3120 setImmediate: function setImmediate(callback) {
3121 var passThruArgs = Array.prototype.slice.call(arguments, 1);
3123 return addTimer.call(this, [callback, 0].concat(passThruArgs), false);
3126 clearImmediate: function clearImmediate(timerId) {
3127 this.clearTimeout(timerId);
3130 tick: function tick(ms) {
3131 ms = typeof ms == "number" ? ms : parseTime(ms);
3132 var tickFrom = this.now, tickTo = this.now + ms, previous = this.now;
3133 var timer = this.firstTimerInRange(tickFrom, tickTo);
3136 while (timer && tickFrom <= tickTo) {
3137 if (this.timeouts[timer.id]) {
3138 tickFrom = this.now = timer.callAt;
3140 this.callTimer(timer);
3142 firstException = firstException || e;
3146 timer = this.firstTimerInRange(previous, tickTo);
3147 previous = tickFrom;
3152 if (firstException) {
3153 throw firstException;
3159 firstTimerInRange: function (from, to) {
3160 var timer, smallest = null, originalTimer;
3162 for (var id in this.timeouts) {
3163 if (this.timeouts.hasOwnProperty(id)) {
3164 if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) {
3168 if (smallest === null || this.timeouts[id].callAt < smallest) {
3169 originalTimer = this.timeouts[id];
3170 smallest = this.timeouts[id].callAt;
3173 func: this.timeouts[id].func,
3174 callAt: this.timeouts[id].callAt,
3175 interval: this.timeouts[id].interval,
3176 id: this.timeouts[id].id,
3177 invokeArgs: this.timeouts[id].invokeArgs
3183 return timer || null;
3186 callTimer: function (timer) {
3187 if (typeof timer.interval == "number") {
3188 this.timeouts[timer.id].callAt += timer.interval;
3190 delete this.timeouts[timer.id];
3194 if (typeof timer.func == "function") {
3195 timer.func.apply(null, timer.invokeArgs);
3203 if (!this.timeouts[timer.id]) {
3215 reset: function reset() {
3219 Date: (function () {
3220 var NativeDate = Date;
3222 function ClockDate(year, month, date, hour, minute, second, ms) {
3223 // Defensive and verbose to avoid potential harm in passing
3224 // explicit undefined when user does not pass argument
3225 switch (arguments.length) {
3227 return new NativeDate(ClockDate.clock.now);
3229 return new NativeDate(year);
3231 return new NativeDate(year, month);
3233 return new NativeDate(year, month, date);
3235 return new NativeDate(year, month, date, hour);
3237 return new NativeDate(year, month, date, hour, minute);
3239 return new NativeDate(year, month, date, hour, minute, second);
3241 return new NativeDate(year, month, date, hour, minute, second, ms);
3245 return mirrorDateProperties(ClockDate, NativeDate);
3249 function mirrorDateProperties(target, source) {
3251 target.now = function now() {
3252 return target.clock.now;
3258 if (source.toSource) {
3259 target.toSource = function toSource() {
3260 return source.toSource();
3263 delete target.toSource;
3266 target.toString = function toString() {
3267 return source.toString();
3270 target.prototype = source.prototype;
3271 target.parse = source.parse;
3272 target.UTC = source.UTC;
3273 target.prototype.toUTCString = source.prototype.toUTCString;
3275 for (var prop in source) {
3276 if (source.hasOwnProperty(prop)) {
3277 target[prop] = source[prop];
3284 var methods = ["Date", "setTimeout", "setInterval",
3285 "clearTimeout", "clearInterval"];
3287 if (typeof global.setImmediate !== "undefined") {
3288 methods.push("setImmediate");
3291 if (typeof global.clearImmediate !== "undefined") {
3292 methods.push("clearImmediate");
3295 function restore() {
3298 for (var i = 0, l = this.methods.length; i < l; i++) {
3299 method = this.methods[i];
3301 if (global[method].hadOwnProperty) {
3302 global[method] = this["_" + method];
3305 delete global[method];
3310 // Prevent multiple executions which will completely remove these props
3314 function stubGlobal(method, clock) {
3315 clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method);
3316 clock["_" + method] = global[method];
3318 if (method == "Date") {
3319 var date = mirrorDateProperties(clock[method], global[method]);
3320 global[method] = date;
3322 global[method] = function () {
3323 return clock[method].apply(clock, arguments);
3326 for (var prop in clock[method]) {
3327 if (clock[method].hasOwnProperty(prop)) {
3328 global[method][prop] = clock[method][prop];
3333 global[method].clock = clock;
3336 sinon.useFakeTimers = function useFakeTimers(now) {
3337 var clock = sinon.clock.create(now);
3338 clock.restore = restore;
3339 clock.methods = Array.prototype.slice.call(arguments,
3340 typeof now == "number" ? 1 : 0);
3342 if (clock.methods.length === 0) {
3343 clock.methods = methods;
3346 for (var i = 0, l = clock.methods.length; i < l; i++) {
3347 stubGlobal(clock.methods[i], clock);
3352 }(typeof global != "undefined" && typeof global !== "function" ? global : this));
3355 setTimeout: setTimeout,
3356 clearTimeout: clearTimeout,
3357 setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined),
3358 clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate: undefined),
3359 setInterval: setInterval,
3360 clearInterval: clearInterval,
3364 if (typeof module !== 'undefined' && module.exports) {
3365 module.exports = sinon;
3368 /*jslint eqeqeq: false, onevar: false*/
3369 /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
3371 * Minimal Event interface implementation
3373 * Original implementation by Sven Fuchs: https://gist.github.com/995028
3374 * Modifications and tests by Christian Johansen.
3376 * @author Sven Fuchs (svenfuchs@artweb-design.de)
3377 * @author Christian Johansen (christian@cjohansen.no)
3380 * Copyright (c) 2011 Sven Fuchs, Christian Johansen
3383 if (typeof sinon == "undefined") {
3390 sinon.Event = function Event(type, bubbles, cancelable, target) {
3391 this.initEvent(type, bubbles, cancelable, target);
3394 sinon.Event.prototype = {
3395 initEvent: function(type, bubbles, cancelable, target) {
3397 this.bubbles = bubbles;
3398 this.cancelable = cancelable;
3399 this.target = target;
3402 stopPropagation: function () {},
3404 preventDefault: function () {
3405 this.defaultPrevented = true;
3409 sinon.ProgressEvent = function ProgressEvent(type, progressEventRaw, target) {
3410 this.initEvent(type, false, false, target);
3411 this.loaded = progressEventRaw.loaded || null;
3412 this.total = progressEventRaw.total || null;
3415 sinon.ProgressEvent.prototype = new sinon.Event();
3417 sinon.ProgressEvent.prototype.constructor = sinon.ProgressEvent;
3419 sinon.CustomEvent = function CustomEvent(type, customData, target) {
3420 this.initEvent(type, false, false, target);
3421 this.detail = customData.detail || null;
3424 sinon.CustomEvent.prototype = new sinon.Event();
3426 sinon.CustomEvent.prototype.constructor = sinon.CustomEvent;
3428 sinon.EventTarget = {
3429 addEventListener: function addEventListener(event, listener) {
3430 this.eventListeners = this.eventListeners || {};
3431 this.eventListeners[event] = this.eventListeners[event] || [];
3432 push.call(this.eventListeners[event], listener);
3435 removeEventListener: function removeEventListener(event, listener) {
3436 var listeners = this.eventListeners && this.eventListeners[event] || [];
3438 for (var i = 0, l = listeners.length; i < l; ++i) {
3439 if (listeners[i] == listener) {
3440 return listeners.splice(i, 1);
3445 dispatchEvent: function dispatchEvent(event) {
3446 var type = event.type;
3447 var listeners = this.eventListeners && this.eventListeners[type] || [];
3449 for (var i = 0; i < listeners.length; i++) {
3450 if (typeof listeners[i] == "function") {
3451 listeners[i].call(this, event);
3453 listeners[i].handleEvent(event);
3457 return !!event.defaultPrevented;
3463 * @depend ../../sinon.js
3466 /*jslint eqeqeq: false, onevar: false*/
3467 /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
3469 * Fake XMLHttpRequest object
3471 * @author Christian Johansen (christian@cjohansen.no)
3474 * Copyright (c) 2010-2013 Christian Johansen
3477 // wrapper for global
3479 if (typeof sinon === "undefined") {
3483 var supportsProgress = typeof ProgressEvent !== "undefined";
3484 var supportsCustomEvent = typeof CustomEvent !== "undefined";
3485 sinon.xhr = { XMLHttpRequest: global.XMLHttpRequest };
3486 var xhr = sinon.xhr;
3487 xhr.GlobalXMLHttpRequest = global.XMLHttpRequest;
3488 xhr.GlobalActiveXObject = global.ActiveXObject;
3489 xhr.supportsActiveX = typeof xhr.GlobalActiveXObject != "undefined";
3490 xhr.supportsXHR = typeof xhr.GlobalXMLHttpRequest != "undefined";
3491 xhr.workingXHR = xhr.supportsXHR ? xhr.GlobalXMLHttpRequest : xhr.supportsActiveX
3492 ? function() { return new xhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false;
3493 xhr.supportsCORS = 'withCredentials' in (new sinon.xhr.GlobalXMLHttpRequest());
3496 var unsafeHeaders = {
3497 "Accept-Charset": true,
3498 "Accept-Encoding": true,
3500 "Content-Length": true,
3503 "Content-Transfer-Encoding": true,
3511 "Transfer-Encoding": true,
3518 function FakeXMLHttpRequest() {
3519 this.readyState = FakeXMLHttpRequest.UNSENT;
3520 this.requestHeaders = {};
3521 this.requestBody = null;
3523 this.statusText = "";
3524 this.upload = new UploadProgress();
3525 if (sinon.xhr.supportsCORS) {
3526 this.withCredentials = false;
3531 var events = ["loadstart", "load", "abort", "loadend"];
3533 function addEventListener(eventName) {
3534 xhr.addEventListener(eventName, function (event) {
3535 var listener = xhr["on" + eventName];
3537 if (listener && typeof listener == "function") {
3538 listener.call(this, event);
3543 for (var i = events.length - 1; i >= 0; i--) {
3544 addEventListener(events[i]);
3547 if (typeof FakeXMLHttpRequest.onCreate == "function") {
3548 FakeXMLHttpRequest.onCreate(this);
3552 // An upload object is created for each
3553 // FakeXMLHttpRequest and allows upload
3554 // events to be simulated using uploadProgress
3556 function UploadProgress() {
3557 this.eventListeners = {
3565 UploadProgress.prototype.addEventListener = function(event, listener) {
3566 this.eventListeners[event].push(listener);
3569 UploadProgress.prototype.removeEventListener = function(event, listener) {
3570 var listeners = this.eventListeners[event] || [];
3572 for (var i = 0, l = listeners.length; i < l; ++i) {
3573 if (listeners[i] == listener) {
3574 return listeners.splice(i, 1);
3579 UploadProgress.prototype.dispatchEvent = function(event) {
3580 var listeners = this.eventListeners[event.type] || [];
3582 for (var i = 0, listener; (listener = listeners[i]) != null; i++) {
3587 function verifyState(xhr) {
3588 if (xhr.readyState !== FakeXMLHttpRequest.OPENED) {
3589 throw new Error("INVALID_STATE_ERR");
3593 throw new Error("INVALID_STATE_ERR");
3597 // filtering to enable a white-list version of Sinon FakeXhr,
3598 // where whitelisted requests are passed through to real XHR
3599 function each(collection, callback) {
3600 if (!collection) return;
3601 for (var i = 0, l = collection.length; i < l; i += 1) {
3602 callback(collection[i]);
3605 function some(collection, callback) {
3606 for (var index = 0; index < collection.length; index++) {
3607 if(callback(collection[index]) === true) return true;
3611 // largest arity in XHR is 5 - XHR#open
3612 var apply = function(obj,method,args) {
3613 switch(args.length) {
3614 case 0: return obj[method]();
3615 case 1: return obj[method](args[0]);
3616 case 2: return obj[method](args[0],args[1]);
3617 case 3: return obj[method](args[0],args[1],args[2]);
3618 case 4: return obj[method](args[0],args[1],args[2],args[3]);
3619 case 5: return obj[method](args[0],args[1],args[2],args[3],args[4]);
3623 FakeXMLHttpRequest.filters = [];
3624 FakeXMLHttpRequest.addFilter = function(fn) {
3625 this.filters.push(fn)
3627 var IE6Re = /MSIE 6/;
3628 FakeXMLHttpRequest.defake = function(fakeXhr,xhrArgs) {
3629 var xhr = new sinon.xhr.workingXHR();
3630 each(["open","setRequestHeader","send","abort","getResponseHeader",
3631 "getAllResponseHeaders","addEventListener","overrideMimeType","removeEventListener"],
3633 fakeXhr[method] = function() {
3634 return apply(xhr,method,arguments);
3638 var copyAttrs = function(args) {
3639 each(args, function(attr) {
3641 fakeXhr[attr] = xhr[attr]
3643 if(!IE6Re.test(navigator.userAgent)) throw e;
3648 var stateChange = function() {
3649 fakeXhr.readyState = xhr.readyState;
3650 if(xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) {
3651 copyAttrs(["status","statusText"]);
3653 if(xhr.readyState >= FakeXMLHttpRequest.LOADING) {
3654 copyAttrs(["responseText"]);
3656 if(xhr.readyState === FakeXMLHttpRequest.DONE) {
3657 copyAttrs(["responseXML"]);
3659 if(fakeXhr.onreadystatechange) fakeXhr.onreadystatechange.call(fakeXhr, { target: fakeXhr });
3661 if(xhr.addEventListener) {
3662 for(var event in fakeXhr.eventListeners) {
3663 if(fakeXhr.eventListeners.hasOwnProperty(event)) {
3664 each(fakeXhr.eventListeners[event],function(handler) {
3665 xhr.addEventListener(event, handler);
3669 xhr.addEventListener("readystatechange",stateChange);
3671 xhr.onreadystatechange = stateChange;
3673 apply(xhr,"open",xhrArgs);
3675 FakeXMLHttpRequest.useFilters = false;
3677 function verifyRequestOpened(xhr) {
3678 if (xhr.readyState != FakeXMLHttpRequest.OPENED) {
3679 throw new Error("INVALID_STATE_ERR - " + xhr.readyState);
3683 function verifyRequestSent(xhr) {
3684 if (xhr.readyState == FakeXMLHttpRequest.DONE) {
3685 throw new Error("Request done");
3689 function verifyHeadersReceived(xhr) {
3690 if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) {
3691 throw new Error("No headers received");
3695 function verifyResponseBodyType(body) {
3696 if (typeof body != "string") {
3697 var error = new Error("Attempted to respond to fake XMLHttpRequest with " +
3698 body + ", which is not a string.");
3699 error.name = "InvalidBodyException";
3704 sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, {
3707 open: function open(method, url, async, username, password) {
3708 this.method = method;
3710 this.async = typeof async == "boolean" ? async : true;
3711 this.username = username;
3712 this.password = password;
3713 this.responseText = null;
3714 this.responseXML = null;
3715 this.requestHeaders = {};
3716 this.sendFlag = false;
3717 if(sinon.FakeXMLHttpRequest.useFilters === true) {
3718 var xhrArgs = arguments;
3719 var defake = some(FakeXMLHttpRequest.filters,function(filter) {
3720 return filter.apply(this,xhrArgs)
3723 return sinon.FakeXMLHttpRequest.defake(this,arguments);
3726 this.readyStateChange(FakeXMLHttpRequest.OPENED);
3729 readyStateChange: function readyStateChange(state) {
3730 this.readyState = state;
3732 if (typeof this.onreadystatechange == "function") {
3734 this.onreadystatechange();
3736 sinon.logError("Fake XHR onreadystatechange handler", e);
3740 this.dispatchEvent(new sinon.Event("readystatechange"));
3742 switch (this.readyState) {
3743 case FakeXMLHttpRequest.DONE:
3744 this.dispatchEvent(new sinon.Event("load", false, false, this));
3745 this.dispatchEvent(new sinon.Event("loadend", false, false, this));
3746 this.upload.dispatchEvent(new sinon.Event("load", false, false, this));
3747 if (supportsProgress) {
3748 this.upload.dispatchEvent(new sinon.ProgressEvent('progress', {loaded: 100, total: 100}));
3754 setRequestHeader: function setRequestHeader(header, value) {
3757 if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) {
3758 throw new Error("Refused to set unsafe header \"" + header + "\"");
3761 if (this.requestHeaders[header]) {
3762 this.requestHeaders[header] += "," + value;
3764 this.requestHeaders[header] = value;
3769 setResponseHeaders: function setResponseHeaders(headers) {
3770 verifyRequestOpened(this);
3771 this.responseHeaders = {};
3773 for (var header in headers) {
3774 if (headers.hasOwnProperty(header)) {
3775 this.responseHeaders[header] = headers[header];
3780 this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED);
3782 this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED;
3786 // Currently treats ALL data as a DOMString (i.e. no Document)
3787 send: function send(data) {
3790 if (!/^(get|head)$/i.test(this.method)) {
3791 if (this.requestHeaders["Content-Type"]) {
3792 var value = this.requestHeaders["Content-Type"].split(";");
3793 this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8";
3795 this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8";
3798 this.requestBody = data;
3801 this.errorFlag = false;
3802 this.sendFlag = this.async;
3803 this.readyStateChange(FakeXMLHttpRequest.OPENED);
3805 if (typeof this.onSend == "function") {
3809 this.dispatchEvent(new sinon.Event("loadstart", false, false, this));
3812 abort: function abort() {
3813 this.aborted = true;
3814 this.responseText = null;
3815 this.errorFlag = true;
3816 this.requestHeaders = {};
3818 if (this.readyState > sinon.FakeXMLHttpRequest.UNSENT && this.sendFlag) {
3819 this.readyStateChange(sinon.FakeXMLHttpRequest.DONE);
3820 this.sendFlag = false;
3823 this.readyState = sinon.FakeXMLHttpRequest.UNSENT;
3825 this.dispatchEvent(new sinon.Event("abort", false, false, this));
3827 this.upload.dispatchEvent(new sinon.Event("abort", false, false, this));
3829 if (typeof this.onerror === "function") {
3834 getResponseHeader: function getResponseHeader(header) {
3835 if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
3839 if (/^Set-Cookie2?$/i.test(header)) {
3843 header = header.toLowerCase();
3845 for (var h in this.responseHeaders) {
3846 if (h.toLowerCase() == header) {
3847 return this.responseHeaders[h];
3854 getAllResponseHeaders: function getAllResponseHeaders() {
3855 if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
3861 for (var header in this.responseHeaders) {
3862 if (this.responseHeaders.hasOwnProperty(header) &&
3863 !/^Set-Cookie2?$/i.test(header)) {
3864 headers += header + ": " + this.responseHeaders[header] + "\r\n";
3871 setResponseBody: function setResponseBody(body) {
3872 verifyRequestSent(this);
3873 verifyHeadersReceived(this);
3874 verifyResponseBodyType(body);
3876 var chunkSize = this.chunkSize || 10;
3878 this.responseText = "";
3882 this.readyStateChange(FakeXMLHttpRequest.LOADING);
3885 this.responseText += body.substring(index, index + chunkSize);
3887 } while (index < body.length);
3889 var type = this.getResponseHeader("Content-Type");
3891 if (this.responseText &&
3892 (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
3894 this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText);
3896 // Unable to parse XML - no biggie
3901 this.readyStateChange(FakeXMLHttpRequest.DONE);
3903 this.readyState = FakeXMLHttpRequest.DONE;
3907 respond: function respond(status, headers, body) {
3908 this.status = typeof status == "number" ? status : 200;
3909 this.statusText = FakeXMLHttpRequest.statusCodes[this.status];
3910 this.setResponseHeaders(headers || {});
3911 this.setResponseBody(body || "");
3914 uploadProgress: function uploadProgress(progressEventRaw) {
3915 if (supportsProgress) {
3916 this.upload.dispatchEvent(new sinon.ProgressEvent("progress", progressEventRaw));
3920 uploadError: function uploadError(error) {
3921 if (supportsCustomEvent) {
3922 this.upload.dispatchEvent(new sinon.CustomEvent("error", {"detail": error}));
3927 sinon.extend(FakeXMLHttpRequest, {
3930 HEADERS_RECEIVED: 2,
3935 // Borrowed from JSpec
3936 FakeXMLHttpRequest.parseXML = function parseXML(text) {
3939 if (typeof DOMParser != "undefined") {
3940 var parser = new DOMParser();
3941 xmlDoc = parser.parseFromString(text, "text/xml");
3943 xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
3944 xmlDoc.async = "false";
3945 xmlDoc.loadXML(text);
3951 FakeXMLHttpRequest.statusCodes = {
3953 101: "Switching Protocols",
3957 203: "Non-Authoritative Information",
3959 205: "Reset Content",
3960 206: "Partial Content",
3961 300: "Multiple Choice",
3962 301: "Moved Permanently",
3965 304: "Not Modified",
3967 307: "Temporary Redirect",
3969 401: "Unauthorized",
3970 402: "Payment Required",
3973 405: "Method Not Allowed",
3974 406: "Not Acceptable",
3975 407: "Proxy Authentication Required",
3976 408: "Request Timeout",
3979 411: "Length Required",
3980 412: "Precondition Failed",
3981 413: "Request Entity Too Large",
3982 414: "Request-URI Too Long",
3983 415: "Unsupported Media Type",
3984 416: "Requested Range Not Satisfiable",
3985 417: "Expectation Failed",
3986 422: "Unprocessable Entity",
3987 500: "Internal Server Error",
3988 501: "Not Implemented",
3990 503: "Service Unavailable",
3991 504: "Gateway Timeout",
3992 505: "HTTP Version Not Supported"
3995 sinon.useFakeXMLHttpRequest = function () {
3996 sinon.FakeXMLHttpRequest.restore = function restore(keepOnCreate) {
3997 if (xhr.supportsXHR) {
3998 global.XMLHttpRequest = xhr.GlobalXMLHttpRequest;
4001 if (xhr.supportsActiveX) {
4002 global.ActiveXObject = xhr.GlobalActiveXObject;
4005 delete sinon.FakeXMLHttpRequest.restore;
4007 if (keepOnCreate !== true) {
4008 delete sinon.FakeXMLHttpRequest.onCreate;
4011 if (xhr.supportsXHR) {
4012 global.XMLHttpRequest = sinon.FakeXMLHttpRequest;
4015 if (xhr.supportsActiveX) {
4016 global.ActiveXObject = function ActiveXObject(objId) {
4017 if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) {
4019 return new sinon.FakeXMLHttpRequest();
4022 return new xhr.GlobalActiveXObject(objId);
4026 return sinon.FakeXMLHttpRequest;
4029 sinon.FakeXMLHttpRequest = FakeXMLHttpRequest;
4031 })(typeof global === "object" ? global : this);
4033 if (typeof module !== 'undefined' && module.exports) {
4034 module.exports = sinon;
4038 * @depend fake_xml_http_request.js
4040 /*jslint eqeqeq: false, onevar: false, regexp: false, plusplus: false*/
4041 /*global module, require, window*/
4043 * The Sinon "server" mimics a web server that receives requests from
4044 * sinon.FakeXMLHttpRequest and provides an API to respond to those requests,
4045 * both synchronously and asynchronously. To respond synchronuously, canned
4046 * answers have to be provided upfront.
4048 * @author Christian Johansen (christian@cjohansen.no)
4051 * Copyright (c) 2010-2013 Christian Johansen
4054 if (typeof sinon == "undefined") {
4058 sinon.fakeServer = (function () {
4062 function create(proto) {
4063 F.prototype = proto;
4067 function responseArray(handler) {
4068 var response = handler;
4070 if (Object.prototype.toString.call(handler) != "[object Array]") {
4071 response = [200, {}, handler];
4074 if (typeof response[2] != "string") {
4075 throw new TypeError("Fake server response body should be string, but was " +
4076 typeof response[2]);
4082 var wloc = typeof window !== "undefined" ? window.location : {};
4083 var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host);
4085 function matchOne(response, reqMethod, reqUrl) {
4086 var rmeth = response.method;
4087 var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase();
4088 var url = response.url;
4089 var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl));
4091 return matchMethod && matchUrl;
4094 function match(response, request) {
4095 var requestUrl = request.url;
4097 if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) {
4098 requestUrl = requestUrl.replace(rCurrLoc, "");
4101 if (matchOne(response, this.getHTTPMethod(request), requestUrl)) {
4102 if (typeof response.response == "function") {
4103 var ru = response.url;
4104 var args = [request].concat(ru && typeof ru.exec == "function" ? ru.exec(requestUrl).slice(1) : []);
4105 return response.response.apply(response, args);
4114 function log(response, request) {
4117 str = "Request:\n" + sinon.format(request) + "\n\n";
4118 str += "Response:\n" + sinon.format(response) + "\n\n";
4124 create: function () {
4125 var server = create(this);
4126 this.xhr = sinon.useFakeXMLHttpRequest();
4127 server.requests = [];
4129 this.xhr.onCreate = function (xhrObj) {
4130 server.addRequest(xhrObj);
4136 addRequest: function addRequest(xhrObj) {
4138 push.call(this.requests, xhrObj);
4140 xhrObj.onSend = function () {
4141 server.handleRequest(this);
4143 if (server.autoRespond && !server.responding) {
4144 setTimeout(function () {
4145 server.responding = false;
4147 }, server.autoRespondAfter || 10);
4149 server.responding = true;
4154 getHTTPMethod: function getHTTPMethod(request) {
4155 if (this.fakeHTTPMethods && /post/i.test(request.method)) {
4156 var matches = (request.requestBody || "").match(/_method=([^\b;]+)/);
4157 return !!matches ? matches[1] : request.method;
4160 return request.method;
4163 handleRequest: function handleRequest(xhr) {
4169 push.call(this.queue, xhr);
4171 this.processRequest(xhr);
4175 respondWith: function respondWith(method, url, body) {
4176 if (arguments.length == 1 && typeof method != "function") {
4177 this.response = responseArray(method);
4181 if (!this.responses) { this.responses = []; }
4183 if (arguments.length == 1) {
4185 url = method = null;
4188 if (arguments.length == 2) {
4194 push.call(this.responses, {
4197 response: typeof body == "function" ? body : responseArray(body)
4201 respond: function respond() {
4202 if (arguments.length > 0) this.respondWith.apply(this, arguments);
4203 var queue = this.queue || [];
4204 var requests = queue.splice(0, queue.length);
4207 while(request = requests.shift()) {
4208 this.processRequest(request);
4212 processRequest: function processRequest(request) {
4214 if (request.aborted) {
4218 var response = this.response || [404, {}, ""];
4220 if (this.responses) {
4221 for (var l = this.responses.length, i = l - 1; i >= 0; i--) {
4222 if (match.call(this, this.responses[i], request)) {
4223 response = this.responses[i].response;
4229 if (request.readyState != 4) {
4230 log(response, request);
4232 request.respond(response[0], response[1], response[2]);
4235 sinon.logError("Fake server request processing", e);
4239 restore: function restore() {
4240 return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments);
4245 if (typeof module !== 'undefined' && module.exports) {
4246 module.exports = sinon;
4250 * @depend fake_server.js
4251 * @depend fake_timers.js
4253 /*jslint browser: true, eqeqeq: false, onevar: false*/
4256 * Add-on for sinon.fakeServer that automatically handles a fake timer along with
4257 * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery
4258 * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead,
4259 * it polls the object for completion with setInterval. Dispite the direct
4260 * motivation, there is nothing jQuery-specific in this file, so it can be used
4261 * in any environment where the ajax implementation depends on setInterval or
4264 * @author Christian Johansen (christian@cjohansen.no)
4267 * Copyright (c) 2010-2013 Christian Johansen
4271 function Server() {}
4272 Server.prototype = sinon.fakeServer;
4274 sinon.fakeServerWithClock = new Server();
4276 sinon.fakeServerWithClock.addRequest = function addRequest(xhr) {
4278 if (typeof setTimeout.clock == "object") {
4279 this.clock = setTimeout.clock;
4281 this.clock = sinon.useFakeTimers();
4282 this.resetClock = true;
4285 if (!this.longestTimeout) {
4286 var clockSetTimeout = this.clock.setTimeout;
4287 var clockSetInterval = this.clock.setInterval;
4290 this.clock.setTimeout = function (fn, timeout) {
4291 server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
4293 return clockSetTimeout.apply(this, arguments);
4296 this.clock.setInterval = function (fn, timeout) {
4297 server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
4299 return clockSetInterval.apply(this, arguments);
4304 return sinon.fakeServer.addRequest.call(this, xhr);
4307 sinon.fakeServerWithClock.respond = function respond() {
4308 var returnVal = sinon.fakeServer.respond.apply(this, arguments);
4311 this.clock.tick(this.longestTimeout || 0);
4312 this.longestTimeout = 0;
4314 if (this.resetClock) {
4315 this.clock.restore();
4316 this.resetClock = false;
4323 sinon.fakeServerWithClock.restore = function restore() {
4325 this.clock.restore();
4328 return sinon.fakeServer.restore.apply(this, arguments);
4333 * @depend ../sinon.js
4334 * @depend collection.js
4335 * @depend util/fake_timers.js
4336 * @depend util/fake_server_with_clock.js
4338 /*jslint eqeqeq: false, onevar: false, plusplus: false*/
4339 /*global require, module*/
4341 * Manages fake collections as well as fake utilities such as Sinon's
4342 * timers and fake XHR implementation in one convenient object.
4344 * @author Christian Johansen (christian@cjohansen.no)
4347 * Copyright (c) 2010-2013 Christian Johansen
4350 if (typeof module !== "undefined" && module.exports && typeof require == "function") {
4351 var sinon = require("../sinon");
4352 sinon.extend(sinon, require("./util/fake_timers"));
4358 function exposeValue(sandbox, config, key, value) {
4363 if (config.injectInto && !(key in config.injectInto)) {
4364 config.injectInto[key] = value;
4365 sandbox.injectedKeys.push(key);
4367 push.call(sandbox.args, value);
4371 function prepareSandboxFromConfig(config) {
4372 var sandbox = sinon.create(sinon.sandbox);
4374 if (config.useFakeServer) {
4375 if (typeof config.useFakeServer == "object") {
4376 sandbox.serverPrototype = config.useFakeServer;
4379 sandbox.useFakeServer();
4382 if (config.useFakeTimers) {
4383 if (typeof config.useFakeTimers == "object") {
4384 sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers);
4386 sandbox.useFakeTimers();
4393 sinon.sandbox = sinon.extend(sinon.create(sinon.collection), {
4394 useFakeTimers: function useFakeTimers() {
4395 this.clock = sinon.useFakeTimers.apply(sinon, arguments);
4397 return this.add(this.clock);
4400 serverPrototype: sinon.fakeServer,
4402 useFakeServer: function useFakeServer() {
4403 var proto = this.serverPrototype || sinon.fakeServer;
4405 if (!proto || !proto.create) {
4409 this.server = proto.create();
4410 return this.add(this.server);
4413 inject: function (obj) {
4414 sinon.collection.inject.call(this, obj);
4417 obj.clock = this.clock;
4421 obj.server = this.server;
4422 obj.requests = this.server.requests;
4428 restore: function () {
4429 sinon.collection.restore.apply(this, arguments);
4430 this.restoreContext();
4433 restoreContext: function () {
4434 if (this.injectedKeys) {
4435 for (var i = 0, j = this.injectedKeys.length; i < j; i++) {
4436 delete this.injectInto[this.injectedKeys[i]];
4438 this.injectedKeys = [];
4442 create: function (config) {
4444 return sinon.create(sinon.sandbox);
4447 var sandbox = prepareSandboxFromConfig(config);
4448 sandbox.args = sandbox.args || [];
4449 sandbox.injectedKeys = [];
4450 sandbox.injectInto = config.injectInto;
4451 var prop, value, exposed = sandbox.inject({});
4453 if (config.properties) {
4454 for (var i = 0, l = config.properties.length; i < l; i++) {
4455 prop = config.properties[i];
4456 value = exposed[prop] || prop == "sandbox" && sandbox;
4457 exposeValue(sandbox, config, prop, value);
4460 exposeValue(sandbox, config, "sandbox", value);
4467 sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer;
4469 if (typeof define === "function" && define.amd) {
4470 define(["module"], function(module) { module.exports = sinon.sandbox; });
4471 } else if (typeof module !== 'undefined' && module.exports) {
4472 module.exports = sinon.sandbox;
4477 * @depend ../sinon.js
4480 * @depend sandbox.js
4482 /*jslint eqeqeq: false, onevar: false, forin: true, plusplus: false*/
4483 /*global module, require, sinon*/
4485 * Test function, sandboxes fakes
4487 * @author Christian Johansen (christian@cjohansen.no)
4490 * Copyright (c) 2010-2013 Christian Johansen
4494 var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function";
4496 if (!sinon && commonJSModule) {
4497 sinon = require("../sinon");
4504 function test(callback) {
4505 var type = typeof callback;
4507 if (type != "function") {
4508 throw new TypeError("sinon.test needs to wrap a test function, got " + type);
4511 return function () {
4512 var config = sinon.getConfig(sinon.config);
4513 config.injectInto = config.injectIntoThis && this || config.injectInto;
4514 var sandbox = sinon.sandbox.create(config);
4515 var exception, result;
4516 var args = Array.prototype.slice.call(arguments).concat(sandbox.args);
4519 result = callback.apply(this, args);
4524 if (typeof exception !== "undefined") {
4529 sandbox.verifyAndRestore();
4537 injectIntoThis: true,
4539 properties: ["spy", "stub", "mock", "clock", "server", "requests"],
4540 useFakeTimers: true,
4546 if (typeof define === "function" && define.amd) {
4547 define(["module"], function(module) { module.exports = test; });
4548 } else if (commonJSModule) {
4549 module.exports = test;
4551 }(typeof sinon == "object" && sinon || null));
4554 * @depend ../sinon.js
4557 /*jslint eqeqeq: false, onevar: false, eqeqeq: false*/
4558 /*global module, require, sinon*/
4560 * Test case, sandboxes all test functions
4562 * @author Christian Johansen (christian@cjohansen.no)
4565 * Copyright (c) 2010-2013 Christian Johansen
4569 var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function";
4571 if (!sinon && commonJSModule) {
4572 sinon = require("../sinon");
4575 if (!sinon || !Object.prototype.hasOwnProperty) {
4579 function createTest(property, setUp, tearDown) {
4580 return function () {
4582 setUp.apply(this, arguments);
4585 var exception, result;
4588 result = property.apply(this, arguments);
4594 tearDown.apply(this, arguments);
4605 function testCase(tests, prefix) {
4607 if (!tests || typeof tests != "object") {
4608 throw new TypeError("sinon.testCase needs an object with test functions");
4612 prefix = prefix || "test";
4613 var rPrefix = new RegExp("^" + prefix);
4614 var methods = {}, testName, property, method;
4615 var setUp = tests.setUp;
4616 var tearDown = tests.tearDown;
4618 for (testName in tests) {
4619 if (tests.hasOwnProperty(testName)) {
4620 property = tests[testName];
4622 if (/^(setUp|tearDown)$/.test(testName)) {
4626 if (typeof property == "function" && rPrefix.test(testName)) {
4629 if (setUp || tearDown) {
4630 method = createTest(property, setUp, tearDown);
4633 methods[testName] = sinon.test(method);
4635 methods[testName] = tests[testName];
4643 sinon.testCase = testCase;
4645 if (typeof define === "function" && define.amd) {
4646 define(["module"], function(module) { module.exports = testCase; });
4647 } else if (commonJSModule) {
4648 module.exports = testCase;
4650 }(typeof sinon == "object" && sinon || null));
4653 * @depend ../sinon.js
4656 /*jslint eqeqeq: false, onevar: false, nomen: false, plusplus: false*/
4657 /*global module, require, sinon*/
4659 * Assertions matching the test spy retrieval interface.
4661 * @author Christian Johansen (christian@cjohansen.no)
4664 * Copyright (c) 2010-2013 Christian Johansen
4667 (function (sinon, global) {
4668 var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function";
4669 var slice = Array.prototype.slice;
4672 if (!sinon && commonJSModule) {
4673 sinon = require("../sinon");
4680 function verifyIsStub() {
4683 for (var i = 0, l = arguments.length; i < l; ++i) {
4684 method = arguments[i];
4687 assert.fail("fake is not a spy");
4690 if (typeof method != "function") {
4691 assert.fail(method + " is not a function");
4694 if (typeof method.getCall != "function") {
4695 assert.fail(method + " is not stubbed");
4700 function failAssertion(object, msg) {
4701 object = object || global;
4702 var failMethod = object.fail || assert.fail;
4703 failMethod.call(object, msg);
4706 function mirrorPropAsAssertion(name, method, message) {
4707 if (arguments.length == 2) {
4712 assert[name] = function (fake) {
4715 var args = slice.call(arguments, 1);
4718 if (typeof method == "function") {
4719 failed = !method(fake);
4721 failed = typeof fake[method] == "function" ?
4722 !fake[method].apply(fake, args) : !fake[method];
4726 failAssertion(this, fake.printf.apply(fake, [message].concat(args)));
4733 function exposedName(prefix, prop) {
4734 return !prefix || /^fail/.test(prop) ? prop :
4735 prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1);
4739 failException: "AssertError",
4741 fail: function fail(message) {
4742 var error = new Error(message);
4743 error.name = this.failException || assert.failException;
4748 pass: function pass(assertion) {},
4750 callOrder: function assertCallOrder() {
4751 verifyIsStub.apply(null, arguments);
4752 var expected = "", actual = "";
4754 if (!sinon.calledInOrder(arguments)) {
4756 expected = [].join.call(arguments, ", ");
4757 var calls = slice.call(arguments);
4758 var i = calls.length;
4760 if (!calls[--i].called) {
4764 actual = sinon.orderByFirstCall(calls).join(", ");
4766 // If this fails, we'll just fall back to the blank string
4769 failAssertion(this, "expected " + expected + " to be " +
4770 "called in order but were called as " + actual);
4772 assert.pass("callOrder");
4776 callCount: function assertCallCount(method, count) {
4777 verifyIsStub(method);
4779 if (method.callCount != count) {
4780 var msg = "expected %n to be called " + sinon.timesInWords(count) +
4781 " but was called %c%C";
4782 failAssertion(this, method.printf(msg));
4784 assert.pass("callCount");
4788 expose: function expose(target, options) {
4790 throw new TypeError("target is null or undefined");
4793 var o = options || {};
4794 var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix;
4795 var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail;
4797 for (var method in this) {
4798 if (method != "export" && (includeFail || !/^(fail)/.test(method))) {
4799 target[exposedName(prefix, method)] = this[method];
4806 match: function match(actual, expectation) {
4807 var matcher = sinon.match(expectation);
4808 if (matcher.test(actual)) {
4809 assert.pass("match");
4812 "expected value to match",
4813 " expected = " + sinon.format(expectation),
4814 " actual = " + sinon.format(actual)
4816 failAssertion(this, formatted.join("\n"));
4821 mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called");
4822 mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; },
4823 "expected %n to not have been called but was called %c%C");
4824 mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C");
4825 mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C");
4826 mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C");
4827 mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t");
4828 mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t");
4829 mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new");
4830 mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new");
4831 mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C");
4832 mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C");
4833 mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C");
4834 mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C");
4835 mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C");
4836 mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C");
4837 mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C");
4838 mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C");
4839 mirrorPropAsAssertion("threw", "%n did not throw exception%C");
4840 mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C");
4842 sinon.assert = assert;
4844 if (typeof define === "function" && define.amd) {
4845 define(["module"], function(module) { module.exports = assert; });
4846 } else if (commonJSModule) {
4847 module.exports = assert;
4849 }(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : (typeof self != "undefined") ? self : global));
4852 * @depend ../../sinon.js
4855 /*jslint eqeqeq: false, onevar: false*/
4856 /*global sinon, module, require, XDomainRequest*/
4858 * Fake XDomainRequest object
4862 if (typeof sinon == "undefined") {
4865 sinon.xdr = { XDomainRequest: this.XDomainRequest };
4867 // wrapper for global
4868 (function (global) {
4869 var xdr = sinon.xdr;
4870 xdr.GlobalXDomainRequest = global.XDomainRequest;
4871 xdr.supportsXDR = typeof xdr.GlobalXDomainRequest != "undefined";
4872 xdr.workingXDR = xdr.supportsXDR ? xdr.GlobalXDomainRequest : false;
4874 function FakeXDomainRequest() {
4875 this.readyState = FakeXDomainRequest.UNSENT;
4876 this.requestBody = null;
4877 this.requestHeaders = {};
4879 this.timeout = null;
4881 if (typeof FakeXDomainRequest.onCreate == "function") {
4882 FakeXDomainRequest.onCreate(this);
4886 function verifyState(xdr) {
4887 if (xdr.readyState !== FakeXDomainRequest.OPENED) {
4888 throw new Error("INVALID_STATE_ERR");
4892 throw new Error("INVALID_STATE_ERR");
4896 function verifyRequestSent(xdr) {
4897 if (xdr.readyState == FakeXDomainRequest.UNSENT) {
4898 throw new Error("Request not sent");
4900 if (xdr.readyState == FakeXDomainRequest.DONE) {
4901 throw new Error("Request done");
4905 function verifyResponseBodyType(body) {
4906 if (typeof body != "string") {
4907 var error = new Error("Attempted to respond to fake XDomainRequest with " +
4908 body + ", which is not a string.");
4909 error.name = "InvalidBodyException";
4914 sinon.extend(FakeXDomainRequest.prototype, sinon.EventTarget, {
4915 open: function open(method, url) {
4916 this.method = method;
4919 this.responseText = null;
4920 this.sendFlag = false;
4922 this.readyStateChange(FakeXDomainRequest.OPENED);
4925 readyStateChange: function readyStateChange(state) {
4926 this.readyState = state;
4928 switch (this.readyState) {
4929 case FakeXDomainRequest.UNSENT:
4931 case FakeXDomainRequest.OPENED:
4933 case FakeXDomainRequest.LOADING:
4935 //raise the progress event
4936 eventName = 'onprogress';
4939 case FakeXDomainRequest.DONE:
4940 if (this.isTimeout){
4941 eventName = 'ontimeout'
4943 else if (this.errorFlag || (this.status < 200 || this.status > 299)) {
4944 eventName = 'onerror';
4947 eventName = 'onload'
4952 // raising event (if defined)
4954 if (typeof this[eventName] == "function") {
4958 sinon.logError("Fake XHR " + eventName + " handler", e);
4964 send: function send(data) {
4967 if (!/^(get|head)$/i.test(this.method)) {
4968 this.requestBody = data;
4970 this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8";
4972 this.errorFlag = false;
4973 this.sendFlag = true;
4974 this.readyStateChange(FakeXDomainRequest.OPENED);
4976 if (typeof this.onSend == "function") {
4981 abort: function abort() {
4982 this.aborted = true;
4983 this.responseText = null;
4984 this.errorFlag = true;
4986 if (this.readyState > sinon.FakeXDomainRequest.UNSENT && this.sendFlag) {
4987 this.readyStateChange(sinon.FakeXDomainRequest.DONE);
4988 this.sendFlag = false;
4992 setResponseBody: function setResponseBody(body) {
4993 verifyRequestSent(this);
4994 verifyResponseBodyType(body);
4996 var chunkSize = this.chunkSize || 10;
4998 this.responseText = "";
5001 this.readyStateChange(FakeXDomainRequest.LOADING);
5002 this.responseText += body.substring(index, index + chunkSize);
5004 } while (index < body.length);
5006 this.readyStateChange(FakeXDomainRequest.DONE);
5009 respond: function respond(status, contentType, body) {
5010 // content-type ignored, since XDomainRequest does not carry this
5011 // we keep the same syntax for respond(...) as for FakeXMLHttpRequest to ease
5012 // test integration across browsers
5013 this.status = typeof status == "number" ? status : 200;
5014 this.setResponseBody(body || "");
5017 simulatetimeout: function(){
5019 this.isTimeout = true;
5020 // Access to this should actually throw an error
5021 this.responseText = undefined;
5022 this.readyStateChange(FakeXDomainRequest.DONE);
5026 sinon.extend(FakeXDomainRequest, {
5033 sinon.useFakeXDomainRequest = function () {
5034 sinon.FakeXDomainRequest.restore = function restore(keepOnCreate) {
5035 if (xdr.supportsXDR) {
5036 global.XDomainRequest = xdr.GlobalXDomainRequest;
5039 delete sinon.FakeXDomainRequest.restore;
5041 if (keepOnCreate !== true) {
5042 delete sinon.FakeXDomainRequest.onCreate;
5045 if (xdr.supportsXDR) {
5046 global.XDomainRequest = sinon.FakeXDomainRequest;
5048 return sinon.FakeXDomainRequest;
5051 sinon.FakeXDomainRequest = FakeXDomainRequest;
5054 if (typeof module == "object" && typeof require == "function") {
5055 module.exports = sinon;
5058 return sinon;}.call(typeof window != 'undefined' && window || {}));