428b729b649b328572e8be0af2fb56202f397d91
[lhc/web/wiklou.git] / resources / sinonjs / sinon-1.9.0.js
1 /**
2 * Sinon.JS 1.9.0, 2014/03/05
3 *
4 * @author Christian Johansen (christian@cjohansen.no)
5 * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS
6 *
7 * (The BSD License)
8 *
9 * Copyright (c) 2010-2014, Christian Johansen, christian@cjohansen.no
10 * All rights reserved.
11 *
12 * Redistribution and use in source and binary forms, with or without modification,
13 * are permitted provided that the following conditions are met:
14 *
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.
23 *
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.
34 */
35
36 this.sinon = (function () {
37 var samsam, formatio;
38 function define(mod, deps, fn) { if (mod == "samsam") { samsam = deps(); } else { formatio = fn(samsam); } }
39 define.amd = true;
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
44 )(function () {
45 var o = Object.prototype;
46 var div = typeof document !== "undefined" && document.createElement("div");
47
48 function isNaN(value) {
49 // Unlike global isNaN, this avoids type coercion
50 // typeof check avoids IE host object issues, hat tip to
51 // lodash
52 var val = value; // JsLint thinks value !== value is "weird"
53 return typeof value === "number" && value !== val;
54 }
55
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];
61 }
62
63 /**
64 * @name samsam.isArguments
65 * @param Object object
66 *
67 * Returns ``true`` if ``object`` is an ``arguments`` object,
68 * ``false`` otherwise.
69 */
70 function isArguments(object) {
71 if (typeof object !== "object" || typeof object.length !== "number" ||
72 getClass(object) === "Array") {
73 return false;
74 }
75 if (typeof object.callee == "function") { return true; }
76 try {
77 object[object.length] = 6;
78 delete object[object.length];
79 } catch (e) {
80 return true;
81 }
82 return false;
83 }
84
85 /**
86 * @name samsam.isElement
87 * @param Object object
88 *
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``.
93 */
94 function isElement(object) {
95 if (!object || object.nodeType !== 1 || !div) { return false; }
96 try {
97 object.appendChild(div);
98 object.removeChild(div);
99 } catch (e) {
100 return false;
101 }
102 return true;
103 }
104
105 /**
106 * @name samsam.keys
107 * @param Object object
108 *
109 * Return an array of own property names.
110 */
111 function keys(object) {
112 var ks = [], prop;
113 for (prop in object) {
114 if (o.hasOwnProperty.call(object, prop)) { ks.push(prop); }
115 }
116 return ks;
117 }
118
119 /**
120 * @name samsam.isDate
121 * @param Object value
122 *
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
126 * ``valueOf``.
127 */
128 function isDate(value) {
129 return typeof value.getTime == "function" &&
130 value.getTime() == value.valueOf();
131 }
132
133 /**
134 * @name samsam.isNegZero
135 * @param Object value
136 *
137 * Returns ``true`` if ``value`` is ``-0``.
138 */
139 function isNegZero(value) {
140 return value === 0 && 1 / value === -Infinity;
141 }
142
143 /**
144 * @name samsam.equal
145 * @param Object obj1
146 * @param Object obj2
147 *
148 * Returns ``true`` if two objects are strictly equal. Compared to
149 * ``===`` there are two exceptions:
150 *
151 * - NaN is considered equal to NaN
152 * - -0 and +0 are not considered equal
153 */
154 function identical(obj1, obj2) {
155 if (obj1 === obj2 || (isNaN(obj1) && isNaN(obj2))) {
156 return obj1 !== 0 || isNegZero(obj1) === isNegZero(obj2);
157 }
158 }
159
160
161 /**
162 * @name samsam.deepEqual
163 * @param Object obj1
164 * @param Object obj2
165 *
166 * Deep equal comparison. Two values are "deep equal" if:
167 *
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``
173 *
174 * Supports cyclic objects.
175 */
176 function deepEqualCyclic(obj1, obj2) {
177
178 // used for cyclic comparison
179 // contain already visited objects
180 var objects1 = [],
181 objects2 = [],
182 // contain pathes (position in the object structure)
183 // of the already visited objects
184 // indexes same as in objects arrays
185 paths1 = [],
186 paths2 = [],
187 // contains combinations of already compared objects
188 // in the manner: { "$1['ref']$2['ref']": true }
189 compared = {};
190
191 /**
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
195 */
196 function isObject(value) {
197
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)) {
204
205 return true;
206 }
207
208 return false;
209 }
210
211 /**
212 * returns the index of the given object in the
213 * given objects array, -1 if not contained
214 * only needed for cyclic logic
215 */
216 function getIndex(objects, obj) {
217
218 var i;
219 for (i = 0; i < objects.length; i++) {
220 if (objects[i] === obj) {
221 return i;
222 }
223 }
224
225 return -1;
226 }
227
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;
232
233 // == null also matches undefined
234 if (obj1 === obj2 ||
235 isNaN(obj1) || isNaN(obj2) ||
236 obj1 == null || obj2 == null ||
237 type1 !== "object" || type2 !== "object") {
238
239 return identical(obj1, obj2);
240 }
241
242 // Elements are only equal if identical(expected, actual)
243 if (isElement(obj1) || isElement(obj2)) { return false; }
244
245 var isDate1 = isDate(obj1), isDate2 = isDate(obj2);
246 if (isDate1 || isDate2) {
247 if (!isDate1 || !isDate2 || obj1.getTime() !== obj2.getTime()) {
248 return false;
249 }
250 }
251
252 if (obj1 instanceof RegExp && obj2 instanceof RegExp) {
253 if (obj1.toString() !== obj2.toString()) { return false; }
254 }
255
256 var class1 = getClass(obj1);
257 var class2 = getClass(obj2);
258 var keys1 = keys(obj1);
259 var keys2 = keys(obj2);
260
261 if (isArguments(obj1) || isArguments(obj2)) {
262 if (obj1.length !== obj2.length) { return false; }
263 } else {
264 if (type1 !== type2 || class1 !== class2 ||
265 keys1.length !== keys2.length) {
266 return false;
267 }
268 }
269
270 var key, i, l,
271 // following vars are used for the cyclic logic
272 value1, value2,
273 isObject1, isObject2,
274 index1, index2,
275 newPath1, newPath2;
276
277 for (i = 0, l = keys1.length; i < l; i++) {
278 key = keys1[i];
279 if (!o.hasOwnProperty.call(obj2, key)) {
280 return false;
281 }
282
283 // Start of the cyclic logic
284
285 value1 = obj1[key];
286 value2 = obj2[key];
287
288 isObject1 = isObject(value1);
289 isObject2 = isObject(value2);
290
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;
296
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
302 ? paths1[index1]
303 : path1 + '[' + JSON.stringify(key) + ']';
304 newPath2 = index2 !== -1
305 ? paths2[index2]
306 : path2 + '[' + JSON.stringify(key) + ']';
307
308 // stop recursion if current objects are already compared
309 if (compared[newPath1 + newPath2]) {
310 return true;
311 }
312
313 // remember the current objects and their pathes
314 if (index1 === -1 && isObject1) {
315 objects1.push(value1);
316 paths1.push(newPath1);
317 }
318 if (index2 === -1 && isObject2) {
319 objects2.push(value2);
320 paths2.push(newPath2);
321 }
322
323 // remember that the current objects are already compared
324 if (isObject1 && isObject2) {
325 compared[newPath1 + newPath2] = true;
326 }
327
328 // End of cyclic logic
329
330 // neither value1 nor value2 is a cycle
331 // continue with next level
332 if (!deepEqual(value1, value2, newPath1, newPath2)) {
333 return false;
334 }
335 }
336
337 return true;
338
339 }(obj1, obj2, '$1', '$2'));
340 }
341
342 var match;
343
344 function arrayContains(array, subset) {
345 if (subset.length === 0) { return true; }
346 var i, l, j, k;
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; }
351 }
352 return true;
353 }
354 }
355 return false;
356 }
357
358 /**
359 * @name samsam.match
360 * @param Object object
361 * @param Object matcher
362 *
363 * Compare arbitrary value ``object`` with matcher.
364 */
365 match = function match(object, matcher) {
366 if (matcher && typeof matcher.test === "function") {
367 return matcher.test(object);
368 }
369
370 if (typeof matcher === "function") {
371 return matcher(object) === true;
372 }
373
374 if (typeof matcher === "string") {
375 matcher = matcher.toLowerCase();
376 var notNull = typeof object === "string" || !!object;
377 return notNull &&
378 (String(object)).toLowerCase().indexOf(matcher) >= 0;
379 }
380
381 if (typeof matcher === "number") {
382 return matcher === object;
383 }
384
385 if (typeof matcher === "boolean") {
386 return matcher === object;
387 }
388
389 if (getClass(object) === "Array" && getClass(matcher) === "Array") {
390 return arrayContains(object, matcher);
391 }
392
393 if (matcher && typeof matcher === "object") {
394 var prop;
395 for (prop in matcher) {
396 if (!match(object[prop], matcher[prop])) {
397 return false;
398 }
399 }
400 return true;
401 }
402
403 throw new Error("Matcher was not a string, a number, a " +
404 "function, a boolean or an object");
405 };
406
407 return {
408 isArguments: isArguments,
409 isElement: isElement,
410 isDate: isDate,
411 isNegZero: isNegZero,
412 identical: identical,
413 deepEqual: deepEqualCyclic,
414 match: match,
415 keys: keys
416 };
417 });
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) {
424
425 var formatio = {
426 excludeConstructors: ["Object", /^.$/],
427 quoteStrings: true
428 };
429
430 var hasOwn = Object.prototype.hasOwnProperty;
431
432 var specialObjects = [];
433 if (typeof global !== "undefined") {
434 specialObjects.push({ object: global, value: "[object global]" });
435 }
436 if (typeof document !== "undefined") {
437 specialObjects.push({
438 object: document,
439 value: "[object HTMLDocument]"
440 });
441 }
442 if (typeof window !== "undefined") {
443 specialObjects.push({ object: window, value: "[object Window]" });
444 }
445
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]) || "";
452 }
453
454 function constructorName(f, object) {
455 var name = functionName(object && object.constructor);
456 var excludes = f.excludeConstructors ||
457 formatio.excludeConstructors || [];
458
459 var i, l;
460 for (i = 0, l = excludes.length; i < l; ++i) {
461 if (typeof excludes[i] === "string" && excludes[i] === name) {
462 return "";
463 } else if (excludes[i].test && excludes[i].test(name)) {
464 return "";
465 }
466 }
467
468 return name;
469 }
470
471 function isCircular(object, objects) {
472 if (typeof object !== "object") { return false; }
473 var i, l;
474 for (i = 0, l = objects.length; i < l; ++i) {
475 if (objects[i] === object) { return true; }
476 }
477 return false;
478 }
479
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;
485 }
486
487 if (typeof object === "function" && !(object instanceof RegExp)) {
488 return ascii.func(object);
489 }
490
491 processed = processed || [];
492
493 if (isCircular(object, processed)) { return "[Circular]"; }
494
495 if (Object.prototype.toString.call(object) === "[object Array]") {
496 return ascii.array.call(f, object, processed);
497 }
498
499 if (!object) { return String((1/object) === -Infinity ? "-0" : object); }
500 if (samsam.isElement(object)) { return ascii.element(object); }
501
502 if (typeof object.toString === "function" &&
503 object.toString !== Object.prototype.toString) {
504 return object.toString();
505 }
506
507 var i, l;
508 for (i = 0, l = specialObjects.length; i < l; i++) {
509 if (object === specialObjects[i].object) {
510 return specialObjects[i].value;
511 }
512 }
513
514 return ascii.object.call(f, object, processed, indent);
515 }
516
517 ascii.func = function (func) {
518 return "function " + functionName(func) + "() {}";
519 };
520
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));
527 }
528 return "[" + pieces.join(", ") + "]";
529 };
530
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();
536 var length = 3;
537 var prop, str, obj, i, l;
538
539 for (i = 0, l = properties.length; i < l; ++i) {
540 prop = properties[i];
541 obj = object[prop];
542
543 if (isCircular(obj, processed)) {
544 str = "[Circular]";
545 } else {
546 str = ascii(this, obj, processed, indent + 2);
547 }
548
549 str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str;
550 length += str.length;
551 pieces.push(str);
552 }
553
554 var cons = constructorName(this, object);
555 var prefix = cons ? "[" + cons + "] " : "";
556 var is = "";
557 for (i = 0, l = indent; i < l; ++i) { is += " "; }
558
559 if (length + indent > 80) {
560 return prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" +
561 is + "}";
562 }
563 return prefix + "{ " + pieces.join(", ") + " }";
564 };
565
566 ascii.element = function (element) {
567 var tagName = element.tagName.toLowerCase();
568 var attrs = element.attributes, attr, pairs = [], attrName, i, l, val;
569
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 + "\""); }
576 }
577 }
578
579 var formatted = "<" + tagName + (pairs.length > 0 ? " " : "");
580 var content = element.innerHTML;
581
582 if (content.length > 20) {
583 content = content.substr(0, 20) + "[...]";
584 }
585
586 var res = formatted + pairs.join(" ") + ">" + content +
587 "</" + tagName + ">";
588
589 return res.replace(/ contentEditable="inherit"/, "");
590 };
591
592 function Formatio(options) {
593 for (var opt in options) {
594 this[opt] = options[opt];
595 }
596 }
597
598 Formatio.prototype = {
599 functionName: functionName,
600
601 configure: function (options) {
602 return new Formatio(options);
603 },
604
605 constructorName: function (object) {
606 return constructorName(this, object);
607 },
608
609 ascii: function (object, processed, indent) {
610 return ascii(this, object, processed, indent);
611 }
612 };
613
614 return Formatio.prototype;
615 });
616 /*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/
617 /*global module, require, __dirname, document*/
618 /**
619 * Sinon core utilities. For internal use only.
620 *
621 * @author Christian Johansen (christian@cjohansen.no)
622 * @license BSD
623 *
624 * Copyright (c) 2010-2013 Christian Johansen
625 */
626
627 var sinon = (function (formatio) {
628 var div = typeof document != "undefined" && document.createElement("div");
629 var hasOwn = Object.prototype.hasOwnProperty;
630
631 function isDOMNode(obj) {
632 var success = false;
633
634 try {
635 obj.appendChild(div);
636 success = div.parentNode == obj;
637 } catch (e) {
638 return false;
639 } finally {
640 try {
641 obj.removeChild(div);
642 } catch (e) {
643 // Remove failed, not much we can do about that
644 }
645 }
646
647 return success;
648 }
649
650 function isElement(obj) {
651 return div && obj && obj.nodeType === 1 && isDOMNode(obj);
652 }
653
654 function isFunction(obj) {
655 return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply);
656 }
657
658 function mirrorProperties(target, source) {
659 for (var prop in source) {
660 if (!hasOwn.call(target, prop)) {
661 target[prop] = source[prop];
662 }
663 }
664 }
665
666 function isRestorable (obj) {
667 return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon;
668 }
669
670 var sinon = {
671 wrapMethod: function wrapMethod(object, property, method) {
672 if (!object) {
673 throw new TypeError("Should wrap property of object");
674 }
675
676 if (typeof method != "function") {
677 throw new TypeError("Method wrapper should be function");
678 }
679
680 var wrappedMethod = object[property],
681 error;
682
683 if (!isFunction(wrappedMethod)) {
684 error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " +
685 property + " as function");
686 }
687
688 if (wrappedMethod.restore && wrappedMethod.restore.sinon) {
689 error = new TypeError("Attempted to wrap " + property + " which is already wrapped");
690 }
691
692 if (wrappedMethod.calledBefore) {
693 var verb = !!wrappedMethod.returns ? "stubbed" : "spied on";
694 error = new TypeError("Attempted to wrap " + property + " which is already " + verb);
695 }
696
697 if (error) {
698 if (wrappedMethod._stack) {
699 error.stack += '\n--------------\n' + wrappedMethod._stack;
700 }
701 throw error;
702 }
703
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;
712
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.
717 if (!owned) {
718 delete object[property];
719 }
720 if (object[property] === method) {
721 object[property] = wrappedMethod;
722 }
723 };
724
725 method.restore.sinon = true;
726 mirrorProperties(method, wrappedMethod);
727
728 return method;
729 },
730
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];
736 }
737
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;
742 }
743 }
744 }
745
746 return target;
747 },
748
749 create: function create(proto) {
750 var F = function () {};
751 F.prototype = proto;
752 return new F();
753 },
754
755 deepEqual: function deepEqual(a, b) {
756 if (sinon.match && sinon.match.isMatcher(a)) {
757 return a.test(b);
758 }
759 if (typeof a != "object" || typeof b != "object") {
760 return a === b;
761 }
762
763 if (isElement(a) || isElement(b)) {
764 return a === b;
765 }
766
767 if (a === b) {
768 return true;
769 }
770
771 if ((a === null && b !== null) || (a !== null && b === null)) {
772 return false;
773 }
774
775 if (a instanceof RegExp && b instanceof RegExp) {
776 return (a.source === b.source) && (a.global === b.global) &&
777 (a.ignoreCase === b.ignoreCase) && (a.multiline === b.multiline);
778 }
779
780 var aString = Object.prototype.toString.call(a);
781 if (aString != Object.prototype.toString.call(b)) {
782 return false;
783 }
784
785 if (aString == "[object Date]") {
786 return a.valueOf() === b.valueOf();
787 }
788
789 var prop, aLength = 0, bLength = 0;
790
791 if (aString == "[object Array]" && a.length !== b.length) {
792 return false;
793 }
794
795 for (prop in a) {
796 aLength += 1;
797
798 if (!deepEqual(a[prop], b[prop])) {
799 return false;
800 }
801 }
802
803 for (prop in b) {
804 bLength += 1;
805 }
806
807 return aLength == bLength;
808 },
809
810 functionName: function functionName(func) {
811 var name = func.displayName || func.name;
812
813 // Use function decomposition as a last resort to get function
814 // name. Does not rely on function decomposition to work - if it
815 // doesn't debugging will be slightly less informative
816 // (i.e. toString will say 'spy' rather than 'myFunc').
817 if (!name) {
818 var matches = func.toString().match(/function ([^\s\(]+)/);
819 name = matches && matches[1];
820 }
821
822 return name;
823 },
824
825 functionToString: function toString() {
826 if (this.getCall && this.callCount) {
827 var thisValue, prop, i = this.callCount;
828
829 while (i--) {
830 thisValue = this.getCall(i).thisValue;
831
832 for (prop in thisValue) {
833 if (thisValue[prop] === this) {
834 return prop;
835 }
836 }
837 }
838 }
839
840 return this.displayName || "sinon fake";
841 },
842
843 getConfig: function (custom) {
844 var config = {};
845 custom = custom || {};
846 var defaults = sinon.defaultConfig;
847
848 for (var prop in defaults) {
849 if (defaults.hasOwnProperty(prop)) {
850 config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop];
851 }
852 }
853
854 return config;
855 },
856
857 format: function (val) {
858 return "" + val;
859 },
860
861 defaultConfig: {
862 injectIntoThis: true,
863 injectInto: null,
864 properties: ["spy", "stub", "mock", "clock", "server", "requests"],
865 useFakeTimers: true,
866 useFakeServer: true
867 },
868
869 timesInWords: function timesInWords(count) {
870 return count == 1 && "once" ||
871 count == 2 && "twice" ||
872 count == 3 && "thrice" ||
873 (count || 0) + " times";
874 },
875
876 calledInOrder: function (spies) {
877 for (var i = 1, l = spies.length; i < l; i++) {
878 if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) {
879 return false;
880 }
881 }
882
883 return true;
884 },
885
886 orderByFirstCall: function (spies) {
887 return spies.sort(function (a, b) {
888 // uuid, won't ever be equal
889 var aCall = a.getCall(0);
890 var bCall = b.getCall(0);
891 var aId = aCall && aCall.callId || -1;
892 var bId = bCall && bCall.callId || -1;
893
894 return aId < bId ? -1 : 1;
895 });
896 },
897
898 log: function () {},
899
900 logError: function (label, err) {
901 var msg = label + " threw exception: ";
902 sinon.log(msg + "[" + err.name + "] " + err.message);
903 if (err.stack) { sinon.log(err.stack); }
904
905 setTimeout(function () {
906 err.message = msg + err.message;
907 throw err;
908 }, 0);
909 },
910
911 typeOf: function (value) {
912 if (value === null) {
913 return "null";
914 }
915 else if (value === undefined) {
916 return "undefined";
917 }
918 var string = Object.prototype.toString.call(value);
919 return string.substring(8, string.length - 1).toLowerCase();
920 },
921
922 createStubInstance: function (constructor) {
923 if (typeof constructor !== "function") {
924 throw new TypeError("The constructor should be a function.");
925 }
926 return sinon.stub(sinon.create(constructor.prototype));
927 },
928
929 restore: function (object) {
930 if (object !== null && typeof object === "object") {
931 for (var prop in object) {
932 if (isRestorable(object[prop])) {
933 object[prop].restore();
934 }
935 }
936 }
937 else if (isRestorable(object)) {
938 object.restore();
939 }
940 }
941 };
942
943 var isNode = typeof module !== "undefined" && module.exports;
944 var isAMD = typeof define === 'function' && typeof define.amd === 'object' && define.amd;
945
946 if (isAMD) {
947 define(function(){
948 return sinon;
949 });
950 } else if (isNode) {
951 try {
952 formatio = require("formatio");
953 } catch (e) {}
954 module.exports = sinon;
955 module.exports.spy = require("./sinon/spy");
956 module.exports.spyCall = require("./sinon/call");
957 module.exports.behavior = require("./sinon/behavior");
958 module.exports.stub = require("./sinon/stub");
959 module.exports.mock = require("./sinon/mock");
960 module.exports.collection = require("./sinon/collection");
961 module.exports.assert = require("./sinon/assert");
962 module.exports.sandbox = require("./sinon/sandbox");
963 module.exports.test = require("./sinon/test");
964 module.exports.testCase = require("./sinon/test_case");
965 module.exports.assert = require("./sinon/assert");
966 module.exports.match = require("./sinon/match");
967 }
968
969 if (formatio) {
970 var formatter = formatio.configure({ quoteStrings: false });
971 sinon.format = function () {
972 return formatter.ascii.apply(formatter, arguments);
973 };
974 } else if (isNode) {
975 try {
976 var util = require("util");
977 sinon.format = function (value) {
978 return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value;
979 };
980 } catch (e) {
981 /* Node, but no util module - would be very old, but better safe than
982 sorry */
983 }
984 }
985
986 return sinon;
987 }(typeof formatio == "object" && formatio));
988
989 /* @depend ../sinon.js */
990 /*jslint eqeqeq: false, onevar: false, plusplus: false*/
991 /*global module, require, sinon*/
992 /**
993 * Match functions
994 *
995 * @author Maximilian Antoni (mail@maxantoni.de)
996 * @license BSD
997 *
998 * Copyright (c) 2012 Maximilian Antoni
999 */
1000
1001 (function (sinon) {
1002 var commonJSModule = typeof module !== 'undefined' && module.exports;
1003
1004 if (!sinon && commonJSModule) {
1005 sinon = require("../sinon");
1006 }
1007
1008 if (!sinon) {
1009 return;
1010 }
1011
1012 function assertType(value, type, name) {
1013 var actual = sinon.typeOf(value);
1014 if (actual !== type) {
1015 throw new TypeError("Expected type of " + name + " to be " +
1016 type + ", but was " + actual);
1017 }
1018 }
1019
1020 var matcher = {
1021 toString: function () {
1022 return this.message;
1023 }
1024 };
1025
1026 function isMatcher(object) {
1027 return matcher.isPrototypeOf(object);
1028 }
1029
1030 function matchObject(expectation, actual) {
1031 if (actual === null || actual === undefined) {
1032 return false;
1033 }
1034 for (var key in expectation) {
1035 if (expectation.hasOwnProperty(key)) {
1036 var exp = expectation[key];
1037 var act = actual[key];
1038 if (match.isMatcher(exp)) {
1039 if (!exp.test(act)) {
1040 return false;
1041 }
1042 } else if (sinon.typeOf(exp) === "object") {
1043 if (!matchObject(exp, act)) {
1044 return false;
1045 }
1046 } else if (!sinon.deepEqual(exp, act)) {
1047 return false;
1048 }
1049 }
1050 }
1051 return true;
1052 }
1053
1054 matcher.or = function (m2) {
1055 if (!arguments.length) {
1056 throw new TypeError("Matcher expected");
1057 } else if (!isMatcher(m2)) {
1058 m2 = match(m2);
1059 }
1060 var m1 = this;
1061 var or = sinon.create(matcher);
1062 or.test = function (actual) {
1063 return m1.test(actual) || m2.test(actual);
1064 };
1065 or.message = m1.message + ".or(" + m2.message + ")";
1066 return or;
1067 };
1068
1069 matcher.and = function (m2) {
1070 if (!arguments.length) {
1071 throw new TypeError("Matcher expected");
1072 } else if (!isMatcher(m2)) {
1073 m2 = match(m2);
1074 }
1075 var m1 = this;
1076 var and = sinon.create(matcher);
1077 and.test = function (actual) {
1078 return m1.test(actual) && m2.test(actual);
1079 };
1080 and.message = m1.message + ".and(" + m2.message + ")";
1081 return and;
1082 };
1083
1084 var match = function (expectation, message) {
1085 var m = sinon.create(matcher);
1086 var type = sinon.typeOf(expectation);
1087 switch (type) {
1088 case "object":
1089 if (typeof expectation.test === "function") {
1090 m.test = function (actual) {
1091 return expectation.test(actual) === true;
1092 };
1093 m.message = "match(" + sinon.functionName(expectation.test) + ")";
1094 return m;
1095 }
1096 var str = [];
1097 for (var key in expectation) {
1098 if (expectation.hasOwnProperty(key)) {
1099 str.push(key + ": " + expectation[key]);
1100 }
1101 }
1102 m.test = function (actual) {
1103 return matchObject(expectation, actual);
1104 };
1105 m.message = "match(" + str.join(", ") + ")";
1106 break;
1107 case "number":
1108 m.test = function (actual) {
1109 return expectation == actual;
1110 };
1111 break;
1112 case "string":
1113 m.test = function (actual) {
1114 if (typeof actual !== "string") {
1115 return false;
1116 }
1117 return actual.indexOf(expectation) !== -1;
1118 };
1119 m.message = "match(\"" + expectation + "\")";
1120 break;
1121 case "regexp":
1122 m.test = function (actual) {
1123 if (typeof actual !== "string") {
1124 return false;
1125 }
1126 return expectation.test(actual);
1127 };
1128 break;
1129 case "function":
1130 m.test = expectation;
1131 if (message) {
1132 m.message = message;
1133 } else {
1134 m.message = "match(" + sinon.functionName(expectation) + ")";
1135 }
1136 break;
1137 default:
1138 m.test = function (actual) {
1139 return sinon.deepEqual(expectation, actual);
1140 };
1141 }
1142 if (!m.message) {
1143 m.message = "match(" + expectation + ")";
1144 }
1145 return m;
1146 };
1147
1148 match.isMatcher = isMatcher;
1149
1150 match.any = match(function () {
1151 return true;
1152 }, "any");
1153
1154 match.defined = match(function (actual) {
1155 return actual !== null && actual !== undefined;
1156 }, "defined");
1157
1158 match.truthy = match(function (actual) {
1159 return !!actual;
1160 }, "truthy");
1161
1162 match.falsy = match(function (actual) {
1163 return !actual;
1164 }, "falsy");
1165
1166 match.same = function (expectation) {
1167 return match(function (actual) {
1168 return expectation === actual;
1169 }, "same(" + expectation + ")");
1170 };
1171
1172 match.typeOf = function (type) {
1173 assertType(type, "string", "type");
1174 return match(function (actual) {
1175 return sinon.typeOf(actual) === type;
1176 }, "typeOf(\"" + type + "\")");
1177 };
1178
1179 match.instanceOf = function (type) {
1180 assertType(type, "function", "type");
1181 return match(function (actual) {
1182 return actual instanceof type;
1183 }, "instanceOf(" + sinon.functionName(type) + ")");
1184 };
1185
1186 function createPropertyMatcher(propertyTest, messagePrefix) {
1187 return function (property, value) {
1188 assertType(property, "string", "property");
1189 var onlyProperty = arguments.length === 1;
1190 var message = messagePrefix + "(\"" + property + "\"";
1191 if (!onlyProperty) {
1192 message += ", " + value;
1193 }
1194 message += ")";
1195 return match(function (actual) {
1196 if (actual === undefined || actual === null ||
1197 !propertyTest(actual, property)) {
1198 return false;
1199 }
1200 return onlyProperty || sinon.deepEqual(value, actual[property]);
1201 }, message);
1202 };
1203 }
1204
1205 match.has = createPropertyMatcher(function (actual, property) {
1206 if (typeof actual === "object") {
1207 return property in actual;
1208 }
1209 return actual[property] !== undefined;
1210 }, "has");
1211
1212 match.hasOwn = createPropertyMatcher(function (actual, property) {
1213 return actual.hasOwnProperty(property);
1214 }, "hasOwn");
1215
1216 match.bool = match.typeOf("boolean");
1217 match.number = match.typeOf("number");
1218 match.string = match.typeOf("string");
1219 match.object = match.typeOf("object");
1220 match.func = match.typeOf("function");
1221 match.array = match.typeOf("array");
1222 match.regexp = match.typeOf("regexp");
1223 match.date = match.typeOf("date");
1224
1225 if (commonJSModule) {
1226 module.exports = match;
1227 } else {
1228 sinon.match = match;
1229 }
1230 }(typeof sinon == "object" && sinon || null));
1231
1232 /**
1233 * @depend ../sinon.js
1234 * @depend match.js
1235 */
1236 /*jslint eqeqeq: false, onevar: false, plusplus: false*/
1237 /*global module, require, sinon*/
1238 /**
1239 * Spy calls
1240 *
1241 * @author Christian Johansen (christian@cjohansen.no)
1242 * @author Maximilian Antoni (mail@maxantoni.de)
1243 * @license BSD
1244 *
1245 * Copyright (c) 2010-2013 Christian Johansen
1246 * Copyright (c) 2013 Maximilian Antoni
1247 */
1248
1249 (function (sinon) {
1250 var commonJSModule = typeof module !== 'undefined' && module.exports;
1251 if (!sinon && commonJSModule) {
1252 sinon = require("../sinon");
1253 }
1254
1255 if (!sinon) {
1256 return;
1257 }
1258
1259 function throwYieldError(proxy, text, args) {
1260 var msg = sinon.functionName(proxy) + text;
1261 if (args.length) {
1262 msg += " Received [" + slice.call(args).join(", ") + "]";
1263 }
1264 throw new Error(msg);
1265 }
1266
1267 var slice = Array.prototype.slice;
1268
1269 var callProto = {
1270 calledOn: function calledOn(thisValue) {
1271 if (sinon.match && sinon.match.isMatcher(thisValue)) {
1272 return thisValue.test(this.thisValue);
1273 }
1274 return this.thisValue === thisValue;
1275 },
1276
1277 calledWith: function calledWith() {
1278 for (var i = 0, l = arguments.length; i < l; i += 1) {
1279 if (!sinon.deepEqual(arguments[i], this.args[i])) {
1280 return false;
1281 }
1282 }
1283
1284 return true;
1285 },
1286
1287 calledWithMatch: function calledWithMatch() {
1288 for (var i = 0, l = arguments.length; i < l; i += 1) {
1289 var actual = this.args[i];
1290 var expectation = arguments[i];
1291 if (!sinon.match || !sinon.match(expectation).test(actual)) {
1292 return false;
1293 }
1294 }
1295 return true;
1296 },
1297
1298 calledWithExactly: function calledWithExactly() {
1299 return arguments.length == this.args.length &&
1300 this.calledWith.apply(this, arguments);
1301 },
1302
1303 notCalledWith: function notCalledWith() {
1304 return !this.calledWith.apply(this, arguments);
1305 },
1306
1307 notCalledWithMatch: function notCalledWithMatch() {
1308 return !this.calledWithMatch.apply(this, arguments);
1309 },
1310
1311 returned: function returned(value) {
1312 return sinon.deepEqual(value, this.returnValue);
1313 },
1314
1315 threw: function threw(error) {
1316 if (typeof error === "undefined" || !this.exception) {
1317 return !!this.exception;
1318 }
1319
1320 return this.exception === error || this.exception.name === error;
1321 },
1322
1323 calledWithNew: function calledWithNew() {
1324 return this.proxy.prototype && this.thisValue instanceof this.proxy;
1325 },
1326
1327 calledBefore: function (other) {
1328 return this.callId < other.callId;
1329 },
1330
1331 calledAfter: function (other) {
1332 return this.callId > other.callId;
1333 },
1334
1335 callArg: function (pos) {
1336 this.args[pos]();
1337 },
1338
1339 callArgOn: function (pos, thisValue) {
1340 this.args[pos].apply(thisValue);
1341 },
1342
1343 callArgWith: function (pos) {
1344 this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1)));
1345 },
1346
1347 callArgOnWith: function (pos, thisValue) {
1348 var args = slice.call(arguments, 2);
1349 this.args[pos].apply(thisValue, args);
1350 },
1351
1352 "yield": function () {
1353 this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0)));
1354 },
1355
1356 yieldOn: function (thisValue) {
1357 var args = this.args;
1358 for (var i = 0, l = args.length; i < l; ++i) {
1359 if (typeof args[i] === "function") {
1360 args[i].apply(thisValue, slice.call(arguments, 1));
1361 return;
1362 }
1363 }
1364 throwYieldError(this.proxy, " cannot yield since no callback was passed.", args);
1365 },
1366
1367 yieldTo: function (prop) {
1368 this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1)));
1369 },
1370
1371 yieldToOn: function (prop, thisValue) {
1372 var args = this.args;
1373 for (var i = 0, l = args.length; i < l; ++i) {
1374 if (args[i] && typeof args[i][prop] === "function") {
1375 args[i][prop].apply(thisValue, slice.call(arguments, 2));
1376 return;
1377 }
1378 }
1379 throwYieldError(this.proxy, " cannot yield to '" + prop +
1380 "' since no callback was passed.", args);
1381 },
1382
1383 toString: function () {
1384 var callStr = this.proxy.toString() + "(";
1385 var args = [];
1386
1387 for (var i = 0, l = this.args.length; i < l; ++i) {
1388 args.push(sinon.format(this.args[i]));
1389 }
1390
1391 callStr = callStr + args.join(", ") + ")";
1392
1393 if (typeof this.returnValue != "undefined") {
1394 callStr += " => " + sinon.format(this.returnValue);
1395 }
1396
1397 if (this.exception) {
1398 callStr += " !" + this.exception.name;
1399
1400 if (this.exception.message) {
1401 callStr += "(" + this.exception.message + ")";
1402 }
1403 }
1404
1405 return callStr;
1406 }
1407 };
1408
1409 callProto.invokeCallback = callProto.yield;
1410
1411 function createSpyCall(spy, thisValue, args, returnValue, exception, id) {
1412 if (typeof id !== "number") {
1413 throw new TypeError("Call id is not a number");
1414 }
1415 var proxyCall = sinon.create(callProto);
1416 proxyCall.proxy = spy;
1417 proxyCall.thisValue = thisValue;
1418 proxyCall.args = args;
1419 proxyCall.returnValue = returnValue;
1420 proxyCall.exception = exception;
1421 proxyCall.callId = id;
1422
1423 return proxyCall;
1424 }
1425 createSpyCall.toString = callProto.toString; // used by mocks
1426
1427 if (commonJSModule) {
1428 module.exports = createSpyCall;
1429 } else {
1430 sinon.spyCall = createSpyCall;
1431 }
1432 }(typeof sinon == "object" && sinon || null));
1433
1434
1435 /**
1436 * @depend ../sinon.js
1437 * @depend call.js
1438 */
1439 /*jslint eqeqeq: false, onevar: false, plusplus: false*/
1440 /*global module, require, sinon*/
1441 /**
1442 * Spy functions
1443 *
1444 * @author Christian Johansen (christian@cjohansen.no)
1445 * @license BSD
1446 *
1447 * Copyright (c) 2010-2013 Christian Johansen
1448 */
1449
1450 (function (sinon) {
1451 var commonJSModule = typeof module !== 'undefined' && module.exports;
1452 var push = Array.prototype.push;
1453 var slice = Array.prototype.slice;
1454 var callId = 0;
1455
1456 if (!sinon && commonJSModule) {
1457 sinon = require("../sinon");
1458 }
1459
1460 if (!sinon) {
1461 return;
1462 }
1463
1464 function spy(object, property) {
1465 if (!property && typeof object == "function") {
1466 return spy.create(object);
1467 }
1468
1469 if (!object && !property) {
1470 return spy.create(function () { });
1471 }
1472
1473 var method = object[property];
1474 return sinon.wrapMethod(object, property, spy.create(method));
1475 }
1476
1477 function matchingFake(fakes, args, strict) {
1478 if (!fakes) {
1479 return;
1480 }
1481
1482 for (var i = 0, l = fakes.length; i < l; i++) {
1483 if (fakes[i].matches(args, strict)) {
1484 return fakes[i];
1485 }
1486 }
1487 }
1488
1489 function incrementCallCount() {
1490 this.called = true;
1491 this.callCount += 1;
1492 this.notCalled = false;
1493 this.calledOnce = this.callCount == 1;
1494 this.calledTwice = this.callCount == 2;
1495 this.calledThrice = this.callCount == 3;
1496 }
1497
1498 function createCallProperties() {
1499 this.firstCall = this.getCall(0);
1500 this.secondCall = this.getCall(1);
1501 this.thirdCall = this.getCall(2);
1502 this.lastCall = this.getCall(this.callCount - 1);
1503 }
1504
1505 var vars = "a,b,c,d,e,f,g,h,i,j,k,l";
1506 function createProxy(func) {
1507 // Retain the function length:
1508 var p;
1509 if (func.length) {
1510 eval("p = (function proxy(" + vars.substring(0, func.length * 2 - 1) +
1511 ") { return p.invoke(func, this, slice.call(arguments)); });");
1512 }
1513 else {
1514 p = function proxy() {
1515 return p.invoke(func, this, slice.call(arguments));
1516 };
1517 }
1518 return p;
1519 }
1520
1521 var uuid = 0;
1522
1523 // Public API
1524 var spyApi = {
1525 reset: function () {
1526 this.called = false;
1527 this.notCalled = true;
1528 this.calledOnce = false;
1529 this.calledTwice = false;
1530 this.calledThrice = false;
1531 this.callCount = 0;
1532 this.firstCall = null;
1533 this.secondCall = null;
1534 this.thirdCall = null;
1535 this.lastCall = null;
1536 this.args = [];
1537 this.returnValues = [];
1538 this.thisValues = [];
1539 this.exceptions = [];
1540 this.callIds = [];
1541 if (this.fakes) {
1542 for (var i = 0; i < this.fakes.length; i++) {
1543 this.fakes[i].reset();
1544 }
1545 }
1546 },
1547
1548 create: function create(func) {
1549 var name;
1550
1551 if (typeof func != "function") {
1552 func = function () { };
1553 } else {
1554 name = sinon.functionName(func);
1555 }
1556
1557 var proxy = createProxy(func);
1558
1559 sinon.extend(proxy, spy);
1560 delete proxy.create;
1561 sinon.extend(proxy, func);
1562
1563 proxy.reset();
1564 proxy.prototype = func.prototype;
1565 proxy.displayName = name || "spy";
1566 proxy.toString = sinon.functionToString;
1567 proxy._create = sinon.spy.create;
1568 proxy.id = "spy#" + uuid++;
1569
1570 return proxy;
1571 },
1572
1573 invoke: function invoke(func, thisValue, args) {
1574 var matching = matchingFake(this.fakes, args);
1575 var exception, returnValue;
1576
1577 incrementCallCount.call(this);
1578 push.call(this.thisValues, thisValue);
1579 push.call(this.args, args);
1580 push.call(this.callIds, callId++);
1581
1582 try {
1583 if (matching) {
1584 returnValue = matching.invoke(func, thisValue, args);
1585 } else {
1586 returnValue = (this.func || func).apply(thisValue, args);
1587 }
1588
1589 var thisCall = this.getCall(this.callCount - 1);
1590 if (thisCall.calledWithNew() && typeof returnValue !== 'object') {
1591 returnValue = thisValue;
1592 }
1593 } catch (e) {
1594 exception = e;
1595 }
1596
1597 push.call(this.exceptions, exception);
1598 push.call(this.returnValues, returnValue);
1599
1600 createCallProperties.call(this);
1601
1602 if (exception !== undefined) {
1603 throw exception;
1604 }
1605
1606 return returnValue;
1607 },
1608
1609 getCall: function getCall(i) {
1610 if (i < 0 || i >= this.callCount) {
1611 return null;
1612 }
1613
1614 return sinon.spyCall(this, this.thisValues[i], this.args[i],
1615 this.returnValues[i], this.exceptions[i],
1616 this.callIds[i]);
1617 },
1618
1619 getCalls: function () {
1620 var calls = [];
1621 var i;
1622
1623 for (i = 0; i < this.callCount; i++) {
1624 calls.push(this.getCall(i));
1625 }
1626
1627 return calls;
1628 },
1629
1630 calledBefore: function calledBefore(spyFn) {
1631 if (!this.called) {
1632 return false;
1633 }
1634
1635 if (!spyFn.called) {
1636 return true;
1637 }
1638
1639 return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1];
1640 },
1641
1642 calledAfter: function calledAfter(spyFn) {
1643 if (!this.called || !spyFn.called) {
1644 return false;
1645 }
1646
1647 return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1];
1648 },
1649
1650 withArgs: function () {
1651 var args = slice.call(arguments);
1652
1653 if (this.fakes) {
1654 var match = matchingFake(this.fakes, args, true);
1655
1656 if (match) {
1657 return match;
1658 }
1659 } else {
1660 this.fakes = [];
1661 }
1662
1663 var original = this;
1664 var fake = this._create();
1665 fake.matchingAguments = args;
1666 fake.parent = this;
1667 push.call(this.fakes, fake);
1668
1669 fake.withArgs = function () {
1670 return original.withArgs.apply(original, arguments);
1671 };
1672
1673 for (var i = 0; i < this.args.length; i++) {
1674 if (fake.matches(this.args[i])) {
1675 incrementCallCount.call(fake);
1676 push.call(fake.thisValues, this.thisValues[i]);
1677 push.call(fake.args, this.args[i]);
1678 push.call(fake.returnValues, this.returnValues[i]);
1679 push.call(fake.exceptions, this.exceptions[i]);
1680 push.call(fake.callIds, this.callIds[i]);
1681 }
1682 }
1683 createCallProperties.call(fake);
1684
1685 return fake;
1686 },
1687
1688 matches: function (args, strict) {
1689 var margs = this.matchingAguments;
1690
1691 if (margs.length <= args.length &&
1692 sinon.deepEqual(margs, args.slice(0, margs.length))) {
1693 return !strict || margs.length == args.length;
1694 }
1695 },
1696
1697 printf: function (format) {
1698 var spy = this;
1699 var args = slice.call(arguments, 1);
1700 var formatter;
1701
1702 return (format || "").replace(/%(.)/g, function (match, specifyer) {
1703 formatter = spyApi.formatters[specifyer];
1704
1705 if (typeof formatter == "function") {
1706 return formatter.call(null, spy, args);
1707 } else if (!isNaN(parseInt(specifyer, 10))) {
1708 return sinon.format(args[specifyer - 1]);
1709 }
1710
1711 return "%" + specifyer;
1712 });
1713 }
1714 };
1715
1716 function delegateToCalls(method, matchAny, actual, notCalled) {
1717 spyApi[method] = function () {
1718 if (!this.called) {
1719 if (notCalled) {
1720 return notCalled.apply(this, arguments);
1721 }
1722 return false;
1723 }
1724
1725 var currentCall;
1726 var matches = 0;
1727
1728 for (var i = 0, l = this.callCount; i < l; i += 1) {
1729 currentCall = this.getCall(i);
1730
1731 if (currentCall[actual || method].apply(currentCall, arguments)) {
1732 matches += 1;
1733
1734 if (matchAny) {
1735 return true;
1736 }
1737 }
1738 }
1739
1740 return matches === this.callCount;
1741 };
1742 }
1743
1744 delegateToCalls("calledOn", true);
1745 delegateToCalls("alwaysCalledOn", false, "calledOn");
1746 delegateToCalls("calledWith", true);
1747 delegateToCalls("calledWithMatch", true);
1748 delegateToCalls("alwaysCalledWith", false, "calledWith");
1749 delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch");
1750 delegateToCalls("calledWithExactly", true);
1751 delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly");
1752 delegateToCalls("neverCalledWith", false, "notCalledWith",
1753 function () { return true; });
1754 delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch",
1755 function () { return true; });
1756 delegateToCalls("threw", true);
1757 delegateToCalls("alwaysThrew", false, "threw");
1758 delegateToCalls("returned", true);
1759 delegateToCalls("alwaysReturned", false, "returned");
1760 delegateToCalls("calledWithNew", true);
1761 delegateToCalls("alwaysCalledWithNew", false, "calledWithNew");
1762 delegateToCalls("callArg", false, "callArgWith", function () {
1763 throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
1764 });
1765 spyApi.callArgWith = spyApi.callArg;
1766 delegateToCalls("callArgOn", false, "callArgOnWith", function () {
1767 throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
1768 });
1769 spyApi.callArgOnWith = spyApi.callArgOn;
1770 delegateToCalls("yield", false, "yield", function () {
1771 throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
1772 });
1773 // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode.
1774 spyApi.invokeCallback = spyApi.yield;
1775 delegateToCalls("yieldOn", false, "yieldOn", function () {
1776 throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
1777 });
1778 delegateToCalls("yieldTo", false, "yieldTo", function (property) {
1779 throw new Error(this.toString() + " cannot yield to '" + property +
1780 "' since it was not yet invoked.");
1781 });
1782 delegateToCalls("yieldToOn", false, "yieldToOn", function (property) {
1783 throw new Error(this.toString() + " cannot yield to '" + property +
1784 "' since it was not yet invoked.");
1785 });
1786
1787 spyApi.formatters = {
1788 "c": function (spy) {
1789 return sinon.timesInWords(spy.callCount);
1790 },
1791
1792 "n": function (spy) {
1793 return spy.toString();
1794 },
1795
1796 "C": function (spy) {
1797 var calls = [];
1798
1799 for (var i = 0, l = spy.callCount; i < l; ++i) {
1800 var stringifiedCall = " " + spy.getCall(i).toString();
1801 if (/\n/.test(calls[i - 1])) {
1802 stringifiedCall = "\n" + stringifiedCall;
1803 }
1804 push.call(calls, stringifiedCall);
1805 }
1806
1807 return calls.length > 0 ? "\n" + calls.join("\n") : "";
1808 },
1809
1810 "t": function (spy) {
1811 var objects = [];
1812
1813 for (var i = 0, l = spy.callCount; i < l; ++i) {
1814 push.call(objects, sinon.format(spy.thisValues[i]));
1815 }
1816
1817 return objects.join(", ");
1818 },
1819
1820 "*": function (spy, args) {
1821 var formatted = [];
1822
1823 for (var i = 0, l = args.length; i < l; ++i) {
1824 push.call(formatted, sinon.format(args[i]));
1825 }
1826
1827 return formatted.join(", ");
1828 }
1829 };
1830
1831 sinon.extend(spy, spyApi);
1832
1833 spy.spyCall = sinon.spyCall;
1834
1835 if (commonJSModule) {
1836 module.exports = spy;
1837 } else {
1838 sinon.spy = spy;
1839 }
1840 }(typeof sinon == "object" && sinon || null));
1841
1842 /**
1843 * @depend ../sinon.js
1844 */
1845 /*jslint eqeqeq: false, onevar: false*/
1846 /*global module, require, sinon, process, setImmediate, setTimeout*/
1847 /**
1848 * Stub behavior
1849 *
1850 * @author Christian Johansen (christian@cjohansen.no)
1851 * @author Tim Fischbach (mail@timfischbach.de)
1852 * @license BSD
1853 *
1854 * Copyright (c) 2010-2013 Christian Johansen
1855 */
1856
1857 (function (sinon) {
1858 var commonJSModule = typeof module !== 'undefined' && module.exports;
1859
1860 if (!sinon && commonJSModule) {
1861 sinon = require("../sinon");
1862 }
1863
1864 if (!sinon) {
1865 return;
1866 }
1867
1868 var slice = Array.prototype.slice;
1869 var join = Array.prototype.join;
1870 var proto;
1871
1872 var nextTick = (function () {
1873 if (typeof process === "object" && typeof process.nextTick === "function") {
1874 return process.nextTick;
1875 } else if (typeof setImmediate === "function") {
1876 return setImmediate;
1877 } else {
1878 return function (callback) {
1879 setTimeout(callback, 0);
1880 };
1881 }
1882 })();
1883
1884 function throwsException(error, message) {
1885 if (typeof error == "string") {
1886 this.exception = new Error(message || "");
1887 this.exception.name = error;
1888 } else if (!error) {
1889 this.exception = new Error("Error");
1890 } else {
1891 this.exception = error;
1892 }
1893
1894 return this;
1895 }
1896
1897 function getCallback(behavior, args) {
1898 var callArgAt = behavior.callArgAt;
1899
1900 if (callArgAt < 0) {
1901 var callArgProp = behavior.callArgProp;
1902
1903 for (var i = 0, l = args.length; i < l; ++i) {
1904 if (!callArgProp && typeof args[i] == "function") {
1905 return args[i];
1906 }
1907
1908 if (callArgProp && args[i] &&
1909 typeof args[i][callArgProp] == "function") {
1910 return args[i][callArgProp];
1911 }
1912 }
1913
1914 return null;
1915 }
1916
1917 return args[callArgAt];
1918 }
1919
1920 function getCallbackError(behavior, func, args) {
1921 if (behavior.callArgAt < 0) {
1922 var msg;
1923
1924 if (behavior.callArgProp) {
1925 msg = sinon.functionName(behavior.stub) +
1926 " expected to yield to '" + behavior.callArgProp +
1927 "', but no object with such a property was passed.";
1928 } else {
1929 msg = sinon.functionName(behavior.stub) +
1930 " expected to yield, but no callback was passed.";
1931 }
1932
1933 if (args.length > 0) {
1934 msg += " Received [" + join.call(args, ", ") + "]";
1935 }
1936
1937 return msg;
1938 }
1939
1940 return "argument at index " + behavior.callArgAt + " is not a function: " + func;
1941 }
1942
1943 function callCallback(behavior, args) {
1944 if (typeof behavior.callArgAt == "number") {
1945 var func = getCallback(behavior, args);
1946
1947 if (typeof func != "function") {
1948 throw new TypeError(getCallbackError(behavior, func, args));
1949 }
1950
1951 if (behavior.callbackAsync) {
1952 nextTick(function() {
1953 func.apply(behavior.callbackContext, behavior.callbackArguments);
1954 });
1955 } else {
1956 func.apply(behavior.callbackContext, behavior.callbackArguments);
1957 }
1958 }
1959 }
1960
1961 proto = {
1962 create: function(stub) {
1963 var behavior = sinon.extend({}, sinon.behavior);
1964 delete behavior.create;
1965 behavior.stub = stub;
1966
1967 return behavior;
1968 },
1969
1970 isPresent: function() {
1971 return (typeof this.callArgAt == 'number' ||
1972 this.exception ||
1973 typeof this.returnArgAt == 'number' ||
1974 this.returnThis ||
1975 this.returnValueDefined);
1976 },
1977
1978 invoke: function(context, args) {
1979 callCallback(this, args);
1980
1981 if (this.exception) {
1982 throw this.exception;
1983 } else if (typeof this.returnArgAt == 'number') {
1984 return args[this.returnArgAt];
1985 } else if (this.returnThis) {
1986 return context;
1987 }
1988
1989 return this.returnValue;
1990 },
1991
1992 onCall: function(index) {
1993 return this.stub.onCall(index);
1994 },
1995
1996 onFirstCall: function() {
1997 return this.stub.onFirstCall();
1998 },
1999
2000 onSecondCall: function() {
2001 return this.stub.onSecondCall();
2002 },
2003
2004 onThirdCall: function() {
2005 return this.stub.onThirdCall();
2006 },
2007
2008 withArgs: function(/* arguments */) {
2009 throw new Error('Defining a stub by invoking "stub.onCall(...).withArgs(...)" is not supported. ' +
2010 'Use "stub.withArgs(...).onCall(...)" to define sequential behavior for calls with certain arguments.');
2011 },
2012
2013 callsArg: function callsArg(pos) {
2014 if (typeof pos != "number") {
2015 throw new TypeError("argument index is not number");
2016 }
2017
2018 this.callArgAt = pos;
2019 this.callbackArguments = [];
2020 this.callbackContext = undefined;
2021 this.callArgProp = undefined;
2022 this.callbackAsync = false;
2023
2024 return this;
2025 },
2026
2027 callsArgOn: function callsArgOn(pos, context) {
2028 if (typeof pos != "number") {
2029 throw new TypeError("argument index is not number");
2030 }
2031 if (typeof context != "object") {
2032 throw new TypeError("argument context is not an object");
2033 }
2034
2035 this.callArgAt = pos;
2036 this.callbackArguments = [];
2037 this.callbackContext = context;
2038 this.callArgProp = undefined;
2039 this.callbackAsync = false;
2040
2041 return this;
2042 },
2043
2044 callsArgWith: function callsArgWith(pos) {
2045 if (typeof pos != "number") {
2046 throw new TypeError("argument index is not number");
2047 }
2048
2049 this.callArgAt = pos;
2050 this.callbackArguments = slice.call(arguments, 1);
2051 this.callbackContext = undefined;
2052 this.callArgProp = undefined;
2053 this.callbackAsync = false;
2054
2055 return this;
2056 },
2057
2058 callsArgOnWith: function callsArgWith(pos, context) {
2059 if (typeof pos != "number") {
2060 throw new TypeError("argument index is not number");
2061 }
2062 if (typeof context != "object") {
2063 throw new TypeError("argument context is not an object");
2064 }
2065
2066 this.callArgAt = pos;
2067 this.callbackArguments = slice.call(arguments, 2);
2068 this.callbackContext = context;
2069 this.callArgProp = undefined;
2070 this.callbackAsync = false;
2071
2072 return this;
2073 },
2074
2075 yields: function () {
2076 this.callArgAt = -1;
2077 this.callbackArguments = slice.call(arguments, 0);
2078 this.callbackContext = undefined;
2079 this.callArgProp = undefined;
2080 this.callbackAsync = false;
2081
2082 return this;
2083 },
2084
2085 yieldsOn: function (context) {
2086 if (typeof context != "object") {
2087 throw new TypeError("argument context is not an object");
2088 }
2089
2090 this.callArgAt = -1;
2091 this.callbackArguments = slice.call(arguments, 1);
2092 this.callbackContext = context;
2093 this.callArgProp = undefined;
2094 this.callbackAsync = false;
2095
2096 return this;
2097 },
2098
2099 yieldsTo: function (prop) {
2100 this.callArgAt = -1;
2101 this.callbackArguments = slice.call(arguments, 1);
2102 this.callbackContext = undefined;
2103 this.callArgProp = prop;
2104 this.callbackAsync = false;
2105
2106 return this;
2107 },
2108
2109 yieldsToOn: function (prop, context) {
2110 if (typeof context != "object") {
2111 throw new TypeError("argument context is not an object");
2112 }
2113
2114 this.callArgAt = -1;
2115 this.callbackArguments = slice.call(arguments, 2);
2116 this.callbackContext = context;
2117 this.callArgProp = prop;
2118 this.callbackAsync = false;
2119
2120 return this;
2121 },
2122
2123
2124 "throws": throwsException,
2125 throwsException: throwsException,
2126
2127 returns: function returns(value) {
2128 this.returnValue = value;
2129 this.returnValueDefined = true;
2130
2131 return this;
2132 },
2133
2134 returnsArg: function returnsArg(pos) {
2135 if (typeof pos != "number") {
2136 throw new TypeError("argument index is not number");
2137 }
2138
2139 this.returnArgAt = pos;
2140
2141 return this;
2142 },
2143
2144 returnsThis: function returnsThis() {
2145 this.returnThis = true;
2146
2147 return this;
2148 }
2149 };
2150
2151 // create asynchronous versions of callsArg* and yields* methods
2152 for (var method in proto) {
2153 // need to avoid creating anotherasync versions of the newly added async methods
2154 if (proto.hasOwnProperty(method) &&
2155 method.match(/^(callsArg|yields)/) &&
2156 !method.match(/Async/)) {
2157 proto[method + 'Async'] = (function (syncFnName) {
2158 return function () {
2159 var result = this[syncFnName].apply(this, arguments);
2160 this.callbackAsync = true;
2161 return result;
2162 };
2163 })(method);
2164 }
2165 }
2166
2167 if (commonJSModule) {
2168 module.exports = proto;
2169 } else {
2170 sinon.behavior = proto;
2171 }
2172 }(typeof sinon == "object" && sinon || null));
2173 /**
2174 * @depend ../sinon.js
2175 * @depend spy.js
2176 * @depend behavior.js
2177 */
2178 /*jslint eqeqeq: false, onevar: false*/
2179 /*global module, require, sinon*/
2180 /**
2181 * Stub functions
2182 *
2183 * @author Christian Johansen (christian@cjohansen.no)
2184 * @license BSD
2185 *
2186 * Copyright (c) 2010-2013 Christian Johansen
2187 */
2188
2189 (function (sinon) {
2190 var commonJSModule = typeof module !== 'undefined' && module.exports;
2191
2192 if (!sinon && commonJSModule) {
2193 sinon = require("../sinon");
2194 }
2195
2196 if (!sinon) {
2197 return;
2198 }
2199
2200 function stub(object, property, func) {
2201 if (!!func && typeof func != "function") {
2202 throw new TypeError("Custom stub should be function");
2203 }
2204
2205 var wrapper;
2206
2207 if (func) {
2208 wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func;
2209 } else {
2210 wrapper = stub.create();
2211 }
2212
2213 if (!object && typeof property === "undefined") {
2214 return sinon.stub.create();
2215 }
2216
2217 if (typeof property === "undefined" && typeof object == "object") {
2218 for (var prop in object) {
2219 if (typeof object[prop] === "function") {
2220 stub(object, prop);
2221 }
2222 }
2223
2224 return object;
2225 }
2226
2227 return sinon.wrapMethod(object, property, wrapper);
2228 }
2229
2230 function getDefaultBehavior(stub) {
2231 return stub.defaultBehavior || getParentBehaviour(stub) || sinon.behavior.create(stub);
2232 }
2233
2234 function getParentBehaviour(stub) {
2235 return (stub.parent && getCurrentBehavior(stub.parent));
2236 }
2237
2238 function getCurrentBehavior(stub) {
2239 var behavior = stub.behaviors[stub.callCount - 1];
2240 return behavior && behavior.isPresent() ? behavior : getDefaultBehavior(stub);
2241 }
2242
2243 var uuid = 0;
2244
2245 sinon.extend(stub, (function () {
2246 var proto = {
2247 create: function create() {
2248 var functionStub = function () {
2249 return getCurrentBehavior(functionStub).invoke(this, arguments);
2250 };
2251
2252 functionStub.id = "stub#" + uuid++;
2253 var orig = functionStub;
2254 functionStub = sinon.spy.create(functionStub);
2255 functionStub.func = orig;
2256
2257 sinon.extend(functionStub, stub);
2258 functionStub._create = sinon.stub.create;
2259 functionStub.displayName = "stub";
2260 functionStub.toString = sinon.functionToString;
2261
2262 functionStub.defaultBehavior = null;
2263 functionStub.behaviors = [];
2264
2265 return functionStub;
2266 },
2267
2268 resetBehavior: function () {
2269 var i;
2270
2271 this.defaultBehavior = null;
2272 this.behaviors = [];
2273
2274 delete this.returnValue;
2275 delete this.returnArgAt;
2276 this.returnThis = false;
2277
2278 if (this.fakes) {
2279 for (i = 0; i < this.fakes.length; i++) {
2280 this.fakes[i].resetBehavior();
2281 }
2282 }
2283 },
2284
2285 onCall: function(index) {
2286 if (!this.behaviors[index]) {
2287 this.behaviors[index] = sinon.behavior.create(this);
2288 }
2289
2290 return this.behaviors[index];
2291 },
2292
2293 onFirstCall: function() {
2294 return this.onCall(0);
2295 },
2296
2297 onSecondCall: function() {
2298 return this.onCall(1);
2299 },
2300
2301 onThirdCall: function() {
2302 return this.onCall(2);
2303 }
2304 };
2305
2306 for (var method in sinon.behavior) {
2307 if (sinon.behavior.hasOwnProperty(method) &&
2308 !proto.hasOwnProperty(method) &&
2309 method != 'create' &&
2310 method != 'withArgs' &&
2311 method != 'invoke') {
2312 proto[method] = (function(behaviorMethod) {
2313 return function() {
2314 this.defaultBehavior = this.defaultBehavior || sinon.behavior.create(this);
2315 this.defaultBehavior[behaviorMethod].apply(this.defaultBehavior, arguments);
2316 return this;
2317 };
2318 }(method));
2319 }
2320 }
2321
2322 return proto;
2323 }()));
2324
2325 if (commonJSModule) {
2326 module.exports = stub;
2327 } else {
2328 sinon.stub = stub;
2329 }
2330 }(typeof sinon == "object" && sinon || null));
2331
2332 /**
2333 * @depend ../sinon.js
2334 * @depend stub.js
2335 */
2336 /*jslint eqeqeq: false, onevar: false, nomen: false*/
2337 /*global module, require, sinon*/
2338 /**
2339 * Mock functions.
2340 *
2341 * @author Christian Johansen (christian@cjohansen.no)
2342 * @license BSD
2343 *
2344 * Copyright (c) 2010-2013 Christian Johansen
2345 */
2346
2347 (function (sinon) {
2348 var commonJSModule = typeof module !== 'undefined' && module.exports;
2349 var push = [].push;
2350 var match;
2351
2352 if (!sinon && commonJSModule) {
2353 sinon = require("../sinon");
2354 }
2355
2356 if (!sinon) {
2357 return;
2358 }
2359
2360 match = sinon.match;
2361
2362 if (!match && commonJSModule) {
2363 match = require("./match");
2364 }
2365
2366 function mock(object) {
2367 if (!object) {
2368 return sinon.expectation.create("Anonymous mock");
2369 }
2370
2371 return mock.create(object);
2372 }
2373
2374 sinon.mock = mock;
2375
2376 sinon.extend(mock, (function () {
2377 function each(collection, callback) {
2378 if (!collection) {
2379 return;
2380 }
2381
2382 for (var i = 0, l = collection.length; i < l; i += 1) {
2383 callback(collection[i]);
2384 }
2385 }
2386
2387 return {
2388 create: function create(object) {
2389 if (!object) {
2390 throw new TypeError("object is null");
2391 }
2392
2393 var mockObject = sinon.extend({}, mock);
2394 mockObject.object = object;
2395 delete mockObject.create;
2396
2397 return mockObject;
2398 },
2399
2400 expects: function expects(method) {
2401 if (!method) {
2402 throw new TypeError("method is falsy");
2403 }
2404
2405 if (!this.expectations) {
2406 this.expectations = {};
2407 this.proxies = [];
2408 }
2409
2410 if (!this.expectations[method]) {
2411 this.expectations[method] = [];
2412 var mockObject = this;
2413
2414 sinon.wrapMethod(this.object, method, function () {
2415 return mockObject.invokeMethod(method, this, arguments);
2416 });
2417
2418 push.call(this.proxies, method);
2419 }
2420
2421 var expectation = sinon.expectation.create(method);
2422 push.call(this.expectations[method], expectation);
2423
2424 return expectation;
2425 },
2426
2427 restore: function restore() {
2428 var object = this.object;
2429
2430 each(this.proxies, function (proxy) {
2431 if (typeof object[proxy].restore == "function") {
2432 object[proxy].restore();
2433 }
2434 });
2435 },
2436
2437 verify: function verify() {
2438 var expectations = this.expectations || {};
2439 var messages = [], met = [];
2440
2441 each(this.proxies, function (proxy) {
2442 each(expectations[proxy], function (expectation) {
2443 if (!expectation.met()) {
2444 push.call(messages, expectation.toString());
2445 } else {
2446 push.call(met, expectation.toString());
2447 }
2448 });
2449 });
2450
2451 this.restore();
2452
2453 if (messages.length > 0) {
2454 sinon.expectation.fail(messages.concat(met).join("\n"));
2455 } else {
2456 sinon.expectation.pass(messages.concat(met).join("\n"));
2457 }
2458
2459 return true;
2460 },
2461
2462 invokeMethod: function invokeMethod(method, thisValue, args) {
2463 var expectations = this.expectations && this.expectations[method];
2464 var length = expectations && expectations.length || 0, i;
2465
2466 for (i = 0; i < length; i += 1) {
2467 if (!expectations[i].met() &&
2468 expectations[i].allowsCall(thisValue, args)) {
2469 return expectations[i].apply(thisValue, args);
2470 }
2471 }
2472
2473 var messages = [], available, exhausted = 0;
2474
2475 for (i = 0; i < length; i += 1) {
2476 if (expectations[i].allowsCall(thisValue, args)) {
2477 available = available || expectations[i];
2478 } else {
2479 exhausted += 1;
2480 }
2481 push.call(messages, " " + expectations[i].toString());
2482 }
2483
2484 if (exhausted === 0) {
2485 return available.apply(thisValue, args);
2486 }
2487
2488 messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({
2489 proxy: method,
2490 args: args
2491 }));
2492
2493 sinon.expectation.fail(messages.join("\n"));
2494 }
2495 };
2496 }()));
2497
2498 var times = sinon.timesInWords;
2499
2500 sinon.expectation = (function () {
2501 var slice = Array.prototype.slice;
2502 var _invoke = sinon.spy.invoke;
2503
2504 function callCountInWords(callCount) {
2505 if (callCount == 0) {
2506 return "never called";
2507 } else {
2508 return "called " + times(callCount);
2509 }
2510 }
2511
2512 function expectedCallCountInWords(expectation) {
2513 var min = expectation.minCalls;
2514 var max = expectation.maxCalls;
2515
2516 if (typeof min == "number" && typeof max == "number") {
2517 var str = times(min);
2518
2519 if (min != max) {
2520 str = "at least " + str + " and at most " + times(max);
2521 }
2522
2523 return str;
2524 }
2525
2526 if (typeof min == "number") {
2527 return "at least " + times(min);
2528 }
2529
2530 return "at most " + times(max);
2531 }
2532
2533 function receivedMinCalls(expectation) {
2534 var hasMinLimit = typeof expectation.minCalls == "number";
2535 return !hasMinLimit || expectation.callCount >= expectation.minCalls;
2536 }
2537
2538 function receivedMaxCalls(expectation) {
2539 if (typeof expectation.maxCalls != "number") {
2540 return false;
2541 }
2542
2543 return expectation.callCount == expectation.maxCalls;
2544 }
2545
2546 function verifyMatcher(possibleMatcher, arg){
2547 if (match && match.isMatcher(possibleMatcher)) {
2548 return possibleMatcher.test(arg);
2549 } else {
2550 return true;
2551 }
2552 }
2553
2554 return {
2555 minCalls: 1,
2556 maxCalls: 1,
2557
2558 create: function create(methodName) {
2559 var expectation = sinon.extend(sinon.stub.create(), sinon.expectation);
2560 delete expectation.create;
2561 expectation.method = methodName;
2562
2563 return expectation;
2564 },
2565
2566 invoke: function invoke(func, thisValue, args) {
2567 this.verifyCallAllowed(thisValue, args);
2568
2569 return _invoke.apply(this, arguments);
2570 },
2571
2572 atLeast: function atLeast(num) {
2573 if (typeof num != "number") {
2574 throw new TypeError("'" + num + "' is not number");
2575 }
2576
2577 if (!this.limitsSet) {
2578 this.maxCalls = null;
2579 this.limitsSet = true;
2580 }
2581
2582 this.minCalls = num;
2583
2584 return this;
2585 },
2586
2587 atMost: function atMost(num) {
2588 if (typeof num != "number") {
2589 throw new TypeError("'" + num + "' is not number");
2590 }
2591
2592 if (!this.limitsSet) {
2593 this.minCalls = null;
2594 this.limitsSet = true;
2595 }
2596
2597 this.maxCalls = num;
2598
2599 return this;
2600 },
2601
2602 never: function never() {
2603 return this.exactly(0);
2604 },
2605
2606 once: function once() {
2607 return this.exactly(1);
2608 },
2609
2610 twice: function twice() {
2611 return this.exactly(2);
2612 },
2613
2614 thrice: function thrice() {
2615 return this.exactly(3);
2616 },
2617
2618 exactly: function exactly(num) {
2619 if (typeof num != "number") {
2620 throw new TypeError("'" + num + "' is not a number");
2621 }
2622
2623 this.atLeast(num);
2624 return this.atMost(num);
2625 },
2626
2627 met: function met() {
2628 return !this.failed && receivedMinCalls(this);
2629 },
2630
2631 verifyCallAllowed: function verifyCallAllowed(thisValue, args) {
2632 if (receivedMaxCalls(this)) {
2633 this.failed = true;
2634 sinon.expectation.fail(this.method + " already called " + times(this.maxCalls));
2635 }
2636
2637 if ("expectedThis" in this && this.expectedThis !== thisValue) {
2638 sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " +
2639 this.expectedThis);
2640 }
2641
2642 if (!("expectedArguments" in this)) {
2643 return;
2644 }
2645
2646 if (!args) {
2647 sinon.expectation.fail(this.method + " received no arguments, expected " +
2648 sinon.format(this.expectedArguments));
2649 }
2650
2651 if (args.length < this.expectedArguments.length) {
2652 sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) +
2653 "), expected " + sinon.format(this.expectedArguments));
2654 }
2655
2656 if (this.expectsExactArgCount &&
2657 args.length != this.expectedArguments.length) {
2658 sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) +
2659 "), expected " + sinon.format(this.expectedArguments));
2660 }
2661
2662 for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
2663
2664 if (!verifyMatcher(this.expectedArguments[i],args[i])) {
2665 sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) +
2666 ", didn't match " + this.expectedArguments.toString());
2667 }
2668
2669 if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
2670 sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) +
2671 ", expected " + sinon.format(this.expectedArguments));
2672 }
2673 }
2674 },
2675
2676 allowsCall: function allowsCall(thisValue, args) {
2677 if (this.met() && receivedMaxCalls(this)) {
2678 return false;
2679 }
2680
2681 if ("expectedThis" in this && this.expectedThis !== thisValue) {
2682 return false;
2683 }
2684
2685 if (!("expectedArguments" in this)) {
2686 return true;
2687 }
2688
2689 args = args || [];
2690
2691 if (args.length < this.expectedArguments.length) {
2692 return false;
2693 }
2694
2695 if (this.expectsExactArgCount &&
2696 args.length != this.expectedArguments.length) {
2697 return false;
2698 }
2699
2700 for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
2701 if (!verifyMatcher(this.expectedArguments[i],args[i])) {
2702 return false;
2703 }
2704
2705 if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
2706 return false;
2707 }
2708 }
2709
2710 return true;
2711 },
2712
2713 withArgs: function withArgs() {
2714 this.expectedArguments = slice.call(arguments);
2715 return this;
2716 },
2717
2718 withExactArgs: function withExactArgs() {
2719 this.withArgs.apply(this, arguments);
2720 this.expectsExactArgCount = true;
2721 return this;
2722 },
2723
2724 on: function on(thisValue) {
2725 this.expectedThis = thisValue;
2726 return this;
2727 },
2728
2729 toString: function () {
2730 var args = (this.expectedArguments || []).slice();
2731
2732 if (!this.expectsExactArgCount) {
2733 push.call(args, "[...]");
2734 }
2735
2736 var callStr = sinon.spyCall.toString.call({
2737 proxy: this.method || "anonymous mock expectation",
2738 args: args
2739 });
2740
2741 var message = callStr.replace(", [...", "[, ...") + " " +
2742 expectedCallCountInWords(this);
2743
2744 if (this.met()) {
2745 return "Expectation met: " + message;
2746 }
2747
2748 return "Expected " + message + " (" +
2749 callCountInWords(this.callCount) + ")";
2750 },
2751
2752 verify: function verify() {
2753 if (!this.met()) {
2754 sinon.expectation.fail(this.toString());
2755 } else {
2756 sinon.expectation.pass(this.toString());
2757 }
2758
2759 return true;
2760 },
2761
2762 pass: function(message) {
2763 sinon.assert.pass(message);
2764 },
2765 fail: function (message) {
2766 var exception = new Error(message);
2767 exception.name = "ExpectationError";
2768
2769 throw exception;
2770 }
2771 };
2772 }());
2773
2774 if (commonJSModule) {
2775 module.exports = mock;
2776 } else {
2777 sinon.mock = mock;
2778 }
2779 }(typeof sinon == "object" && sinon || null));
2780
2781 /**
2782 * @depend ../sinon.js
2783 * @depend stub.js
2784 * @depend mock.js
2785 */
2786 /*jslint eqeqeq: false, onevar: false, forin: true*/
2787 /*global module, require, sinon*/
2788 /**
2789 * Collections of stubs, spies and mocks.
2790 *
2791 * @author Christian Johansen (christian@cjohansen.no)
2792 * @license BSD
2793 *
2794 * Copyright (c) 2010-2013 Christian Johansen
2795 */
2796
2797 (function (sinon) {
2798 var commonJSModule = typeof module !== 'undefined' && module.exports;
2799 var push = [].push;
2800 var hasOwnProperty = Object.prototype.hasOwnProperty;
2801
2802 if (!sinon && commonJSModule) {
2803 sinon = require("../sinon");
2804 }
2805
2806 if (!sinon) {
2807 return;
2808 }
2809
2810 function getFakes(fakeCollection) {
2811 if (!fakeCollection.fakes) {
2812 fakeCollection.fakes = [];
2813 }
2814
2815 return fakeCollection.fakes;
2816 }
2817
2818 function each(fakeCollection, method) {
2819 var fakes = getFakes(fakeCollection);
2820
2821 for (var i = 0, l = fakes.length; i < l; i += 1) {
2822 if (typeof fakes[i][method] == "function") {
2823 fakes[i][method]();
2824 }
2825 }
2826 }
2827
2828 function compact(fakeCollection) {
2829 var fakes = getFakes(fakeCollection);
2830 var i = 0;
2831 while (i < fakes.length) {
2832 fakes.splice(i, 1);
2833 }
2834 }
2835
2836 var collection = {
2837 verify: function resolve() {
2838 each(this, "verify");
2839 },
2840
2841 restore: function restore() {
2842 each(this, "restore");
2843 compact(this);
2844 },
2845
2846 verifyAndRestore: function verifyAndRestore() {
2847 var exception;
2848
2849 try {
2850 this.verify();
2851 } catch (e) {
2852 exception = e;
2853 }
2854
2855 this.restore();
2856
2857 if (exception) {
2858 throw exception;
2859 }
2860 },
2861
2862 add: function add(fake) {
2863 push.call(getFakes(this), fake);
2864 return fake;
2865 },
2866
2867 spy: function spy() {
2868 return this.add(sinon.spy.apply(sinon, arguments));
2869 },
2870
2871 stub: function stub(object, property, value) {
2872 if (property) {
2873 var original = object[property];
2874
2875 if (typeof original != "function") {
2876 if (!hasOwnProperty.call(object, property)) {
2877 throw new TypeError("Cannot stub non-existent own property " + property);
2878 }
2879
2880 object[property] = value;
2881
2882 return this.add({
2883 restore: function () {
2884 object[property] = original;
2885 }
2886 });
2887 }
2888 }
2889 if (!property && !!object && typeof object == "object") {
2890 var stubbedObj = sinon.stub.apply(sinon, arguments);
2891
2892 for (var prop in stubbedObj) {
2893 if (typeof stubbedObj[prop] === "function") {
2894 this.add(stubbedObj[prop]);
2895 }
2896 }
2897
2898 return stubbedObj;
2899 }
2900
2901 return this.add(sinon.stub.apply(sinon, arguments));
2902 },
2903
2904 mock: function mock() {
2905 return this.add(sinon.mock.apply(sinon, arguments));
2906 },
2907
2908 inject: function inject(obj) {
2909 var col = this;
2910
2911 obj.spy = function () {
2912 return col.spy.apply(col, arguments);
2913 };
2914
2915 obj.stub = function () {
2916 return col.stub.apply(col, arguments);
2917 };
2918
2919 obj.mock = function () {
2920 return col.mock.apply(col, arguments);
2921 };
2922
2923 return obj;
2924 }
2925 };
2926
2927 if (commonJSModule) {
2928 module.exports = collection;
2929 } else {
2930 sinon.collection = collection;
2931 }
2932 }(typeof sinon == "object" && sinon || null));
2933
2934 /*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/
2935 /*global module, require, window*/
2936 /**
2937 * Fake timer API
2938 * setTimeout
2939 * setInterval
2940 * clearTimeout
2941 * clearInterval
2942 * tick
2943 * reset
2944 * Date
2945 *
2946 * Inspired by jsUnitMockTimeOut from JsUnit
2947 *
2948 * @author Christian Johansen (christian@cjohansen.no)
2949 * @license BSD
2950 *
2951 * Copyright (c) 2010-2013 Christian Johansen
2952 */
2953
2954 if (typeof sinon == "undefined") {
2955 var sinon = {};
2956 }
2957
2958 (function (global) {
2959 var id = 1;
2960
2961 function addTimer(args, recurring) {
2962 if (args.length === 0) {
2963 throw new Error("Function requires at least 1 parameter");
2964 }
2965
2966 if (typeof args[0] === "undefined") {
2967 throw new Error("Callback must be provided to timer calls");
2968 }
2969
2970 var toId = id++;
2971 var delay = args[1] || 0;
2972
2973 if (!this.timeouts) {
2974 this.timeouts = {};
2975 }
2976
2977 this.timeouts[toId] = {
2978 id: toId,
2979 func: args[0],
2980 callAt: this.now + delay,
2981 invokeArgs: Array.prototype.slice.call(args, 2)
2982 };
2983
2984 if (recurring === true) {
2985 this.timeouts[toId].interval = delay;
2986 }
2987
2988 return toId;
2989 }
2990
2991 function parseTime(str) {
2992 if (!str) {
2993 return 0;
2994 }
2995
2996 var strings = str.split(":");
2997 var l = strings.length, i = l;
2998 var ms = 0, parsed;
2999
3000 if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
3001 throw new Error("tick only understands numbers and 'h:m:s'");
3002 }
3003
3004 while (i--) {
3005 parsed = parseInt(strings[i], 10);
3006
3007 if (parsed >= 60) {
3008 throw new Error("Invalid time " + str);
3009 }
3010
3011 ms += parsed * Math.pow(60, (l - i - 1));
3012 }
3013
3014 return ms * 1000;
3015 }
3016
3017 function createObject(object) {
3018 var newObject;
3019
3020 if (Object.create) {
3021 newObject = Object.create(object);
3022 } else {
3023 var F = function () {};
3024 F.prototype = object;
3025 newObject = new F();
3026 }
3027
3028 newObject.Date.clock = newObject;
3029 return newObject;
3030 }
3031
3032 sinon.clock = {
3033 now: 0,
3034
3035 create: function create(now) {
3036 var clock = createObject(this);
3037
3038 if (typeof now == "number") {
3039 clock.now = now;
3040 }
3041
3042 if (!!now && typeof now == "object") {
3043 throw new TypeError("now should be milliseconds since UNIX epoch");
3044 }
3045
3046 return clock;
3047 },
3048
3049 setTimeout: function setTimeout(callback, timeout) {
3050 return addTimer.call(this, arguments, false);
3051 },
3052
3053 clearTimeout: function clearTimeout(timerId) {
3054 if (!this.timeouts) {
3055 this.timeouts = [];
3056 }
3057
3058 if (timerId in this.timeouts) {
3059 delete this.timeouts[timerId];
3060 }
3061 },
3062
3063 setInterval: function setInterval(callback, timeout) {
3064 return addTimer.call(this, arguments, true);
3065 },
3066
3067 clearInterval: function clearInterval(timerId) {
3068 this.clearTimeout(timerId);
3069 },
3070
3071 setImmediate: function setImmediate(callback) {
3072 var passThruArgs = Array.prototype.slice.call(arguments, 1);
3073
3074 return addTimer.call(this, [callback, 0].concat(passThruArgs), false);
3075 },
3076
3077 clearImmediate: function clearImmediate(timerId) {
3078 this.clearTimeout(timerId);
3079 },
3080
3081 tick: function tick(ms) {
3082 ms = typeof ms == "number" ? ms : parseTime(ms);
3083 var tickFrom = this.now, tickTo = this.now + ms, previous = this.now;
3084 var timer = this.firstTimerInRange(tickFrom, tickTo);
3085
3086 var firstException;
3087 while (timer && tickFrom <= tickTo) {
3088 if (this.timeouts[timer.id]) {
3089 tickFrom = this.now = timer.callAt;
3090 try {
3091 this.callTimer(timer);
3092 } catch (e) {
3093 firstException = firstException || e;
3094 }
3095 }
3096
3097 timer = this.firstTimerInRange(previous, tickTo);
3098 previous = tickFrom;
3099 }
3100
3101 this.now = tickTo;
3102
3103 if (firstException) {
3104 throw firstException;
3105 }
3106
3107 return this.now;
3108 },
3109
3110 firstTimerInRange: function (from, to) {
3111 var timer, smallest = null, originalTimer;
3112
3113 for (var id in this.timeouts) {
3114 if (this.timeouts.hasOwnProperty(id)) {
3115 if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) {
3116 continue;
3117 }
3118
3119 if (smallest === null || this.timeouts[id].callAt < smallest) {
3120 originalTimer = this.timeouts[id];
3121 smallest = this.timeouts[id].callAt;
3122
3123 timer = {
3124 func: this.timeouts[id].func,
3125 callAt: this.timeouts[id].callAt,
3126 interval: this.timeouts[id].interval,
3127 id: this.timeouts[id].id,
3128 invokeArgs: this.timeouts[id].invokeArgs
3129 };
3130 }
3131 }
3132 }
3133
3134 return timer || null;
3135 },
3136
3137 callTimer: function (timer) {
3138 if (typeof timer.interval == "number") {
3139 this.timeouts[timer.id].callAt += timer.interval;
3140 } else {
3141 delete this.timeouts[timer.id];
3142 }
3143
3144 try {
3145 if (typeof timer.func == "function") {
3146 timer.func.apply(null, timer.invokeArgs);
3147 } else {
3148 eval(timer.func);
3149 }
3150 } catch (e) {
3151 var exception = e;
3152 }
3153
3154 if (!this.timeouts[timer.id]) {
3155 if (exception) {
3156 throw exception;
3157 }
3158 return;
3159 }
3160
3161 if (exception) {
3162 throw exception;
3163 }
3164 },
3165
3166 reset: function reset() {
3167 this.timeouts = {};
3168 },
3169
3170 Date: (function () {
3171 var NativeDate = Date;
3172
3173 function ClockDate(year, month, date, hour, minute, second, ms) {
3174 // Defensive and verbose to avoid potential harm in passing
3175 // explicit undefined when user does not pass argument
3176 switch (arguments.length) {
3177 case 0:
3178 return new NativeDate(ClockDate.clock.now);
3179 case 1:
3180 return new NativeDate(year);
3181 case 2:
3182 return new NativeDate(year, month);
3183 case 3:
3184 return new NativeDate(year, month, date);
3185 case 4:
3186 return new NativeDate(year, month, date, hour);
3187 case 5:
3188 return new NativeDate(year, month, date, hour, minute);
3189 case 6:
3190 return new NativeDate(year, month, date, hour, minute, second);
3191 default:
3192 return new NativeDate(year, month, date, hour, minute, second, ms);
3193 }
3194 }
3195
3196 return mirrorDateProperties(ClockDate, NativeDate);
3197 }())
3198 };
3199
3200 function mirrorDateProperties(target, source) {
3201 if (source.now) {
3202 target.now = function now() {
3203 return target.clock.now;
3204 };
3205 } else {
3206 delete target.now;
3207 }
3208
3209 if (source.toSource) {
3210 target.toSource = function toSource() {
3211 return source.toSource();
3212 };
3213 } else {
3214 delete target.toSource;
3215 }
3216
3217 target.toString = function toString() {
3218 return source.toString();
3219 };
3220
3221 target.prototype = source.prototype;
3222 target.parse = source.parse;
3223 target.UTC = source.UTC;
3224 target.prototype.toUTCString = source.prototype.toUTCString;
3225
3226 for (var prop in source) {
3227 if (source.hasOwnProperty(prop)) {
3228 target[prop] = source[prop];
3229 }
3230 }
3231
3232 return target;
3233 }
3234
3235 var methods = ["Date", "setTimeout", "setInterval",
3236 "clearTimeout", "clearInterval"];
3237
3238 if (typeof global.setImmediate !== "undefined") {
3239 methods.push("setImmediate");
3240 }
3241
3242 if (typeof global.clearImmediate !== "undefined") {
3243 methods.push("clearImmediate");
3244 }
3245
3246 function restore() {
3247 var method;
3248
3249 for (var i = 0, l = this.methods.length; i < l; i++) {
3250 method = this.methods[i];
3251
3252 if (global[method].hadOwnProperty) {
3253 global[method] = this["_" + method];
3254 } else {
3255 try {
3256 delete global[method];
3257 } catch (e) {}
3258 }
3259 }
3260
3261 // Prevent multiple executions which will completely remove these props
3262 this.methods = [];
3263 }
3264
3265 function stubGlobal(method, clock) {
3266 clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method);
3267 clock["_" + method] = global[method];
3268
3269 if (method == "Date") {
3270 var date = mirrorDateProperties(clock[method], global[method]);
3271 global[method] = date;
3272 } else {
3273 global[method] = function () {
3274 return clock[method].apply(clock, arguments);
3275 };
3276
3277 for (var prop in clock[method]) {
3278 if (clock[method].hasOwnProperty(prop)) {
3279 global[method][prop] = clock[method][prop];
3280 }
3281 }
3282 }
3283
3284 global[method].clock = clock;
3285 }
3286
3287 sinon.useFakeTimers = function useFakeTimers(now) {
3288 var clock = sinon.clock.create(now);
3289 clock.restore = restore;
3290 clock.methods = Array.prototype.slice.call(arguments,
3291 typeof now == "number" ? 1 : 0);
3292
3293 if (clock.methods.length === 0) {
3294 clock.methods = methods;
3295 }
3296
3297 for (var i = 0, l = clock.methods.length; i < l; i++) {
3298 stubGlobal(clock.methods[i], clock);
3299 }
3300
3301 return clock;
3302 };
3303 }(typeof global != "undefined" && typeof global !== "function" ? global : this));
3304
3305 sinon.timers = {
3306 setTimeout: setTimeout,
3307 clearTimeout: clearTimeout,
3308 setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined),
3309 clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate: undefined),
3310 setInterval: setInterval,
3311 clearInterval: clearInterval,
3312 Date: Date
3313 };
3314
3315 if (typeof module !== 'undefined' && module.exports) {
3316 module.exports = sinon;
3317 }
3318
3319 /*jslint eqeqeq: false, onevar: false*/
3320 /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
3321 /**
3322 * Minimal Event interface implementation
3323 *
3324 * Original implementation by Sven Fuchs: https://gist.github.com/995028
3325 * Modifications and tests by Christian Johansen.
3326 *
3327 * @author Sven Fuchs (svenfuchs@artweb-design.de)
3328 * @author Christian Johansen (christian@cjohansen.no)
3329 * @license BSD
3330 *
3331 * Copyright (c) 2011 Sven Fuchs, Christian Johansen
3332 */
3333
3334 if (typeof sinon == "undefined") {
3335 this.sinon = {};
3336 }
3337
3338 (function () {
3339 var push = [].push;
3340
3341 sinon.Event = function Event(type, bubbles, cancelable, target) {
3342 this.initEvent(type, bubbles, cancelable, target);
3343 };
3344
3345 sinon.Event.prototype = {
3346 initEvent: function(type, bubbles, cancelable, target) {
3347 this.type = type;
3348 this.bubbles = bubbles;
3349 this.cancelable = cancelable;
3350 this.target = target;
3351 },
3352
3353 stopPropagation: function () {},
3354
3355 preventDefault: function () {
3356 this.defaultPrevented = true;
3357 }
3358 };
3359
3360 sinon.ProgressEvent = function ProgressEvent(type, progressEventRaw, target) {
3361 this.initEvent(type, false, false, target);
3362 this.loaded = progressEventRaw.loaded || null;
3363 this.total = progressEventRaw.total || null;
3364 };
3365
3366 sinon.ProgressEvent.prototype = new sinon.Event();
3367
3368 sinon.ProgressEvent.prototype.constructor = sinon.ProgressEvent;
3369
3370 sinon.CustomEvent = function CustomEvent(type, customData, target) {
3371 this.initEvent(type, false, false, target);
3372 this.detail = customData.detail || null;
3373 };
3374
3375 sinon.CustomEvent.prototype = new sinon.Event();
3376
3377 sinon.CustomEvent.prototype.constructor = sinon.CustomEvent;
3378
3379 sinon.EventTarget = {
3380 addEventListener: function addEventListener(event, listener) {
3381 this.eventListeners = this.eventListeners || {};
3382 this.eventListeners[event] = this.eventListeners[event] || [];
3383 push.call(this.eventListeners[event], listener);
3384 },
3385
3386 removeEventListener: function removeEventListener(event, listener) {
3387 var listeners = this.eventListeners && this.eventListeners[event] || [];
3388
3389 for (var i = 0, l = listeners.length; i < l; ++i) {
3390 if (listeners[i] == listener) {
3391 return listeners.splice(i, 1);
3392 }
3393 }
3394 },
3395
3396 dispatchEvent: function dispatchEvent(event) {
3397 var type = event.type;
3398 var listeners = this.eventListeners && this.eventListeners[type] || [];
3399
3400 for (var i = 0; i < listeners.length; i++) {
3401 if (typeof listeners[i] == "function") {
3402 listeners[i].call(this, event);
3403 } else {
3404 listeners[i].handleEvent(event);
3405 }
3406 }
3407
3408 return !!event.defaultPrevented;
3409 }
3410 };
3411 }());
3412
3413 /**
3414 * @depend ../../sinon.js
3415 * @depend event.js
3416 */
3417 /*jslint eqeqeq: false, onevar: false*/
3418 /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
3419 /**
3420 * Fake XMLHttpRequest object
3421 *
3422 * @author Christian Johansen (christian@cjohansen.no)
3423 * @license BSD
3424 *
3425 * Copyright (c) 2010-2013 Christian Johansen
3426 */
3427
3428 // wrapper for global
3429 (function(global) {
3430 if (typeof sinon === "undefined") {
3431 global.sinon = {};
3432 }
3433
3434 var supportsProgress = typeof ProgressEvent !== "undefined";
3435 var supportsCustomEvent = typeof CustomEvent !== "undefined";
3436 sinon.xhr = { XMLHttpRequest: global.XMLHttpRequest };
3437 var xhr = sinon.xhr;
3438 xhr.GlobalXMLHttpRequest = global.XMLHttpRequest;
3439 xhr.GlobalActiveXObject = global.ActiveXObject;
3440 xhr.supportsActiveX = typeof xhr.GlobalActiveXObject != "undefined";
3441 xhr.supportsXHR = typeof xhr.GlobalXMLHttpRequest != "undefined";
3442 xhr.workingXHR = xhr.supportsXHR ? xhr.GlobalXMLHttpRequest : xhr.supportsActiveX
3443 ? function() { return new xhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false;
3444 xhr.supportsCORS = 'withCredentials' in (new sinon.xhr.GlobalXMLHttpRequest());
3445
3446 /*jsl:ignore*/
3447 var unsafeHeaders = {
3448 "Accept-Charset": true,
3449 "Accept-Encoding": true,
3450 "Connection": true,
3451 "Content-Length": true,
3452 "Cookie": true,
3453 "Cookie2": true,
3454 "Content-Transfer-Encoding": true,
3455 "Date": true,
3456 "Expect": true,
3457 "Host": true,
3458 "Keep-Alive": true,
3459 "Referer": true,
3460 "TE": true,
3461 "Trailer": true,
3462 "Transfer-Encoding": true,
3463 "Upgrade": true,
3464 "User-Agent": true,
3465 "Via": true
3466 };
3467 /*jsl:end*/
3468
3469 function FakeXMLHttpRequest() {
3470 this.readyState = FakeXMLHttpRequest.UNSENT;
3471 this.requestHeaders = {};
3472 this.requestBody = null;
3473 this.status = 0;
3474 this.statusText = "";
3475 this.upload = new UploadProgress();
3476 if (sinon.xhr.supportsCORS) {
3477 this.withCredentials = false;
3478 }
3479
3480
3481 var xhr = this;
3482 var events = ["loadstart", "load", "abort", "loadend"];
3483
3484 function addEventListener(eventName) {
3485 xhr.addEventListener(eventName, function (event) {
3486 var listener = xhr["on" + eventName];
3487
3488 if (listener && typeof listener == "function") {
3489 listener.call(this, event);
3490 }
3491 });
3492 }
3493
3494 for (var i = events.length - 1; i >= 0; i--) {
3495 addEventListener(events[i]);
3496 }
3497
3498 if (typeof FakeXMLHttpRequest.onCreate == "function") {
3499 FakeXMLHttpRequest.onCreate(this);
3500 }
3501 }
3502
3503 // An upload object is created for each
3504 // FakeXMLHttpRequest and allows upload
3505 // events to be simulated using uploadProgress
3506 // and uploadError.
3507 function UploadProgress() {
3508 this.eventListeners = {
3509 "progress": [],
3510 "load": [],
3511 "abort": [],
3512 "error": []
3513 }
3514 }
3515
3516 UploadProgress.prototype.addEventListener = function(event, listener) {
3517 this.eventListeners[event].push(listener);
3518 };
3519
3520 UploadProgress.prototype.removeEventListener = function(event, listener) {
3521 var listeners = this.eventListeners[event] || [];
3522
3523 for (var i = 0, l = listeners.length; i < l; ++i) {
3524 if (listeners[i] == listener) {
3525 return listeners.splice(i, 1);
3526 }
3527 }
3528 };
3529
3530 UploadProgress.prototype.dispatchEvent = function(event) {
3531 var listeners = this.eventListeners[event.type] || [];
3532
3533 for (var i = 0, listener; (listener = listeners[i]) != null; i++) {
3534 listener(event);
3535 }
3536 };
3537
3538 function verifyState(xhr) {
3539 if (xhr.readyState !== FakeXMLHttpRequest.OPENED) {
3540 throw new Error("INVALID_STATE_ERR");
3541 }
3542
3543 if (xhr.sendFlag) {
3544 throw new Error("INVALID_STATE_ERR");
3545 }
3546 }
3547
3548 // filtering to enable a white-list version of Sinon FakeXhr,
3549 // where whitelisted requests are passed through to real XHR
3550 function each(collection, callback) {
3551 if (!collection) return;
3552 for (var i = 0, l = collection.length; i < l; i += 1) {
3553 callback(collection[i]);
3554 }
3555 }
3556 function some(collection, callback) {
3557 for (var index = 0; index < collection.length; index++) {
3558 if(callback(collection[index]) === true) return true;
3559 }
3560 return false;
3561 }
3562 // largest arity in XHR is 5 - XHR#open
3563 var apply = function(obj,method,args) {
3564 switch(args.length) {
3565 case 0: return obj[method]();
3566 case 1: return obj[method](args[0]);
3567 case 2: return obj[method](args[0],args[1]);
3568 case 3: return obj[method](args[0],args[1],args[2]);
3569 case 4: return obj[method](args[0],args[1],args[2],args[3]);
3570 case 5: return obj[method](args[0],args[1],args[2],args[3],args[4]);
3571 }
3572 };
3573
3574 FakeXMLHttpRequest.filters = [];
3575 FakeXMLHttpRequest.addFilter = function(fn) {
3576 this.filters.push(fn)
3577 };
3578 var IE6Re = /MSIE 6/;
3579 FakeXMLHttpRequest.defake = function(fakeXhr,xhrArgs) {
3580 var xhr = new sinon.xhr.workingXHR();
3581 each(["open","setRequestHeader","send","abort","getResponseHeader",
3582 "getAllResponseHeaders","addEventListener","overrideMimeType","removeEventListener"],
3583 function(method) {
3584 fakeXhr[method] = function() {
3585 return apply(xhr,method,arguments);
3586 };
3587 });
3588
3589 var copyAttrs = function(args) {
3590 each(args, function(attr) {
3591 try {
3592 fakeXhr[attr] = xhr[attr]
3593 } catch(e) {
3594 if(!IE6Re.test(navigator.userAgent)) throw e;
3595 }
3596 });
3597 };
3598
3599 var stateChange = function() {
3600 fakeXhr.readyState = xhr.readyState;
3601 if(xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) {
3602 copyAttrs(["status","statusText"]);
3603 }
3604 if(xhr.readyState >= FakeXMLHttpRequest.LOADING) {
3605 copyAttrs(["responseText"]);
3606 }
3607 if(xhr.readyState === FakeXMLHttpRequest.DONE) {
3608 copyAttrs(["responseXML"]);
3609 }
3610 if(fakeXhr.onreadystatechange) fakeXhr.onreadystatechange.call(fakeXhr, { target: fakeXhr });
3611 };
3612 if(xhr.addEventListener) {
3613 for(var event in fakeXhr.eventListeners) {
3614 if(fakeXhr.eventListeners.hasOwnProperty(event)) {
3615 each(fakeXhr.eventListeners[event],function(handler) {
3616 xhr.addEventListener(event, handler);
3617 });
3618 }
3619 }
3620 xhr.addEventListener("readystatechange",stateChange);
3621 } else {
3622 xhr.onreadystatechange = stateChange;
3623 }
3624 apply(xhr,"open",xhrArgs);
3625 };
3626 FakeXMLHttpRequest.useFilters = false;
3627
3628 function verifyRequestOpened(xhr) {
3629 if (xhr.readyState != FakeXMLHttpRequest.OPENED) {
3630 throw new Error("INVALID_STATE_ERR - " + xhr.readyState);
3631 }
3632 }
3633
3634 function verifyRequestSent(xhr) {
3635 if (xhr.readyState == FakeXMLHttpRequest.DONE) {
3636 throw new Error("Request done");
3637 }
3638 }
3639
3640 function verifyHeadersReceived(xhr) {
3641 if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) {
3642 throw new Error("No headers received");
3643 }
3644 }
3645
3646 function verifyResponseBodyType(body) {
3647 if (typeof body != "string") {
3648 var error = new Error("Attempted to respond to fake XMLHttpRequest with " +
3649 body + ", which is not a string.");
3650 error.name = "InvalidBodyException";
3651 throw error;
3652 }
3653 }
3654
3655 sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, {
3656 async: true,
3657
3658 open: function open(method, url, async, username, password) {
3659 this.method = method;
3660 this.url = url;
3661 this.async = typeof async == "boolean" ? async : true;
3662 this.username = username;
3663 this.password = password;
3664 this.responseText = null;
3665 this.responseXML = null;
3666 this.requestHeaders = {};
3667 this.sendFlag = false;
3668 if(sinon.FakeXMLHttpRequest.useFilters === true) {
3669 var xhrArgs = arguments;
3670 var defake = some(FakeXMLHttpRequest.filters,function(filter) {
3671 return filter.apply(this,xhrArgs)
3672 });
3673 if (defake) {
3674 return sinon.FakeXMLHttpRequest.defake(this,arguments);
3675 }
3676 }
3677 this.readyStateChange(FakeXMLHttpRequest.OPENED);
3678 },
3679
3680 readyStateChange: function readyStateChange(state) {
3681 this.readyState = state;
3682
3683 if (typeof this.onreadystatechange == "function") {
3684 try {
3685 this.onreadystatechange();
3686 } catch (e) {
3687 sinon.logError("Fake XHR onreadystatechange handler", e);
3688 }
3689 }
3690
3691 this.dispatchEvent(new sinon.Event("readystatechange"));
3692
3693 switch (this.readyState) {
3694 case FakeXMLHttpRequest.DONE:
3695 this.dispatchEvent(new sinon.Event("load", false, false, this));
3696 this.dispatchEvent(new sinon.Event("loadend", false, false, this));
3697 this.upload.dispatchEvent(new sinon.Event("load", false, false, this));
3698 if (supportsProgress) {
3699 this.upload.dispatchEvent(new sinon.ProgressEvent('progress', {loaded: 100, total: 100}));
3700 }
3701 break;
3702 }
3703 },
3704
3705 setRequestHeader: function setRequestHeader(header, value) {
3706 verifyState(this);
3707
3708 if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) {
3709 throw new Error("Refused to set unsafe header \"" + header + "\"");
3710 }
3711
3712 if (this.requestHeaders[header]) {
3713 this.requestHeaders[header] += "," + value;
3714 } else {
3715 this.requestHeaders[header] = value;
3716 }
3717 },
3718
3719 // Helps testing
3720 setResponseHeaders: function setResponseHeaders(headers) {
3721 verifyRequestOpened(this);
3722 this.responseHeaders = {};
3723
3724 for (var header in headers) {
3725 if (headers.hasOwnProperty(header)) {
3726 this.responseHeaders[header] = headers[header];
3727 }
3728 }
3729
3730 if (this.async) {
3731 this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED);
3732 } else {
3733 this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED;
3734 }
3735 },
3736
3737 // Currently treats ALL data as a DOMString (i.e. no Document)
3738 send: function send(data) {
3739 verifyState(this);
3740
3741 if (!/^(get|head)$/i.test(this.method)) {
3742 if (this.requestHeaders["Content-Type"]) {
3743 var value = this.requestHeaders["Content-Type"].split(";");
3744 this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8";
3745 } else {
3746 this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8";
3747 }
3748
3749 this.requestBody = data;
3750 }
3751
3752 this.errorFlag = false;
3753 this.sendFlag = this.async;
3754 this.readyStateChange(FakeXMLHttpRequest.OPENED);
3755
3756 if (typeof this.onSend == "function") {
3757 this.onSend(this);
3758 }
3759
3760 this.dispatchEvent(new sinon.Event("loadstart", false, false, this));
3761 },
3762
3763 abort: function abort() {
3764 this.aborted = true;
3765 this.responseText = null;
3766 this.errorFlag = true;
3767 this.requestHeaders = {};
3768
3769 if (this.readyState > sinon.FakeXMLHttpRequest.UNSENT && this.sendFlag) {
3770 this.readyStateChange(sinon.FakeXMLHttpRequest.DONE);
3771 this.sendFlag = false;
3772 }
3773
3774 this.readyState = sinon.FakeXMLHttpRequest.UNSENT;
3775
3776 this.dispatchEvent(new sinon.Event("abort", false, false, this));
3777
3778 this.upload.dispatchEvent(new sinon.Event("abort", false, false, this));
3779
3780 if (typeof this.onerror === "function") {
3781 this.onerror();
3782 }
3783 },
3784
3785 getResponseHeader: function getResponseHeader(header) {
3786 if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
3787 return null;
3788 }
3789
3790 if (/^Set-Cookie2?$/i.test(header)) {
3791 return null;
3792 }
3793
3794 header = header.toLowerCase();
3795
3796 for (var h in this.responseHeaders) {
3797 if (h.toLowerCase() == header) {
3798 return this.responseHeaders[h];
3799 }
3800 }
3801
3802 return null;
3803 },
3804
3805 getAllResponseHeaders: function getAllResponseHeaders() {
3806 if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
3807 return "";
3808 }
3809
3810 var headers = "";
3811
3812 for (var header in this.responseHeaders) {
3813 if (this.responseHeaders.hasOwnProperty(header) &&
3814 !/^Set-Cookie2?$/i.test(header)) {
3815 headers += header + ": " + this.responseHeaders[header] + "\r\n";
3816 }
3817 }
3818
3819 return headers;
3820 },
3821
3822 setResponseBody: function setResponseBody(body) {
3823 verifyRequestSent(this);
3824 verifyHeadersReceived(this);
3825 verifyResponseBodyType(body);
3826
3827 var chunkSize = this.chunkSize || 10;
3828 var index = 0;
3829 this.responseText = "";
3830
3831 do {
3832 if (this.async) {
3833 this.readyStateChange(FakeXMLHttpRequest.LOADING);
3834 }
3835
3836 this.responseText += body.substring(index, index + chunkSize);
3837 index += chunkSize;
3838 } while (index < body.length);
3839
3840 var type = this.getResponseHeader("Content-Type");
3841
3842 if (this.responseText &&
3843 (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
3844 try {
3845 this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText);
3846 } catch (e) {
3847 // Unable to parse XML - no biggie
3848 }
3849 }
3850
3851 if (this.async) {
3852 this.readyStateChange(FakeXMLHttpRequest.DONE);
3853 } else {
3854 this.readyState = FakeXMLHttpRequest.DONE;
3855 }
3856 },
3857
3858 respond: function respond(status, headers, body) {
3859 this.status = typeof status == "number" ? status : 200;
3860 this.statusText = FakeXMLHttpRequest.statusCodes[this.status];
3861 this.setResponseHeaders(headers || {});
3862 this.setResponseBody(body || "");
3863 },
3864
3865 uploadProgress: function uploadProgress(progressEventRaw) {
3866 if (supportsProgress) {
3867 this.upload.dispatchEvent(new sinon.ProgressEvent("progress", progressEventRaw));
3868 }
3869 },
3870
3871 uploadError: function uploadError(error) {
3872 if (supportsCustomEvent) {
3873 this.upload.dispatchEvent(new sinon.CustomEvent("error", {"detail": error}));
3874 }
3875 }
3876 });
3877
3878 sinon.extend(FakeXMLHttpRequest, {
3879 UNSENT: 0,
3880 OPENED: 1,
3881 HEADERS_RECEIVED: 2,
3882 LOADING: 3,
3883 DONE: 4
3884 });
3885
3886 // Borrowed from JSpec
3887 FakeXMLHttpRequest.parseXML = function parseXML(text) {
3888 var xmlDoc;
3889
3890 if (typeof DOMParser != "undefined") {
3891 var parser = new DOMParser();
3892 xmlDoc = parser.parseFromString(text, "text/xml");
3893 } else {
3894 xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
3895 xmlDoc.async = "false";
3896 xmlDoc.loadXML(text);
3897 }
3898
3899 return xmlDoc;
3900 };
3901
3902 FakeXMLHttpRequest.statusCodes = {
3903 100: "Continue",
3904 101: "Switching Protocols",
3905 200: "OK",
3906 201: "Created",
3907 202: "Accepted",
3908 203: "Non-Authoritative Information",
3909 204: "No Content",
3910 205: "Reset Content",
3911 206: "Partial Content",
3912 300: "Multiple Choice",
3913 301: "Moved Permanently",
3914 302: "Found",
3915 303: "See Other",
3916 304: "Not Modified",
3917 305: "Use Proxy",
3918 307: "Temporary Redirect",
3919 400: "Bad Request",
3920 401: "Unauthorized",
3921 402: "Payment Required",
3922 403: "Forbidden",
3923 404: "Not Found",
3924 405: "Method Not Allowed",
3925 406: "Not Acceptable",
3926 407: "Proxy Authentication Required",
3927 408: "Request Timeout",
3928 409: "Conflict",
3929 410: "Gone",
3930 411: "Length Required",
3931 412: "Precondition Failed",
3932 413: "Request Entity Too Large",
3933 414: "Request-URI Too Long",
3934 415: "Unsupported Media Type",
3935 416: "Requested Range Not Satisfiable",
3936 417: "Expectation Failed",
3937 422: "Unprocessable Entity",
3938 500: "Internal Server Error",
3939 501: "Not Implemented",
3940 502: "Bad Gateway",
3941 503: "Service Unavailable",
3942 504: "Gateway Timeout",
3943 505: "HTTP Version Not Supported"
3944 };
3945
3946 sinon.useFakeXMLHttpRequest = function () {
3947 sinon.FakeXMLHttpRequest.restore = function restore(keepOnCreate) {
3948 if (xhr.supportsXHR) {
3949 global.XMLHttpRequest = xhr.GlobalXMLHttpRequest;
3950 }
3951
3952 if (xhr.supportsActiveX) {
3953 global.ActiveXObject = xhr.GlobalActiveXObject;
3954 }
3955
3956 delete sinon.FakeXMLHttpRequest.restore;
3957
3958 if (keepOnCreate !== true) {
3959 delete sinon.FakeXMLHttpRequest.onCreate;
3960 }
3961 };
3962 if (xhr.supportsXHR) {
3963 global.XMLHttpRequest = sinon.FakeXMLHttpRequest;
3964 }
3965
3966 if (xhr.supportsActiveX) {
3967 global.ActiveXObject = function ActiveXObject(objId) {
3968 if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) {
3969
3970 return new sinon.FakeXMLHttpRequest();
3971 }
3972
3973 return new xhr.GlobalActiveXObject(objId);
3974 };
3975 }
3976
3977 return sinon.FakeXMLHttpRequest;
3978 };
3979
3980 sinon.FakeXMLHttpRequest = FakeXMLHttpRequest;
3981
3982 })(typeof global === "object" ? global : this);
3983
3984 if (typeof module !== 'undefined' && module.exports) {
3985 module.exports = sinon;
3986 }
3987
3988 /**
3989 * @depend fake_xml_http_request.js
3990 */
3991 /*jslint eqeqeq: false, onevar: false, regexp: false, plusplus: false*/
3992 /*global module, require, window*/
3993 /**
3994 * The Sinon "server" mimics a web server that receives requests from
3995 * sinon.FakeXMLHttpRequest and provides an API to respond to those requests,
3996 * both synchronously and asynchronously. To respond synchronuously, canned
3997 * answers have to be provided upfront.
3998 *
3999 * @author Christian Johansen (christian@cjohansen.no)
4000 * @license BSD
4001 *
4002 * Copyright (c) 2010-2013 Christian Johansen
4003 */
4004
4005 if (typeof sinon == "undefined") {
4006 var sinon = {};
4007 }
4008
4009 sinon.fakeServer = (function () {
4010 var push = [].push;
4011 function F() {}
4012
4013 function create(proto) {
4014 F.prototype = proto;
4015 return new F();
4016 }
4017
4018 function responseArray(handler) {
4019 var response = handler;
4020
4021 if (Object.prototype.toString.call(handler) != "[object Array]") {
4022 response = [200, {}, handler];
4023 }
4024
4025 if (typeof response[2] != "string") {
4026 throw new TypeError("Fake server response body should be string, but was " +
4027 typeof response[2]);
4028 }
4029
4030 return response;
4031 }
4032
4033 var wloc = typeof window !== "undefined" ? window.location : {};
4034 var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host);
4035
4036 function matchOne(response, reqMethod, reqUrl) {
4037 var rmeth = response.method;
4038 var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase();
4039 var url = response.url;
4040 var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl));
4041
4042 return matchMethod && matchUrl;
4043 }
4044
4045 function match(response, request) {
4046 var requestUrl = request.url;
4047
4048 if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) {
4049 requestUrl = requestUrl.replace(rCurrLoc, "");
4050 }
4051
4052 if (matchOne(response, this.getHTTPMethod(request), requestUrl)) {
4053 if (typeof response.response == "function") {
4054 var ru = response.url;
4055 var args = [request].concat(ru && typeof ru.exec == "function" ? ru.exec(requestUrl).slice(1) : []);
4056 return response.response.apply(response, args);
4057 }
4058
4059 return true;
4060 }
4061
4062 return false;
4063 }
4064
4065 function log(response, request) {
4066 var str;
4067
4068 str = "Request:\n" + sinon.format(request) + "\n\n";
4069 str += "Response:\n" + sinon.format(response) + "\n\n";
4070
4071 sinon.log(str);
4072 }
4073
4074 return {
4075 create: function () {
4076 var server = create(this);
4077 this.xhr = sinon.useFakeXMLHttpRequest();
4078 server.requests = [];
4079
4080 this.xhr.onCreate = function (xhrObj) {
4081 server.addRequest(xhrObj);
4082 };
4083
4084 return server;
4085 },
4086
4087 addRequest: function addRequest(xhrObj) {
4088 var server = this;
4089 push.call(this.requests, xhrObj);
4090
4091 xhrObj.onSend = function () {
4092 server.handleRequest(this);
4093
4094 if (server.autoRespond && !server.responding) {
4095 setTimeout(function () {
4096 server.responding = false;
4097 server.respond();
4098 }, server.autoRespondAfter || 10);
4099
4100 server.responding = true;
4101 }
4102 };
4103 },
4104
4105 getHTTPMethod: function getHTTPMethod(request) {
4106 if (this.fakeHTTPMethods && /post/i.test(request.method)) {
4107 var matches = (request.requestBody || "").match(/_method=([^\b;]+)/);
4108 return !!matches ? matches[1] : request.method;
4109 }
4110
4111 return request.method;
4112 },
4113
4114 handleRequest: function handleRequest(xhr) {
4115 if (xhr.async) {
4116 if (!this.queue) {
4117 this.queue = [];
4118 }
4119
4120 push.call(this.queue, xhr);
4121 } else {
4122 this.processRequest(xhr);
4123 }
4124 },
4125
4126 respondWith: function respondWith(method, url, body) {
4127 if (arguments.length == 1 && typeof method != "function") {
4128 this.response = responseArray(method);
4129 return;
4130 }
4131
4132 if (!this.responses) { this.responses = []; }
4133
4134 if (arguments.length == 1) {
4135 body = method;
4136 url = method = null;
4137 }
4138
4139 if (arguments.length == 2) {
4140 body = url;
4141 url = method;
4142 method = null;
4143 }
4144
4145 push.call(this.responses, {
4146 method: method,
4147 url: url,
4148 response: typeof body == "function" ? body : responseArray(body)
4149 });
4150 },
4151
4152 respond: function respond() {
4153 if (arguments.length > 0) this.respondWith.apply(this, arguments);
4154 var queue = this.queue || [];
4155 var requests = queue.splice(0);
4156 var request;
4157
4158 while(request = requests.shift()) {
4159 this.processRequest(request);
4160 }
4161 },
4162
4163 processRequest: function processRequest(request) {
4164 try {
4165 if (request.aborted) {
4166 return;
4167 }
4168
4169 var response = this.response || [404, {}, ""];
4170
4171 if (this.responses) {
4172 for (var l = this.responses.length, i = l - 1; i >= 0; i--) {
4173 if (match.call(this, this.responses[i], request)) {
4174 response = this.responses[i].response;
4175 break;
4176 }
4177 }
4178 }
4179
4180 if (request.readyState != 4) {
4181 log(response, request);
4182
4183 request.respond(response[0], response[1], response[2]);
4184 }
4185 } catch (e) {
4186 sinon.logError("Fake server request processing", e);
4187 }
4188 },
4189
4190 restore: function restore() {
4191 return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments);
4192 }
4193 };
4194 }());
4195
4196 if (typeof module !== 'undefined' && module.exports) {
4197 module.exports = sinon;
4198 }
4199
4200 /**
4201 * @depend fake_server.js
4202 * @depend fake_timers.js
4203 */
4204 /*jslint browser: true, eqeqeq: false, onevar: false*/
4205 /*global sinon*/
4206 /**
4207 * Add-on for sinon.fakeServer that automatically handles a fake timer along with
4208 * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery
4209 * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead,
4210 * it polls the object for completion with setInterval. Dispite the direct
4211 * motivation, there is nothing jQuery-specific in this file, so it can be used
4212 * in any environment where the ajax implementation depends on setInterval or
4213 * setTimeout.
4214 *
4215 * @author Christian Johansen (christian@cjohansen.no)
4216 * @license BSD
4217 *
4218 * Copyright (c) 2010-2013 Christian Johansen
4219 */
4220
4221 (function () {
4222 function Server() {}
4223 Server.prototype = sinon.fakeServer;
4224
4225 sinon.fakeServerWithClock = new Server();
4226
4227 sinon.fakeServerWithClock.addRequest = function addRequest(xhr) {
4228 if (xhr.async) {
4229 if (typeof setTimeout.clock == "object") {
4230 this.clock = setTimeout.clock;
4231 } else {
4232 this.clock = sinon.useFakeTimers();
4233 this.resetClock = true;
4234 }
4235
4236 if (!this.longestTimeout) {
4237 var clockSetTimeout = this.clock.setTimeout;
4238 var clockSetInterval = this.clock.setInterval;
4239 var server = this;
4240
4241 this.clock.setTimeout = function (fn, timeout) {
4242 server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
4243
4244 return clockSetTimeout.apply(this, arguments);
4245 };
4246
4247 this.clock.setInterval = function (fn, timeout) {
4248 server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
4249
4250 return clockSetInterval.apply(this, arguments);
4251 };
4252 }
4253 }
4254
4255 return sinon.fakeServer.addRequest.call(this, xhr);
4256 };
4257
4258 sinon.fakeServerWithClock.respond = function respond() {
4259 var returnVal = sinon.fakeServer.respond.apply(this, arguments);
4260
4261 if (this.clock) {
4262 this.clock.tick(this.longestTimeout || 0);
4263 this.longestTimeout = 0;
4264
4265 if (this.resetClock) {
4266 this.clock.restore();
4267 this.resetClock = false;
4268 }
4269 }
4270
4271 return returnVal;
4272 };
4273
4274 sinon.fakeServerWithClock.restore = function restore() {
4275 if (this.clock) {
4276 this.clock.restore();
4277 }
4278
4279 return sinon.fakeServer.restore.apply(this, arguments);
4280 };
4281 }());
4282
4283 /**
4284 * @depend ../sinon.js
4285 * @depend collection.js
4286 * @depend util/fake_timers.js
4287 * @depend util/fake_server_with_clock.js
4288 */
4289 /*jslint eqeqeq: false, onevar: false, plusplus: false*/
4290 /*global require, module*/
4291 /**
4292 * Manages fake collections as well as fake utilities such as Sinon's
4293 * timers and fake XHR implementation in one convenient object.
4294 *
4295 * @author Christian Johansen (christian@cjohansen.no)
4296 * @license BSD
4297 *
4298 * Copyright (c) 2010-2013 Christian Johansen
4299 */
4300
4301 if (typeof module !== 'undefined' && module.exports) {
4302 var sinon = require("../sinon");
4303 sinon.extend(sinon, require("./util/fake_timers"));
4304 }
4305
4306 (function () {
4307 var push = [].push;
4308
4309 function exposeValue(sandbox, config, key, value) {
4310 if (!value) {
4311 return;
4312 }
4313
4314 if (config.injectInto && !(key in config.injectInto)) {
4315 config.injectInto[key] = value;
4316 sandbox.injectedKeys.push(key);
4317 } else {
4318 push.call(sandbox.args, value);
4319 }
4320 }
4321
4322 function prepareSandboxFromConfig(config) {
4323 var sandbox = sinon.create(sinon.sandbox);
4324
4325 if (config.useFakeServer) {
4326 if (typeof config.useFakeServer == "object") {
4327 sandbox.serverPrototype = config.useFakeServer;
4328 }
4329
4330 sandbox.useFakeServer();
4331 }
4332
4333 if (config.useFakeTimers) {
4334 if (typeof config.useFakeTimers == "object") {
4335 sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers);
4336 } else {
4337 sandbox.useFakeTimers();
4338 }
4339 }
4340
4341 return sandbox;
4342 }
4343
4344 sinon.sandbox = sinon.extend(sinon.create(sinon.collection), {
4345 useFakeTimers: function useFakeTimers() {
4346 this.clock = sinon.useFakeTimers.apply(sinon, arguments);
4347
4348 return this.add(this.clock);
4349 },
4350
4351 serverPrototype: sinon.fakeServer,
4352
4353 useFakeServer: function useFakeServer() {
4354 var proto = this.serverPrototype || sinon.fakeServer;
4355
4356 if (!proto || !proto.create) {
4357 return null;
4358 }
4359
4360 this.server = proto.create();
4361 return this.add(this.server);
4362 },
4363
4364 inject: function (obj) {
4365 sinon.collection.inject.call(this, obj);
4366
4367 if (this.clock) {
4368 obj.clock = this.clock;
4369 }
4370
4371 if (this.server) {
4372 obj.server = this.server;
4373 obj.requests = this.server.requests;
4374 }
4375
4376 return obj;
4377 },
4378
4379 restore: function () {
4380 sinon.collection.restore.apply(this, arguments);
4381 this.restoreContext();
4382 },
4383
4384 restoreContext: function () {
4385 if (this.injectedKeys) {
4386 for (var i = 0, j = this.injectedKeys.length; i < j; i++) {
4387 delete this.injectInto[this.injectedKeys[i]];
4388 }
4389 this.injectedKeys = [];
4390 }
4391 },
4392
4393 create: function (config) {
4394 if (!config) {
4395 return sinon.create(sinon.sandbox);
4396 }
4397
4398 var sandbox = prepareSandboxFromConfig(config);
4399 sandbox.args = sandbox.args || [];
4400 sandbox.injectedKeys = [];
4401 sandbox.injectInto = config.injectInto;
4402 var prop, value, exposed = sandbox.inject({});
4403
4404 if (config.properties) {
4405 for (var i = 0, l = config.properties.length; i < l; i++) {
4406 prop = config.properties[i];
4407 value = exposed[prop] || prop == "sandbox" && sandbox;
4408 exposeValue(sandbox, config, prop, value);
4409 }
4410 } else {
4411 exposeValue(sandbox, config, "sandbox", value);
4412 }
4413
4414 return sandbox;
4415 }
4416 });
4417
4418 sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer;
4419
4420 if (typeof module !== 'undefined' && module.exports) {
4421 module.exports = sinon.sandbox;
4422 }
4423 }());
4424
4425 /**
4426 * @depend ../sinon.js
4427 * @depend stub.js
4428 * @depend mock.js
4429 * @depend sandbox.js
4430 */
4431 /*jslint eqeqeq: false, onevar: false, forin: true, plusplus: false*/
4432 /*global module, require, sinon*/
4433 /**
4434 * Test function, sandboxes fakes
4435 *
4436 * @author Christian Johansen (christian@cjohansen.no)
4437 * @license BSD
4438 *
4439 * Copyright (c) 2010-2013 Christian Johansen
4440 */
4441
4442 (function (sinon) {
4443 var commonJSModule = typeof module !== 'undefined' && module.exports;
4444
4445 if (!sinon && commonJSModule) {
4446 sinon = require("../sinon");
4447 }
4448
4449 if (!sinon) {
4450 return;
4451 }
4452
4453 function test(callback) {
4454 var type = typeof callback;
4455
4456 if (type != "function") {
4457 throw new TypeError("sinon.test needs to wrap a test function, got " + type);
4458 }
4459
4460 return function () {
4461 var config = sinon.getConfig(sinon.config);
4462 config.injectInto = config.injectIntoThis && this || config.injectInto;
4463 var sandbox = sinon.sandbox.create(config);
4464 var exception, result;
4465 var args = Array.prototype.slice.call(arguments).concat(sandbox.args);
4466
4467 try {
4468 result = callback.apply(this, args);
4469 } catch (e) {
4470 exception = e;
4471 }
4472
4473 if (typeof exception !== "undefined") {
4474 sandbox.restore();
4475 throw exception;
4476 }
4477 else {
4478 sandbox.verifyAndRestore();
4479 }
4480
4481 return result;
4482 };
4483 }
4484
4485 test.config = {
4486 injectIntoThis: true,
4487 injectInto: null,
4488 properties: ["spy", "stub", "mock", "clock", "server", "requests"],
4489 useFakeTimers: true,
4490 useFakeServer: true
4491 };
4492
4493 if (commonJSModule) {
4494 module.exports = test;
4495 } else {
4496 sinon.test = test;
4497 }
4498 }(typeof sinon == "object" && sinon || null));
4499
4500 /**
4501 * @depend ../sinon.js
4502 * @depend test.js
4503 */
4504 /*jslint eqeqeq: false, onevar: false, eqeqeq: false*/
4505 /*global module, require, sinon*/
4506 /**
4507 * Test case, sandboxes all test functions
4508 *
4509 * @author Christian Johansen (christian@cjohansen.no)
4510 * @license BSD
4511 *
4512 * Copyright (c) 2010-2013 Christian Johansen
4513 */
4514
4515 (function (sinon) {
4516 var commonJSModule = typeof module !== 'undefined' && module.exports;
4517
4518 if (!sinon && commonJSModule) {
4519 sinon = require("../sinon");
4520 }
4521
4522 if (!sinon || !Object.prototype.hasOwnProperty) {
4523 return;
4524 }
4525
4526 function createTest(property, setUp, tearDown) {
4527 return function () {
4528 if (setUp) {
4529 setUp.apply(this, arguments);
4530 }
4531
4532 var exception, result;
4533
4534 try {
4535 result = property.apply(this, arguments);
4536 } catch (e) {
4537 exception = e;
4538 }
4539
4540 if (tearDown) {
4541 tearDown.apply(this, arguments);
4542 }
4543
4544 if (exception) {
4545 throw exception;
4546 }
4547
4548 return result;
4549 };
4550 }
4551
4552 function testCase(tests, prefix) {
4553 /*jsl:ignore*/
4554 if (!tests || typeof tests != "object") {
4555 throw new TypeError("sinon.testCase needs an object with test functions");
4556 }
4557 /*jsl:end*/
4558
4559 prefix = prefix || "test";
4560 var rPrefix = new RegExp("^" + prefix);
4561 var methods = {}, testName, property, method;
4562 var setUp = tests.setUp;
4563 var tearDown = tests.tearDown;
4564
4565 for (testName in tests) {
4566 if (tests.hasOwnProperty(testName)) {
4567 property = tests[testName];
4568
4569 if (/^(setUp|tearDown)$/.test(testName)) {
4570 continue;
4571 }
4572
4573 if (typeof property == "function" && rPrefix.test(testName)) {
4574 method = property;
4575
4576 if (setUp || tearDown) {
4577 method = createTest(property, setUp, tearDown);
4578 }
4579
4580 methods[testName] = sinon.test(method);
4581 } else {
4582 methods[testName] = tests[testName];
4583 }
4584 }
4585 }
4586
4587 return methods;
4588 }
4589
4590 if (commonJSModule) {
4591 module.exports = testCase;
4592 } else {
4593 sinon.testCase = testCase;
4594 }
4595 }(typeof sinon == "object" && sinon || null));
4596
4597 /**
4598 * @depend ../sinon.js
4599 * @depend stub.js
4600 */
4601 /*jslint eqeqeq: false, onevar: false, nomen: false, plusplus: false*/
4602 /*global module, require, sinon*/
4603 /**
4604 * Assertions matching the test spy retrieval interface.
4605 *
4606 * @author Christian Johansen (christian@cjohansen.no)
4607 * @license BSD
4608 *
4609 * Copyright (c) 2010-2013 Christian Johansen
4610 */
4611
4612 (function (sinon, global) {
4613 var commonJSModule = typeof module !== "undefined" && module.exports;
4614 var slice = Array.prototype.slice;
4615 var assert;
4616
4617 if (!sinon && commonJSModule) {
4618 sinon = require("../sinon");
4619 }
4620
4621 if (!sinon) {
4622 return;
4623 }
4624
4625 function verifyIsStub() {
4626 var method;
4627
4628 for (var i = 0, l = arguments.length; i < l; ++i) {
4629 method = arguments[i];
4630
4631 if (!method) {
4632 assert.fail("fake is not a spy");
4633 }
4634
4635 if (typeof method != "function") {
4636 assert.fail(method + " is not a function");
4637 }
4638
4639 if (typeof method.getCall != "function") {
4640 assert.fail(method + " is not stubbed");
4641 }
4642 }
4643 }
4644
4645 function failAssertion(object, msg) {
4646 object = object || global;
4647 var failMethod = object.fail || assert.fail;
4648 failMethod.call(object, msg);
4649 }
4650
4651 function mirrorPropAsAssertion(name, method, message) {
4652 if (arguments.length == 2) {
4653 message = method;
4654 method = name;
4655 }
4656
4657 assert[name] = function (fake) {
4658 verifyIsStub(fake);
4659
4660 var args = slice.call(arguments, 1);
4661 var failed = false;
4662
4663 if (typeof method == "function") {
4664 failed = !method(fake);
4665 } else {
4666 failed = typeof fake[method] == "function" ?
4667 !fake[method].apply(fake, args) : !fake[method];
4668 }
4669
4670 if (failed) {
4671 failAssertion(this, fake.printf.apply(fake, [message].concat(args)));
4672 } else {
4673 assert.pass(name);
4674 }
4675 };
4676 }
4677
4678 function exposedName(prefix, prop) {
4679 return !prefix || /^fail/.test(prop) ? prop :
4680 prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1);
4681 }
4682
4683 assert = {
4684 failException: "AssertError",
4685
4686 fail: function fail(message) {
4687 var error = new Error(message);
4688 error.name = this.failException || assert.failException;
4689
4690 throw error;
4691 },
4692
4693 pass: function pass(assertion) {},
4694
4695 callOrder: function assertCallOrder() {
4696 verifyIsStub.apply(null, arguments);
4697 var expected = "", actual = "";
4698
4699 if (!sinon.calledInOrder(arguments)) {
4700 try {
4701 expected = [].join.call(arguments, ", ");
4702 var calls = slice.call(arguments);
4703 var i = calls.length;
4704 while (i) {
4705 if (!calls[--i].called) {
4706 calls.splice(i, 1);
4707 }
4708 }
4709 actual = sinon.orderByFirstCall(calls).join(", ");
4710 } catch (e) {
4711 // If this fails, we'll just fall back to the blank string
4712 }
4713
4714 failAssertion(this, "expected " + expected + " to be " +
4715 "called in order but were called as " + actual);
4716 } else {
4717 assert.pass("callOrder");
4718 }
4719 },
4720
4721 callCount: function assertCallCount(method, count) {
4722 verifyIsStub(method);
4723
4724 if (method.callCount != count) {
4725 var msg = "expected %n to be called " + sinon.timesInWords(count) +
4726 " but was called %c%C";
4727 failAssertion(this, method.printf(msg));
4728 } else {
4729 assert.pass("callCount");
4730 }
4731 },
4732
4733 expose: function expose(target, options) {
4734 if (!target) {
4735 throw new TypeError("target is null or undefined");
4736 }
4737
4738 var o = options || {};
4739 var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix;
4740 var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail;
4741
4742 for (var method in this) {
4743 if (method != "export" && (includeFail || !/^(fail)/.test(method))) {
4744 target[exposedName(prefix, method)] = this[method];
4745 }
4746 }
4747
4748 return target;
4749 },
4750
4751 match: function match(actual, expectation) {
4752 var matcher = sinon.match(expectation);
4753 if (matcher.test(actual)) {
4754 assert.pass("match");
4755 } else {
4756 var formatted = [
4757 "expected value to match",
4758 " expected = " + sinon.format(expectation),
4759 " actual = " + sinon.format(actual)
4760 ]
4761 failAssertion(this, formatted.join("\n"));
4762 }
4763 }
4764 };
4765
4766 mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called");
4767 mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; },
4768 "expected %n to not have been called but was called %c%C");
4769 mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C");
4770 mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C");
4771 mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C");
4772 mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t");
4773 mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t");
4774 mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new");
4775 mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new");
4776 mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C");
4777 mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C");
4778 mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C");
4779 mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C");
4780 mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C");
4781 mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C");
4782 mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C");
4783 mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C");
4784 mirrorPropAsAssertion("threw", "%n did not throw exception%C");
4785 mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C");
4786
4787 if (commonJSModule) {
4788 module.exports = assert;
4789 } else {
4790 sinon.assert = assert;
4791 }
4792 }(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : (typeof self != "undefined") ? self : global));
4793
4794 return sinon;}.call(typeof window != 'undefined' && window || {}));