sinon.js 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142
  1. /**
  2. * Sinon.JS 1.5.0, 2012/10/19
  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-2012, 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. var sinon = (function () {
  36. "use strict";
  37. var buster = (function (setTimeout, B) {
  38. var isNode = typeof require == "function" && typeof module == "object";
  39. var div = typeof document != "undefined" && document.createElement("div");
  40. var F = function () {};
  41. var buster = {
  42. bind: function bind(obj, methOrProp) {
  43. var method = typeof methOrProp == "string" ? obj[methOrProp] : methOrProp;
  44. var args = Array.prototype.slice.call(arguments, 2);
  45. return function () {
  46. var allArgs = args.concat(Array.prototype.slice.call(arguments));
  47. return method.apply(obj, allArgs);
  48. };
  49. },
  50. partial: function partial(fn) {
  51. var args = [].slice.call(arguments, 1);
  52. return function () {
  53. return fn.apply(this, args.concat([].slice.call(arguments)));
  54. };
  55. },
  56. create: function create(object) {
  57. F.prototype = object;
  58. return new F();
  59. },
  60. extend: function extend(target) {
  61. if (!target) { return; }
  62. for (var i = 1, l = arguments.length, prop; i < l; ++i) {
  63. for (prop in arguments[i]) {
  64. target[prop] = arguments[i][prop];
  65. }
  66. }
  67. return target;
  68. },
  69. nextTick: function nextTick(callback) {
  70. if (typeof process != "undefined" && process.nextTick) {
  71. return process.nextTick(callback);
  72. }
  73. setTimeout(callback, 0);
  74. },
  75. functionName: function functionName(func) {
  76. if (!func) return "";
  77. if (func.displayName) return func.displayName;
  78. if (func.name) return func.name;
  79. var matches = func.toString().match(/function\s+([^\(]+)/m);
  80. return matches && matches[1] || "";
  81. },
  82. isNode: function isNode(obj) {
  83. if (!div) return false;
  84. try {
  85. obj.appendChild(div);
  86. obj.removeChild(div);
  87. } catch (e) {
  88. return false;
  89. }
  90. return true;
  91. },
  92. isElement: function isElement(obj) {
  93. return obj && obj.nodeType === 1 && buster.isNode(obj);
  94. },
  95. isArray: function isArray(arr) {
  96. return Object.prototype.toString.call(arr) == "[object Array]";
  97. },
  98. flatten: function flatten(arr) {
  99. var result = [], arr = arr || [];
  100. for (var i = 0, l = arr.length; i < l; ++i) {
  101. result = result.concat(buster.isArray(arr[i]) ? flatten(arr[i]) : arr[i]);
  102. }
  103. return result;
  104. },
  105. each: function each(arr, callback) {
  106. for (var i = 0, l = arr.length; i < l; ++i) {
  107. callback(arr[i]);
  108. }
  109. },
  110. map: function map(arr, callback) {
  111. var results = [];
  112. for (var i = 0, l = arr.length; i < l; ++i) {
  113. results.push(callback(arr[i]));
  114. }
  115. return results;
  116. },
  117. parallel: function parallel(fns, callback) {
  118. function cb(err, res) {
  119. if (typeof callback == "function") {
  120. callback(err, res);
  121. callback = null;
  122. }
  123. }
  124. if (fns.length == 0) { return cb(null, []); }
  125. var remaining = fns.length, results = [];
  126. function makeDone(num) {
  127. return function done(err, result) {
  128. if (err) { return cb(err); }
  129. results[num] = result;
  130. if (--remaining == 0) { cb(null, results); }
  131. };
  132. }
  133. for (var i = 0, l = fns.length; i < l; ++i) {
  134. fns[i](makeDone(i));
  135. }
  136. },
  137. series: function series(fns, callback) {
  138. function cb(err, res) {
  139. if (typeof callback == "function") {
  140. callback(err, res);
  141. }
  142. }
  143. var remaining = fns.slice();
  144. var results = [];
  145. function callNext() {
  146. if (remaining.length == 0) return cb(null, results);
  147. var promise = remaining.shift()(next);
  148. if (promise && typeof promise.then == "function") {
  149. promise.then(buster.partial(next, null), next);
  150. }
  151. }
  152. function next(err, result) {
  153. if (err) return cb(err);
  154. results.push(result);
  155. callNext();
  156. }
  157. callNext();
  158. },
  159. countdown: function countdown(num, done) {
  160. return function () {
  161. if (--num == 0) done();
  162. };
  163. }
  164. };
  165. if (typeof process === "object" &&
  166. typeof require === "function" && typeof module === "object") {
  167. var crypto = require("crypto");
  168. var path = require("path");
  169. buster.tmpFile = function (fileName) {
  170. var hashed = crypto.createHash("sha1");
  171. hashed.update(fileName);
  172. var tmpfileName = hashed.digest("hex");
  173. if (process.platform == "win32") {
  174. return path.join(process.env["TEMP"], tmpfileName);
  175. } else {
  176. return path.join("/tmp", tmpfileName);
  177. }
  178. };
  179. }
  180. if (Array.prototype.some) {
  181. buster.some = function (arr, fn, thisp) {
  182. return arr.some(fn, thisp);
  183. };
  184. } else {
  185. // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
  186. buster.some = function (arr, fun, thisp) {
  187. if (arr == null) { throw new TypeError(); }
  188. arr = Object(arr);
  189. var len = arr.length >>> 0;
  190. if (typeof fun !== "function") { throw new TypeError(); }
  191. for (var i = 0; i < len; i++) {
  192. if (arr.hasOwnProperty(i) && fun.call(thisp, arr[i], i, arr)) {
  193. return true;
  194. }
  195. }
  196. return false;
  197. };
  198. }
  199. if (Array.prototype.filter) {
  200. buster.filter = function (arr, fn, thisp) {
  201. return arr.filter(fn, thisp);
  202. };
  203. } else {
  204. // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
  205. buster.filter = function (fn, thisp) {
  206. if (this == null) { throw new TypeError(); }
  207. var t = Object(this);
  208. var len = t.length >>> 0;
  209. if (typeof fn != "function") { throw new TypeError(); }
  210. var res = [];
  211. for (var i = 0; i < len; i++) {
  212. if (i in t) {
  213. var val = t[i]; // in case fun mutates this
  214. if (fn.call(thisp, val, i, t)) { res.push(val); }
  215. }
  216. }
  217. return res;
  218. };
  219. }
  220. if (isNode) {
  221. module.exports = buster;
  222. buster.eventEmitter = require("./buster-event-emitter");
  223. Object.defineProperty(buster, "defineVersionGetter", {
  224. get: function () {
  225. return require("./define-version-getter");
  226. }
  227. });
  228. }
  229. return buster.extend(B || {}, buster);
  230. }(setTimeout, buster));
  231. if (typeof buster === "undefined") {
  232. var buster = {};
  233. }
  234. if (typeof module === "object" && typeof require === "function") {
  235. buster = require("buster-core");
  236. }
  237. buster.format = buster.format || {};
  238. buster.format.excludeConstructors = ["Object", /^.$/];
  239. buster.format.quoteStrings = true;
  240. buster.format.ascii = (function () {
  241. var hasOwn = Object.prototype.hasOwnProperty;
  242. var specialObjects = [];
  243. if (typeof global != "undefined") {
  244. specialObjects.push({ obj: global, value: "[object global]" });
  245. }
  246. if (typeof document != "undefined") {
  247. specialObjects.push({ obj: document, value: "[object HTMLDocument]" });
  248. }
  249. if (typeof window != "undefined") {
  250. specialObjects.push({ obj: window, value: "[object Window]" });
  251. }
  252. function keys(object) {
  253. var k = Object.keys && Object.keys(object) || [];
  254. if (k.length == 0) {
  255. for (var prop in object) {
  256. if (hasOwn.call(object, prop)) {
  257. k.push(prop);
  258. }
  259. }
  260. }
  261. return k.sort();
  262. }
  263. function isCircular(object, objects) {
  264. if (typeof object != "object") {
  265. return false;
  266. }
  267. for (var i = 0, l = objects.length; i < l; ++i) {
  268. if (objects[i] === object) {
  269. return true;
  270. }
  271. }
  272. return false;
  273. }
  274. function ascii(object, processed, indent) {
  275. if (typeof object == "string") {
  276. var quote = typeof this.quoteStrings != "boolean" || this.quoteStrings;
  277. return processed || quote ? '"' + object + '"' : object;
  278. }
  279. if (typeof object == "function" && !(object instanceof RegExp)) {
  280. return ascii.func(object);
  281. }
  282. processed = processed || [];
  283. if (isCircular(object, processed)) {
  284. return "[Circular]";
  285. }
  286. if (Object.prototype.toString.call(object) == "[object Array]") {
  287. return ascii.array.call(this, object, processed);
  288. }
  289. if (!object) {
  290. return "" + object;
  291. }
  292. if (buster.isElement(object)) {
  293. return ascii.element(object);
  294. }
  295. if (typeof object.toString == "function" &&
  296. object.toString !== Object.prototype.toString) {
  297. return object.toString();
  298. }
  299. for (var i = 0, l = specialObjects.length; i < l; i++) {
  300. if (object === specialObjects[i].obj) {
  301. return specialObjects[i].value;
  302. }
  303. }
  304. return ascii.object.call(this, object, processed, indent);
  305. }
  306. ascii.func = function (func) {
  307. return "function " + buster.functionName(func) + "() {}";
  308. };
  309. ascii.array = function (array, processed) {
  310. processed = processed || [];
  311. processed.push(array);
  312. var pieces = [];
  313. for (var i = 0, l = array.length; i < l; ++i) {
  314. pieces.push(ascii.call(this, array[i], processed));
  315. }
  316. return "[" + pieces.join(", ") + "]";
  317. };
  318. ascii.object = function (object, processed, indent) {
  319. processed = processed || [];
  320. processed.push(object);
  321. indent = indent || 0;
  322. var pieces = [], properties = keys(object), prop, str, obj;
  323. var is = "";
  324. var length = 3;
  325. for (var i = 0, l = indent; i < l; ++i) {
  326. is += " ";
  327. }
  328. for (i = 0, l = properties.length; i < l; ++i) {
  329. prop = properties[i];
  330. obj = object[prop];
  331. if (isCircular(obj, processed)) {
  332. str = "[Circular]";
  333. } else {
  334. str = ascii.call(this, obj, processed, indent + 2);
  335. }
  336. str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str;
  337. length += str.length;
  338. pieces.push(str);
  339. }
  340. var cons = ascii.constructorName.call(this, object);
  341. var prefix = cons ? "[" + cons + "] " : ""
  342. return (length + indent) > 80 ?
  343. prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + is + "}" :
  344. prefix + "{ " + pieces.join(", ") + " }";
  345. };
  346. ascii.element = function (element) {
  347. var tagName = element.tagName.toLowerCase();
  348. var attrs = element.attributes, attribute, pairs = [], attrName;
  349. for (var i = 0, l = attrs.length; i < l; ++i) {
  350. attribute = attrs.item(i);
  351. attrName = attribute.nodeName.toLowerCase().replace("html:", "");
  352. if (attrName == "contenteditable" && attribute.nodeValue == "inherit") {
  353. continue;
  354. }
  355. if (!!attribute.nodeValue) {
  356. pairs.push(attrName + "=\"" + attribute.nodeValue + "\"");
  357. }
  358. }
  359. var formatted = "<" + tagName + (pairs.length > 0 ? " " : "");
  360. var content = element.innerHTML;
  361. if (content.length > 20) {
  362. content = content.substr(0, 20) + "[...]";
  363. }
  364. var res = formatted + pairs.join(" ") + ">" + content + "</" + tagName + ">";
  365. return res.replace(/ contentEditable="inherit"/, "");
  366. };
  367. ascii.constructorName = function (object) {
  368. var name = buster.functionName(object && object.constructor);
  369. var excludes = this.excludeConstructors || buster.format.excludeConstructors || [];
  370. for (var i = 0, l = excludes.length; i < l; ++i) {
  371. if (typeof excludes[i] == "string" && excludes[i] == name) {
  372. return "";
  373. } else if (excludes[i].test && excludes[i].test(name)) {
  374. return "";
  375. }
  376. }
  377. return name;
  378. };
  379. return ascii;
  380. }());
  381. if (typeof module != "undefined") {
  382. module.exports = buster.format;
  383. }
  384. /*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/
  385. /*global module, require, __dirname, document*/
  386. /**
  387. * Sinon core utilities. For internal use only.
  388. *
  389. * @author Christian Johansen (christian@cjohansen.no)
  390. * @license BSD
  391. *
  392. * Copyright (c) 2010-2011 Christian Johansen
  393. */
  394. var sinon = (function (buster) {
  395. var div = typeof document != "undefined" && document.createElement("div");
  396. var hasOwn = Object.prototype.hasOwnProperty;
  397. function isDOMNode(obj) {
  398. var success = false;
  399. try {
  400. obj.appendChild(div);
  401. success = div.parentNode == obj;
  402. } catch (e) {
  403. return false;
  404. } finally {
  405. try {
  406. obj.removeChild(div);
  407. } catch (e) {
  408. // Remove failed, not much we can do about that
  409. }
  410. }
  411. return success;
  412. }
  413. function isElement(obj) {
  414. return div && obj && obj.nodeType === 1 && isDOMNode(obj);
  415. }
  416. function isFunction(obj) {
  417. return !!(obj && obj.constructor && obj.call && obj.apply);
  418. }
  419. function mirrorProperties(target, source) {
  420. for (var prop in source) {
  421. if (!hasOwn.call(target, prop)) {
  422. target[prop] = source[prop];
  423. }
  424. }
  425. }
  426. var sinon = {
  427. wrapMethod: function wrapMethod(object, property, method) {
  428. if (!object) {
  429. throw new TypeError("Should wrap property of object");
  430. }
  431. if (typeof method != "function") {
  432. throw new TypeError("Method wrapper should be function");
  433. }
  434. var wrappedMethod = object[property];
  435. if (!isFunction(wrappedMethod)) {
  436. throw new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " +
  437. property + " as function");
  438. }
  439. if (wrappedMethod.restore && wrappedMethod.restore.sinon) {
  440. throw new TypeError("Attempted to wrap " + property + " which is already wrapped");
  441. }
  442. if (wrappedMethod.calledBefore) {
  443. var verb = !!wrappedMethod.returns ? "stubbed" : "spied on";
  444. throw new TypeError("Attempted to wrap " + property + " which is already " + verb);
  445. }
  446. // IE 8 does not support hasOwnProperty on the window object.
  447. var owned = hasOwn.call(object, property);
  448. object[property] = method;
  449. method.displayName = property;
  450. method.restore = function () {
  451. // For prototype properties try to reset by delete first.
  452. // If this fails (ex: localStorage on mobile safari) then force a reset
  453. // via direct assignment.
  454. if (!owned) {
  455. delete object[property];
  456. }
  457. if (object[property] === method) {
  458. object[property] = wrappedMethod;
  459. }
  460. };
  461. method.restore.sinon = true;
  462. mirrorProperties(method, wrappedMethod);
  463. return method;
  464. },
  465. extend: function extend(target) {
  466. for (var i = 1, l = arguments.length; i < l; i += 1) {
  467. for (var prop in arguments[i]) {
  468. if (arguments[i].hasOwnProperty(prop)) {
  469. target[prop] = arguments[i][prop];
  470. }
  471. // DONT ENUM bug, only care about toString
  472. if (arguments[i].hasOwnProperty("toString") &&
  473. arguments[i].toString != target.toString) {
  474. target.toString = arguments[i].toString;
  475. }
  476. }
  477. }
  478. return target;
  479. },
  480. create: function create(proto) {
  481. var F = function () {};
  482. F.prototype = proto;
  483. return new F();
  484. },
  485. deepEqual: function deepEqual(a, b) {
  486. if (sinon.match && sinon.match.isMatcher(a)) {
  487. return a.test(b);
  488. }
  489. if (typeof a != "object" || typeof b != "object") {
  490. return a === b;
  491. }
  492. if (isElement(a) || isElement(b)) {
  493. return a === b;
  494. }
  495. if (a === b) {
  496. return true;
  497. }
  498. var aString = Object.prototype.toString.call(a);
  499. if (aString != Object.prototype.toString.call(b)) {
  500. return false;
  501. }
  502. if (aString == "[object Array]") {
  503. if (a.length !== b.length) {
  504. return false;
  505. }
  506. for (var i = 0, l = a.length; i < l; i += 1) {
  507. if (!deepEqual(a[i], b[i])) {
  508. return false;
  509. }
  510. }
  511. return true;
  512. }
  513. var prop, aLength = 0, bLength = 0;
  514. for (prop in a) {
  515. aLength += 1;
  516. if (!deepEqual(a[prop], b[prop])) {
  517. return false;
  518. }
  519. }
  520. for (prop in b) {
  521. bLength += 1;
  522. }
  523. if (aLength != bLength) {
  524. return false;
  525. }
  526. return true;
  527. },
  528. functionName: function functionName(func) {
  529. var name = func.displayName || func.name;
  530. // Use function decomposition as a last resort to get function
  531. // name. Does not rely on function decomposition to work - if it
  532. // doesn't debugging will be slightly less informative
  533. // (i.e. toString will say 'spy' rather than 'myFunc').
  534. if (!name) {
  535. var matches = func.toString().match(/function ([^\s\(]+)/);
  536. name = matches && matches[1];
  537. }
  538. return name;
  539. },
  540. functionToString: function toString() {
  541. if (this.getCall && this.callCount) {
  542. var thisValue, prop, i = this.callCount;
  543. while (i--) {
  544. thisValue = this.getCall(i).thisValue;
  545. for (prop in thisValue) {
  546. if (thisValue[prop] === this) {
  547. return prop;
  548. }
  549. }
  550. }
  551. }
  552. return this.displayName || "sinon fake";
  553. },
  554. getConfig: function (custom) {
  555. var config = {};
  556. custom = custom || {};
  557. var defaults = sinon.defaultConfig;
  558. for (var prop in defaults) {
  559. if (defaults.hasOwnProperty(prop)) {
  560. config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop];
  561. }
  562. }
  563. return config;
  564. },
  565. format: function (val) {
  566. return "" + val;
  567. },
  568. defaultConfig: {
  569. injectIntoThis: true,
  570. injectInto: null,
  571. properties: ["spy", "stub", "mock", "clock", "server", "requests"],
  572. useFakeTimers: true,
  573. useFakeServer: true
  574. },
  575. timesInWords: function timesInWords(count) {
  576. return count == 1 && "once" ||
  577. count == 2 && "twice" ||
  578. count == 3 && "thrice" ||
  579. (count || 0) + " times";
  580. },
  581. calledInOrder: function (spies) {
  582. for (var i = 1, l = spies.length; i < l; i++) {
  583. if (!spies[i - 1].calledBefore(spies[i])) {
  584. return false;
  585. }
  586. }
  587. return true;
  588. },
  589. orderByFirstCall: function (spies) {
  590. return spies.sort(function (a, b) {
  591. // uuid, won't ever be equal
  592. var aCall = a.getCall(0);
  593. var bCall = b.getCall(0);
  594. var aId = aCall && aCall.callId || -1;
  595. var bId = bCall && bCall.callId || -1;
  596. return aId < bId ? -1 : 1;
  597. });
  598. },
  599. log: function () {},
  600. logError: function (label, err) {
  601. var msg = label + " threw exception: "
  602. sinon.log(msg + "[" + err.name + "] " + err.message);
  603. if (err.stack) { sinon.log(err.stack); }
  604. setTimeout(function () {
  605. err.message = msg + err.message;
  606. throw err;
  607. }, 0);
  608. },
  609. typeOf: function (value) {
  610. if (value === null) {
  611. return "null";
  612. }
  613. var string = Object.prototype.toString.call(value);
  614. return string.substring(8, string.length - 1).toLowerCase();
  615. }
  616. };
  617. var isNode = typeof module == "object" && typeof require == "function";
  618. if (isNode) {
  619. try {
  620. buster = { format: require("buster-format") };
  621. } catch (e) {}
  622. module.exports = sinon;
  623. module.exports.spy = require("./sinon/spy");
  624. module.exports.stub = require("./sinon/stub");
  625. module.exports.mock = require("./sinon/mock");
  626. module.exports.collection = require("./sinon/collection");
  627. module.exports.assert = require("./sinon/assert");
  628. module.exports.sandbox = require("./sinon/sandbox");
  629. module.exports.test = require("./sinon/test");
  630. module.exports.testCase = require("./sinon/test_case");
  631. module.exports.assert = require("./sinon/assert");
  632. module.exports.match = require("./sinon/match");
  633. }
  634. if (buster) {
  635. var formatter = sinon.create(buster.format);
  636. formatter.quoteStrings = false;
  637. sinon.format = function () {
  638. return formatter.ascii.apply(formatter, arguments);
  639. };
  640. } else if (isNode) {
  641. try {
  642. var util = require("util");
  643. sinon.format = function (value) {
  644. return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value;
  645. };
  646. } catch (e) {
  647. /* Node, but no util module - would be very old, but better safe than
  648. sorry */
  649. }
  650. }
  651. return sinon;
  652. }(typeof buster == "object" && buster));
  653. /* @depend ../sinon.js */
  654. /*jslint eqeqeq: false, onevar: false, plusplus: false*/
  655. /*global module, require, sinon*/
  656. /**
  657. * Match functions
  658. *
  659. * @author Maximilian Antoni (mail@maxantoni.de)
  660. * @license BSD
  661. *
  662. * Copyright (c) 2012 Maximilian Antoni
  663. */
  664. (function (sinon) {
  665. var commonJSModule = typeof module == "object" && typeof require == "function";
  666. if (!sinon && commonJSModule) {
  667. sinon = require("../sinon");
  668. }
  669. if (!sinon) {
  670. return;
  671. }
  672. function assertType(value, type, name) {
  673. var actual = sinon.typeOf(value);
  674. if (actual !== type) {
  675. throw new TypeError("Expected type of " + name + " to be " +
  676. type + ", but was " + actual);
  677. }
  678. }
  679. var matcher = {
  680. toString: function () {
  681. return this.message;
  682. }
  683. };
  684. function isMatcher(object) {
  685. return matcher.isPrototypeOf(object);
  686. }
  687. function matchObject(expectation, actual) {
  688. if (actual === null || actual === undefined) {
  689. return false;
  690. }
  691. for (var key in expectation) {
  692. if (expectation.hasOwnProperty(key)) {
  693. var exp = expectation[key];
  694. var act = actual[key];
  695. if (match.isMatcher(exp)) {
  696. if (!exp.test(act)) {
  697. return false;
  698. }
  699. } else if (sinon.typeOf(exp) === "object") {
  700. if (!matchObject(exp, act)) {
  701. return false;
  702. }
  703. } else if (!sinon.deepEqual(exp, act)) {
  704. return false;
  705. }
  706. }
  707. }
  708. return true;
  709. }
  710. matcher.or = function (m2) {
  711. if (!isMatcher(m2)) {
  712. throw new TypeError("Matcher expected");
  713. }
  714. var m1 = this;
  715. var or = sinon.create(matcher);
  716. or.test = function (actual) {
  717. return m1.test(actual) || m2.test(actual);
  718. };
  719. or.message = m1.message + ".or(" + m2.message + ")";
  720. return or;
  721. };
  722. matcher.and = function (m2) {
  723. if (!isMatcher(m2)) {
  724. throw new TypeError("Matcher expected");
  725. }
  726. var m1 = this;
  727. var and = sinon.create(matcher);
  728. and.test = function (actual) {
  729. return m1.test(actual) && m2.test(actual);
  730. };
  731. and.message = m1.message + ".and(" + m2.message + ")";
  732. return and;
  733. };
  734. var match = function (expectation, message) {
  735. var m = sinon.create(matcher);
  736. var type = sinon.typeOf(expectation);
  737. switch (type) {
  738. case "object":
  739. if (typeof expectation.test === "function") {
  740. m.test = function (actual) {
  741. return expectation.test(actual) === true;
  742. };
  743. m.message = "match(" + sinon.functionName(expectation.test) + ")";
  744. return m;
  745. }
  746. var str = [];
  747. for (var key in expectation) {
  748. if (expectation.hasOwnProperty(key)) {
  749. str.push(key + ": " + expectation[key]);
  750. }
  751. }
  752. m.test = function (actual) {
  753. return matchObject(expectation, actual);
  754. };
  755. m.message = "match(" + str.join(", ") + ")";
  756. break;
  757. case "number":
  758. m.test = function (actual) {
  759. return expectation == actual;
  760. };
  761. break;
  762. case "string":
  763. m.test = function (actual) {
  764. if (typeof actual !== "string") {
  765. return false;
  766. }
  767. return actual.indexOf(expectation) !== -1;
  768. };
  769. m.message = "match(\"" + expectation + "\")";
  770. break;
  771. case "regexp":
  772. m.test = function (actual) {
  773. if (typeof actual !== "string") {
  774. return false;
  775. }
  776. return expectation.test(actual);
  777. };
  778. break;
  779. case "function":
  780. m.test = expectation;
  781. if (message) {
  782. m.message = message;
  783. } else {
  784. m.message = "match(" + sinon.functionName(expectation) + ")";
  785. }
  786. break;
  787. default:
  788. m.test = function (actual) {
  789. return sinon.deepEqual(expectation, actual);
  790. };
  791. }
  792. if (!m.message) {
  793. m.message = "match(" + expectation + ")";
  794. }
  795. return m;
  796. };
  797. match.isMatcher = isMatcher;
  798. match.any = match(function () {
  799. return true;
  800. }, "any");
  801. match.defined = match(function (actual) {
  802. return actual !== null && actual !== undefined;
  803. }, "defined");
  804. match.truthy = match(function (actual) {
  805. return !!actual;
  806. }, "truthy");
  807. match.falsy = match(function (actual) {
  808. return !actual;
  809. }, "falsy");
  810. match.same = function (expectation) {
  811. return match(function (actual) {
  812. return expectation === actual;
  813. }, "same(" + expectation + ")");
  814. };
  815. match.typeOf = function (type) {
  816. assertType(type, "string", "type");
  817. return match(function (actual) {
  818. return sinon.typeOf(actual) === type;
  819. }, "typeOf(\"" + type + "\")");
  820. };
  821. match.instanceOf = function (type) {
  822. assertType(type, "function", "type");
  823. return match(function (actual) {
  824. return actual instanceof type;
  825. }, "instanceOf(" + sinon.functionName(type) + ")");
  826. };
  827. function createPropertyMatcher(propertyTest, messagePrefix) {
  828. return function (property, value) {
  829. assertType(property, "string", "property");
  830. var onlyProperty = arguments.length === 1;
  831. var message = messagePrefix + "(\"" + property + "\"";
  832. if (!onlyProperty) {
  833. message += ", " + value;
  834. }
  835. message += ")";
  836. return match(function (actual) {
  837. if (actual === undefined || actual === null ||
  838. !propertyTest(actual, property)) {
  839. return false;
  840. }
  841. return onlyProperty || sinon.deepEqual(value, actual[property]);
  842. }, message);
  843. };
  844. }
  845. match.has = createPropertyMatcher(function (actual, property) {
  846. if (typeof actual === "object") {
  847. return property in actual;
  848. }
  849. return actual[property] !== undefined;
  850. }, "has");
  851. match.hasOwn = createPropertyMatcher(function (actual, property) {
  852. return actual.hasOwnProperty(property);
  853. }, "hasOwn");
  854. match.bool = match.typeOf("boolean");
  855. match.number = match.typeOf("number");
  856. match.string = match.typeOf("string");
  857. match.object = match.typeOf("object");
  858. match.func = match.typeOf("function");
  859. match.array = match.typeOf("array");
  860. match.regexp = match.typeOf("regexp");
  861. match.date = match.typeOf("date");
  862. if (commonJSModule) {
  863. module.exports = match;
  864. } else {
  865. sinon.match = match;
  866. }
  867. }(typeof sinon == "object" && sinon || null));
  868. /**
  869. * @depend ../sinon.js
  870. * @depend match.js
  871. */
  872. /*jslint eqeqeq: false, onevar: false, plusplus: false*/
  873. /*global module, require, sinon*/
  874. /**
  875. * Spy functions
  876. *
  877. * @author Christian Johansen (christian@cjohansen.no)
  878. * @license BSD
  879. *
  880. * Copyright (c) 2010-2011 Christian Johansen
  881. */
  882. (function (sinon) {
  883. var commonJSModule = typeof module == "object" && typeof require == "function";
  884. var spyCall;
  885. var callId = 0;
  886. var push = [].push;
  887. var slice = Array.prototype.slice;
  888. if (!sinon && commonJSModule) {
  889. sinon = require("../sinon");
  890. }
  891. if (!sinon) {
  892. return;
  893. }
  894. function spy(object, property) {
  895. if (!property && typeof object == "function") {
  896. return spy.create(object);
  897. }
  898. if (!object && !property) {
  899. return spy.create(function () {});
  900. }
  901. var method = object[property];
  902. return sinon.wrapMethod(object, property, spy.create(method));
  903. }
  904. sinon.extend(spy, (function () {
  905. function delegateToCalls(api, method, matchAny, actual, notCalled) {
  906. api[method] = function () {
  907. if (!this.called) {
  908. if (notCalled) {
  909. return notCalled.apply(this, arguments);
  910. }
  911. return false;
  912. }
  913. var currentCall;
  914. var matches = 0;
  915. for (var i = 0, l = this.callCount; i < l; i += 1) {
  916. currentCall = this.getCall(i);
  917. if (currentCall[actual || method].apply(currentCall, arguments)) {
  918. matches += 1;
  919. if (matchAny) {
  920. return true;
  921. }
  922. }
  923. }
  924. return matches === this.callCount;
  925. };
  926. }
  927. function matchingFake(fakes, args, strict) {
  928. if (!fakes) {
  929. return;
  930. }
  931. var alen = args.length;
  932. for (var i = 0, l = fakes.length; i < l; i++) {
  933. if (fakes[i].matches(args, strict)) {
  934. return fakes[i];
  935. }
  936. }
  937. }
  938. function incrementCallCount() {
  939. this.called = true;
  940. this.callCount += 1;
  941. this.notCalled = false;
  942. this.calledOnce = this.callCount == 1;
  943. this.calledTwice = this.callCount == 2;
  944. this.calledThrice = this.callCount == 3;
  945. }
  946. function createCallProperties() {
  947. this.firstCall = this.getCall(0);
  948. this.secondCall = this.getCall(1);
  949. this.thirdCall = this.getCall(2);
  950. this.lastCall = this.getCall(this.callCount - 1);
  951. }
  952. var vars = "a,b,c,d,e,f,g,h,i,j,k,l";
  953. function createProxy(func) {
  954. // Retain the function length:
  955. if (func.length) {
  956. return eval("(function proxy(" + vars.substring(0, func.length * 2 - 1) +
  957. ") { return proxy.invoke(func, this, slice.call(arguments)); })");
  958. }
  959. return function proxy() {
  960. return proxy.invoke(func, this, slice.call(arguments));
  961. };
  962. }
  963. var uuid = 0;
  964. // Public API
  965. var spyApi = {
  966. reset: function () {
  967. this.called = false;
  968. this.notCalled = true;
  969. this.calledOnce = false;
  970. this.calledTwice = false;
  971. this.calledThrice = false;
  972. this.callCount = 0;
  973. this.firstCall = null;
  974. this.secondCall = null;
  975. this.thirdCall = null;
  976. this.lastCall = null;
  977. this.args = [];
  978. this.returnValues = [];
  979. this.thisValues = [];
  980. this.exceptions = [];
  981. this.callIds = [];
  982. if (this.fakes) {
  983. for (var i = 0; i < this.fakes.length; i++) {
  984. this.fakes[i].reset();
  985. }
  986. }
  987. },
  988. create: function create(func) {
  989. var name;
  990. if (typeof func != "function") {
  991. func = function () {};
  992. } else {
  993. name = sinon.functionName(func);
  994. }
  995. var proxy = createProxy(func);
  996. sinon.extend(proxy, spy);
  997. delete proxy.create;
  998. sinon.extend(proxy, func);
  999. proxy.reset();
  1000. proxy.prototype = func.prototype;
  1001. proxy.displayName = name || "spy";
  1002. proxy.toString = sinon.functionToString;
  1003. proxy._create = sinon.spy.create;
  1004. proxy.id = "spy#" + uuid++;
  1005. return proxy;
  1006. },
  1007. invoke: function invoke(func, thisValue, args) {
  1008. var matching = matchingFake(this.fakes, args);
  1009. var exception, returnValue;
  1010. incrementCallCount.call(this);
  1011. push.call(this.thisValues, thisValue);
  1012. push.call(this.args, args);
  1013. push.call(this.callIds, callId++);
  1014. try {
  1015. if (matching) {
  1016. returnValue = matching.invoke(func, thisValue, args);
  1017. } else {
  1018. returnValue = (this.func || func).apply(thisValue, args);
  1019. }
  1020. } catch (e) {
  1021. push.call(this.returnValues, undefined);
  1022. exception = e;
  1023. throw e;
  1024. } finally {
  1025. push.call(this.exceptions, exception);
  1026. }
  1027. push.call(this.returnValues, returnValue);
  1028. createCallProperties.call(this);
  1029. return returnValue;
  1030. },
  1031. getCall: function getCall(i) {
  1032. if (i < 0 || i >= this.callCount) {
  1033. return null;
  1034. }
  1035. return spyCall.create(this, this.thisValues[i], this.args[i],
  1036. this.returnValues[i], this.exceptions[i],
  1037. this.callIds[i]);
  1038. },
  1039. calledBefore: function calledBefore(spyFn) {
  1040. if (!this.called) {
  1041. return false;
  1042. }
  1043. if (!spyFn.called) {
  1044. return true;
  1045. }
  1046. return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1];
  1047. },
  1048. calledAfter: function calledAfter(spyFn) {
  1049. if (!this.called || !spyFn.called) {
  1050. return false;
  1051. }
  1052. return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1];
  1053. },
  1054. withArgs: function () {
  1055. var args = slice.call(arguments);
  1056. if (this.fakes) {
  1057. var match = matchingFake(this.fakes, args, true);
  1058. if (match) {
  1059. return match;
  1060. }
  1061. } else {
  1062. this.fakes = [];
  1063. }
  1064. var original = this;
  1065. var fake = this._create();
  1066. fake.matchingAguments = args;
  1067. push.call(this.fakes, fake);
  1068. fake.withArgs = function () {
  1069. return original.withArgs.apply(original, arguments);
  1070. };
  1071. for (var i = 0; i < this.args.length; i++) {
  1072. if (fake.matches(this.args[i])) {
  1073. incrementCallCount.call(fake);
  1074. push.call(fake.thisValues, this.thisValues[i]);
  1075. push.call(fake.args, this.args[i]);
  1076. push.call(fake.returnValues, this.returnValues[i]);
  1077. push.call(fake.exceptions, this.exceptions[i]);
  1078. push.call(fake.callIds, this.callIds[i]);
  1079. }
  1080. }
  1081. createCallProperties.call(fake);
  1082. return fake;
  1083. },
  1084. matches: function (args, strict) {
  1085. var margs = this.matchingAguments;
  1086. if (margs.length <= args.length &&
  1087. sinon.deepEqual(margs, args.slice(0, margs.length))) {
  1088. return !strict || margs.length == args.length;
  1089. }
  1090. },
  1091. printf: function (format) {
  1092. var spy = this;
  1093. var args = slice.call(arguments, 1);
  1094. var formatter;
  1095. return (format || "").replace(/%(.)/g, function (match, specifyer) {
  1096. formatter = spyApi.formatters[specifyer];
  1097. if (typeof formatter == "function") {
  1098. return formatter.call(null, spy, args);
  1099. } else if (!isNaN(parseInt(specifyer), 10)) {
  1100. return sinon.format(args[specifyer - 1]);
  1101. }
  1102. return "%" + specifyer;
  1103. });
  1104. }
  1105. };
  1106. delegateToCalls(spyApi, "calledOn", true);
  1107. delegateToCalls(spyApi, "alwaysCalledOn", false, "calledOn");
  1108. delegateToCalls(spyApi, "calledWith", true);
  1109. delegateToCalls(spyApi, "calledWithMatch", true);
  1110. delegateToCalls(spyApi, "alwaysCalledWith", false, "calledWith");
  1111. delegateToCalls(spyApi, "alwaysCalledWithMatch", false, "calledWithMatch");
  1112. delegateToCalls(spyApi, "calledWithExactly", true);
  1113. delegateToCalls(spyApi, "alwaysCalledWithExactly", false, "calledWithExactly");
  1114. delegateToCalls(spyApi, "neverCalledWith", false, "notCalledWith",
  1115. function () { return true; });
  1116. delegateToCalls(spyApi, "neverCalledWithMatch", false, "notCalledWithMatch",
  1117. function () { return true; });
  1118. delegateToCalls(spyApi, "threw", true);
  1119. delegateToCalls(spyApi, "alwaysThrew", false, "threw");
  1120. delegateToCalls(spyApi, "returned", true);
  1121. delegateToCalls(spyApi, "alwaysReturned", false, "returned");
  1122. delegateToCalls(spyApi, "calledWithNew", true);
  1123. delegateToCalls(spyApi, "alwaysCalledWithNew", false, "calledWithNew");
  1124. delegateToCalls(spyApi, "callArg", false, "callArgWith", function () {
  1125. throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
  1126. });
  1127. spyApi.callArgWith = spyApi.callArg;
  1128. delegateToCalls(spyApi, "yield", false, "yield", function () {
  1129. throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
  1130. });
  1131. // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode.
  1132. spyApi.invokeCallback = spyApi.yield;
  1133. delegateToCalls(spyApi, "yieldTo", false, "yieldTo", function (property) {
  1134. throw new Error(this.toString() + " cannot yield to '" + property +
  1135. "' since it was not yet invoked.");
  1136. });
  1137. spyApi.formatters = {
  1138. "c": function (spy) {
  1139. return sinon.timesInWords(spy.callCount);
  1140. },
  1141. "n": function (spy) {
  1142. return spy.toString();
  1143. },
  1144. "C": function (spy) {
  1145. var calls = [];
  1146. for (var i = 0, l = spy.callCount; i < l; ++i) {
  1147. push.call(calls, " " + spy.getCall(i).toString());
  1148. }
  1149. return calls.length > 0 ? "\n" + calls.join("\n") : "";
  1150. },
  1151. "t": function (spy) {
  1152. var objects = [];
  1153. for (var i = 0, l = spy.callCount; i < l; ++i) {
  1154. push.call(objects, sinon.format(spy.thisValues[i]));
  1155. }
  1156. return objects.join(", ");
  1157. },
  1158. "*": function (spy, args) {
  1159. var formatted = [];
  1160. for (var i = 0, l = args.length; i < l; ++i) {
  1161. push.call(formatted, sinon.format(args[i]));
  1162. }
  1163. return formatted.join(", ");
  1164. }
  1165. };
  1166. return spyApi;
  1167. }()));
  1168. spyCall = (function () {
  1169. function throwYieldError(proxy, text, args) {
  1170. var msg = sinon.functionName(proxy) + text;
  1171. if (args.length) {
  1172. msg += " Received [" + slice.call(args).join(", ") + "]";
  1173. }
  1174. throw new Error(msg);
  1175. }
  1176. var callApi = {
  1177. create: function create(spy, thisValue, args, returnValue, exception, id) {
  1178. var proxyCall = sinon.create(spyCall);
  1179. delete proxyCall.create;
  1180. proxyCall.proxy = spy;
  1181. proxyCall.thisValue = thisValue;
  1182. proxyCall.args = args;
  1183. proxyCall.returnValue = returnValue;
  1184. proxyCall.exception = exception;
  1185. proxyCall.callId = typeof id == "number" && id || callId++;
  1186. return proxyCall;
  1187. },
  1188. calledOn: function calledOn(thisValue) {
  1189. if (sinon.match && sinon.match.isMatcher(thisValue)) {
  1190. return thisValue.test(this.thisValue);
  1191. }
  1192. return this.thisValue === thisValue;
  1193. },
  1194. calledWith: function calledWith() {
  1195. for (var i = 0, l = arguments.length; i < l; i += 1) {
  1196. if (!sinon.deepEqual(arguments[i], this.args[i])) {
  1197. return false;
  1198. }
  1199. }
  1200. return true;
  1201. },
  1202. calledWithMatch: function calledWithMatch() {
  1203. for (var i = 0, l = arguments.length; i < l; i += 1) {
  1204. var actual = this.args[i];
  1205. var expectation = arguments[i];
  1206. if (!sinon.match || !sinon.match(expectation).test(actual)) {
  1207. return false;
  1208. }
  1209. }
  1210. return true;
  1211. },
  1212. calledWithExactly: function calledWithExactly() {
  1213. return arguments.length == this.args.length &&
  1214. this.calledWith.apply(this, arguments);
  1215. },
  1216. notCalledWith: function notCalledWith() {
  1217. return !this.calledWith.apply(this, arguments);
  1218. },
  1219. notCalledWithMatch: function notCalledWithMatch() {
  1220. return !this.calledWithMatch.apply(this, arguments);
  1221. },
  1222. returned: function returned(value) {
  1223. return sinon.deepEqual(value, this.returnValue);
  1224. },
  1225. threw: function threw(error) {
  1226. if (typeof error == "undefined" || !this.exception) {
  1227. return !!this.exception;
  1228. }
  1229. if (typeof error == "string") {
  1230. return this.exception.name == error;
  1231. }
  1232. return this.exception === error;
  1233. },
  1234. calledWithNew: function calledWithNew(thisValue) {
  1235. return this.thisValue instanceof this.proxy;
  1236. },
  1237. calledBefore: function (other) {
  1238. return this.callId < other.callId;
  1239. },
  1240. calledAfter: function (other) {
  1241. return this.callId > other.callId;
  1242. },
  1243. callArg: function (pos) {
  1244. this.args[pos]();
  1245. },
  1246. callArgWith: function (pos) {
  1247. var args = slice.call(arguments, 1);
  1248. this.args[pos].apply(null, args);
  1249. },
  1250. "yield": function () {
  1251. var args = this.args;
  1252. for (var i = 0, l = args.length; i < l; ++i) {
  1253. if (typeof args[i] === "function") {
  1254. args[i].apply(null, slice.call(arguments));
  1255. return;
  1256. }
  1257. }
  1258. throwYieldError(this.proxy, " cannot yield since no callback was passed.", args);
  1259. },
  1260. yieldTo: function (prop) {
  1261. var args = this.args;
  1262. for (var i = 0, l = args.length; i < l; ++i) {
  1263. if (args[i] && typeof args[i][prop] === "function") {
  1264. args[i][prop].apply(null, slice.call(arguments, 1));
  1265. return;
  1266. }
  1267. }
  1268. throwYieldError(this.proxy, " cannot yield to '" + prop +
  1269. "' since no callback was passed.", args);
  1270. },
  1271. toString: function () {
  1272. var callStr = this.proxy.toString() + "(";
  1273. var args = [];
  1274. for (var i = 0, l = this.args.length; i < l; ++i) {
  1275. push.call(args, sinon.format(this.args[i]));
  1276. }
  1277. callStr = callStr + args.join(", ") + ")";
  1278. if (typeof this.returnValue != "undefined") {
  1279. callStr += " => " + sinon.format(this.returnValue);
  1280. }
  1281. if (this.exception) {
  1282. callStr += " !" + this.exception.name;
  1283. if (this.exception.message) {
  1284. callStr += "(" + this.exception.message + ")";
  1285. }
  1286. }
  1287. return callStr;
  1288. }
  1289. };
  1290. callApi.invokeCallback = callApi.yield;
  1291. return callApi;
  1292. }());
  1293. spy.spyCall = spyCall;
  1294. // This steps outside the module sandbox and will be removed
  1295. sinon.spyCall = spyCall;
  1296. if (commonJSModule) {
  1297. module.exports = spy;
  1298. } else {
  1299. sinon.spy = spy;
  1300. }
  1301. }(typeof sinon == "object" && sinon || null));
  1302. /**
  1303. * @depend ../sinon.js
  1304. * @depend spy.js
  1305. */
  1306. /*jslint eqeqeq: false, onevar: false*/
  1307. /*global module, require, sinon*/
  1308. /**
  1309. * Stub functions
  1310. *
  1311. * @author Christian Johansen (christian@cjohansen.no)
  1312. * @license BSD
  1313. *
  1314. * Copyright (c) 2010-2011 Christian Johansen
  1315. */
  1316. (function (sinon) {
  1317. var commonJSModule = typeof module == "object" && typeof require == "function";
  1318. if (!sinon && commonJSModule) {
  1319. sinon = require("../sinon");
  1320. }
  1321. if (!sinon) {
  1322. return;
  1323. }
  1324. function stub(object, property, func) {
  1325. if (!!func && typeof func != "function") {
  1326. throw new TypeError("Custom stub should be function");
  1327. }
  1328. var wrapper;
  1329. if (func) {
  1330. wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func;
  1331. } else {
  1332. wrapper = stub.create();
  1333. }
  1334. if (!object && !property) {
  1335. return sinon.stub.create();
  1336. }
  1337. if (!property && !!object && typeof object == "object") {
  1338. for (var prop in object) {
  1339. if (typeof object[prop] === "function") {
  1340. stub(object, prop);
  1341. }
  1342. }
  1343. return object;
  1344. }
  1345. return sinon.wrapMethod(object, property, wrapper);
  1346. }
  1347. function getChangingValue(stub, property) {
  1348. var index = stub.callCount - 1;
  1349. var prop = index in stub[property] ? stub[property][index] : stub[property + "Last"];
  1350. stub[property + "Last"] = prop;
  1351. return prop;
  1352. }
  1353. function getCallback(stub, args) {
  1354. var callArgAt = getChangingValue(stub, "callArgAts");
  1355. if (callArgAt < 0) {
  1356. var callArgProp = getChangingValue(stub, "callArgProps");
  1357. for (var i = 0, l = args.length; i < l; ++i) {
  1358. if (!callArgProp && typeof args[i] == "function") {
  1359. return args[i];
  1360. }
  1361. if (callArgProp && args[i] &&
  1362. typeof args[i][callArgProp] == "function") {
  1363. return args[i][callArgProp];
  1364. }
  1365. }
  1366. return null;
  1367. }
  1368. return args[callArgAt];
  1369. }
  1370. var join = Array.prototype.join;
  1371. function getCallbackError(stub, func, args) {
  1372. if (stub.callArgAtsLast < 0) {
  1373. var msg;
  1374. if (stub.callArgPropsLast) {
  1375. msg = sinon.functionName(stub) +
  1376. " expected to yield to '" + stub.callArgPropsLast +
  1377. "', but no object with such a property was passed."
  1378. } else {
  1379. msg = sinon.functionName(stub) +
  1380. " expected to yield, but no callback was passed."
  1381. }
  1382. if (args.length > 0) {
  1383. msg += " Received [" + join.call(args, ", ") + "]";
  1384. }
  1385. return msg;
  1386. }
  1387. return "argument at index " + stub.callArgAtsLast + " is not a function: " + func;
  1388. }
  1389. var nextTick = (function () {
  1390. if (typeof process === "object" && typeof process.nextTick === "function") {
  1391. return process.nextTick;
  1392. } else if (typeof msSetImmediate === "function") {
  1393. return msSetImmediate.bind(window);
  1394. } else if (typeof setImmediate === "function") {
  1395. return setImmediate;
  1396. } else {
  1397. return function (callback) {
  1398. setTimeout(callback, 0);
  1399. };
  1400. }
  1401. })();
  1402. function callCallback(stub, args) {
  1403. if (stub.callArgAts.length > 0) {
  1404. var func = getCallback(stub, args);
  1405. if (typeof func != "function") {
  1406. throw new TypeError(getCallbackError(stub, func, args));
  1407. }
  1408. var index = stub.callCount - 1;
  1409. var callbackArguments = getChangingValue(stub, "callbackArguments");
  1410. var callbackContext = getChangingValue(stub, "callbackContexts");
  1411. if (stub.callbackAsync) {
  1412. nextTick(function() {
  1413. func.apply(callbackContext, callbackArguments);
  1414. });
  1415. } else {
  1416. func.apply(callbackContext, callbackArguments);
  1417. }
  1418. }
  1419. }
  1420. var uuid = 0;
  1421. sinon.extend(stub, (function () {
  1422. var slice = Array.prototype.slice, proto;
  1423. function throwsException(error, message) {
  1424. if (typeof error == "string") {
  1425. this.exception = new Error(message || "");
  1426. this.exception.name = error;
  1427. } else if (!error) {
  1428. this.exception = new Error("Error");
  1429. } else {
  1430. this.exception = error;
  1431. }
  1432. return this;
  1433. }
  1434. proto = {
  1435. create: function create() {
  1436. var functionStub = function () {
  1437. callCallback(functionStub, arguments);
  1438. if (functionStub.exception) {
  1439. throw functionStub.exception;
  1440. } else if (typeof functionStub.returnArgAt == 'number') {
  1441. return arguments[functionStub.returnArgAt];
  1442. } else if (functionStub.returnThis) {
  1443. return this;
  1444. }
  1445. return functionStub.returnValue;
  1446. };
  1447. functionStub.id = "stub#" + uuid++;
  1448. var orig = functionStub;
  1449. functionStub = sinon.spy.create(functionStub);
  1450. functionStub.func = orig;
  1451. functionStub.callArgAts = [];
  1452. functionStub.callbackArguments = [];
  1453. functionStub.callbackContexts = [];
  1454. functionStub.callArgProps = [];
  1455. sinon.extend(functionStub, stub);
  1456. functionStub._create = sinon.stub.create;
  1457. functionStub.displayName = "stub";
  1458. functionStub.toString = sinon.functionToString;
  1459. return functionStub;
  1460. },
  1461. returns: function returns(value) {
  1462. this.returnValue = value;
  1463. return this;
  1464. },
  1465. returnsArg: function returnsArg(pos) {
  1466. if (typeof pos != "number") {
  1467. throw new TypeError("argument index is not number");
  1468. }
  1469. this.returnArgAt = pos;
  1470. return this;
  1471. },
  1472. returnsThis: function returnsThis() {
  1473. this.returnThis = true;
  1474. return this;
  1475. },
  1476. "throws": throwsException,
  1477. throwsException: throwsException,
  1478. callsArg: function callsArg(pos) {
  1479. if (typeof pos != "number") {
  1480. throw new TypeError("argument index is not number");
  1481. }
  1482. this.callArgAts.push(pos);
  1483. this.callbackArguments.push([]);
  1484. this.callbackContexts.push(undefined);
  1485. this.callArgProps.push(undefined);
  1486. return this;
  1487. },
  1488. callsArgOn: function callsArgOn(pos, context) {
  1489. if (typeof pos != "number") {
  1490. throw new TypeError("argument index is not number");
  1491. }
  1492. if (typeof context != "object") {
  1493. throw new TypeError("argument context is not an object");
  1494. }
  1495. this.callArgAts.push(pos);
  1496. this.callbackArguments.push([]);
  1497. this.callbackContexts.push(context);
  1498. this.callArgProps.push(undefined);
  1499. return this;
  1500. },
  1501. callsArgWith: function callsArgWith(pos) {
  1502. if (typeof pos != "number") {
  1503. throw new TypeError("argument index is not number");
  1504. }
  1505. this.callArgAts.push(pos);
  1506. this.callbackArguments.push(slice.call(arguments, 1));
  1507. this.callbackContexts.push(undefined);
  1508. this.callArgProps.push(undefined);
  1509. return this;
  1510. },
  1511. callsArgOnWith: function callsArgWith(pos, context) {
  1512. if (typeof pos != "number") {
  1513. throw new TypeError("argument index is not number");
  1514. }
  1515. if (typeof context != "object") {
  1516. throw new TypeError("argument context is not an object");
  1517. }
  1518. this.callArgAts.push(pos);
  1519. this.callbackArguments.push(slice.call(arguments, 2));
  1520. this.callbackContexts.push(context);
  1521. this.callArgProps.push(undefined);
  1522. return this;
  1523. },
  1524. yields: function () {
  1525. this.callArgAts.push(-1);
  1526. this.callbackArguments.push(slice.call(arguments, 0));
  1527. this.callbackContexts.push(undefined);
  1528. this.callArgProps.push(undefined);
  1529. return this;
  1530. },
  1531. yieldsOn: function (context) {
  1532. if (typeof context != "object") {
  1533. throw new TypeError("argument context is not an object");
  1534. }
  1535. this.callArgAts.push(-1);
  1536. this.callbackArguments.push(slice.call(arguments, 1));
  1537. this.callbackContexts.push(context);
  1538. this.callArgProps.push(undefined);
  1539. return this;
  1540. },
  1541. yieldsTo: function (prop) {
  1542. this.callArgAts.push(-1);
  1543. this.callbackArguments.push(slice.call(arguments, 1));
  1544. this.callbackContexts.push(undefined);
  1545. this.callArgProps.push(prop);
  1546. return this;
  1547. },
  1548. yieldsToOn: function (prop, context) {
  1549. if (typeof context != "object") {
  1550. throw new TypeError("argument context is not an object");
  1551. }
  1552. this.callArgAts.push(-1);
  1553. this.callbackArguments.push(slice.call(arguments, 2));
  1554. this.callbackContexts.push(context);
  1555. this.callArgProps.push(prop);
  1556. return this;
  1557. }
  1558. };
  1559. // create asynchronous versions of callsArg* and yields* methods
  1560. for (var method in proto) {
  1561. // need to avoid creating anotherasync versions of the newly added async methods
  1562. if (proto.hasOwnProperty(method) &&
  1563. method.match(/^(callsArg|yields|thenYields$)/) &&
  1564. !method.match(/Async/)) {
  1565. proto[method + 'Async'] = (function (syncFnName) {
  1566. return function () {
  1567. this.callbackAsync = true;
  1568. return this[syncFnName].apply(this, arguments);
  1569. };
  1570. })(method);
  1571. }
  1572. }
  1573. return proto;
  1574. }()));
  1575. if (commonJSModule) {
  1576. module.exports = stub;
  1577. } else {
  1578. sinon.stub = stub;
  1579. }
  1580. }(typeof sinon == "object" && sinon || null));
  1581. /**
  1582. * @depend ../sinon.js
  1583. * @depend stub.js
  1584. */
  1585. /*jslint eqeqeq: false, onevar: false, nomen: false*/
  1586. /*global module, require, sinon*/
  1587. /**
  1588. * Mock functions.
  1589. *
  1590. * @author Christian Johansen (christian@cjohansen.no)
  1591. * @license BSD
  1592. *
  1593. * Copyright (c) 2010-2011 Christian Johansen
  1594. */
  1595. (function (sinon) {
  1596. var commonJSModule = typeof module == "object" && typeof require == "function";
  1597. var push = [].push;
  1598. if (!sinon && commonJSModule) {
  1599. sinon = require("../sinon");
  1600. }
  1601. if (!sinon) {
  1602. return;
  1603. }
  1604. function mock(object) {
  1605. if (!object) {
  1606. return sinon.expectation.create("Anonymous mock");
  1607. }
  1608. return mock.create(object);
  1609. }
  1610. sinon.mock = mock;
  1611. sinon.extend(mock, (function () {
  1612. function each(collection, callback) {
  1613. if (!collection) {
  1614. return;
  1615. }
  1616. for (var i = 0, l = collection.length; i < l; i += 1) {
  1617. callback(collection[i]);
  1618. }
  1619. }
  1620. return {
  1621. create: function create(object) {
  1622. if (!object) {
  1623. throw new TypeError("object is null");
  1624. }
  1625. var mockObject = sinon.extend({}, mock);
  1626. mockObject.object = object;
  1627. delete mockObject.create;
  1628. return mockObject;
  1629. },
  1630. expects: function expects(method) {
  1631. if (!method) {
  1632. throw new TypeError("method is falsy");
  1633. }
  1634. if (!this.expectations) {
  1635. this.expectations = {};
  1636. this.proxies = [];
  1637. }
  1638. if (!this.expectations[method]) {
  1639. this.expectations[method] = [];
  1640. var mockObject = this;
  1641. sinon.wrapMethod(this.object, method, function () {
  1642. return mockObject.invokeMethod(method, this, arguments);
  1643. });
  1644. push.call(this.proxies, method);
  1645. }
  1646. var expectation = sinon.expectation.create(method);
  1647. push.call(this.expectations[method], expectation);
  1648. return expectation;
  1649. },
  1650. restore: function restore() {
  1651. var object = this.object;
  1652. each(this.proxies, function (proxy) {
  1653. if (typeof object[proxy].restore == "function") {
  1654. object[proxy].restore();
  1655. }
  1656. });
  1657. },
  1658. verify: function verify() {
  1659. var expectations = this.expectations || {};
  1660. var messages = [], met = [];
  1661. each(this.proxies, function (proxy) {
  1662. each(expectations[proxy], function (expectation) {
  1663. if (!expectation.met()) {
  1664. push.call(messages, expectation.toString());
  1665. } else {
  1666. push.call(met, expectation.toString());
  1667. }
  1668. });
  1669. });
  1670. this.restore();
  1671. if (messages.length > 0) {
  1672. sinon.expectation.fail(messages.concat(met).join("\n"));
  1673. } else {
  1674. sinon.expectation.pass(messages.concat(met).join("\n"));
  1675. }
  1676. return true;
  1677. },
  1678. invokeMethod: function invokeMethod(method, thisValue, args) {
  1679. var expectations = this.expectations && this.expectations[method];
  1680. var length = expectations && expectations.length || 0, i;
  1681. for (i = 0; i < length; i += 1) {
  1682. if (!expectations[i].met() &&
  1683. expectations[i].allowsCall(thisValue, args)) {
  1684. return expectations[i].apply(thisValue, args);
  1685. }
  1686. }
  1687. var messages = [], available, exhausted = 0;
  1688. for (i = 0; i < length; i += 1) {
  1689. if (expectations[i].allowsCall(thisValue, args)) {
  1690. available = available || expectations[i];
  1691. } else {
  1692. exhausted += 1;
  1693. }
  1694. push.call(messages, " " + expectations[i].toString());
  1695. }
  1696. if (exhausted === 0) {
  1697. return available.apply(thisValue, args);
  1698. }
  1699. messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({
  1700. proxy: method,
  1701. args: args
  1702. }));
  1703. sinon.expectation.fail(messages.join("\n"));
  1704. }
  1705. };
  1706. }()));
  1707. var times = sinon.timesInWords;
  1708. sinon.expectation = (function () {
  1709. var slice = Array.prototype.slice;
  1710. var _invoke = sinon.spy.invoke;
  1711. function callCountInWords(callCount) {
  1712. if (callCount == 0) {
  1713. return "never called";
  1714. } else {
  1715. return "called " + times(callCount);
  1716. }
  1717. }
  1718. function expectedCallCountInWords(expectation) {
  1719. var min = expectation.minCalls;
  1720. var max = expectation.maxCalls;
  1721. if (typeof min == "number" && typeof max == "number") {
  1722. var str = times(min);
  1723. if (min != max) {
  1724. str = "at least " + str + " and at most " + times(max);
  1725. }
  1726. return str;
  1727. }
  1728. if (typeof min == "number") {
  1729. return "at least " + times(min);
  1730. }
  1731. return "at most " + times(max);
  1732. }
  1733. function receivedMinCalls(expectation) {
  1734. var hasMinLimit = typeof expectation.minCalls == "number";
  1735. return !hasMinLimit || expectation.callCount >= expectation.minCalls;
  1736. }
  1737. function receivedMaxCalls(expectation) {
  1738. if (typeof expectation.maxCalls != "number") {
  1739. return false;
  1740. }
  1741. return expectation.callCount == expectation.maxCalls;
  1742. }
  1743. return {
  1744. minCalls: 1,
  1745. maxCalls: 1,
  1746. create: function create(methodName) {
  1747. var expectation = sinon.extend(sinon.stub.create(), sinon.expectation);
  1748. delete expectation.create;
  1749. expectation.method = methodName;
  1750. return expectation;
  1751. },
  1752. invoke: function invoke(func, thisValue, args) {
  1753. this.verifyCallAllowed(thisValue, args);
  1754. return _invoke.apply(this, arguments);
  1755. },
  1756. atLeast: function atLeast(num) {
  1757. if (typeof num != "number") {
  1758. throw new TypeError("'" + num + "' is not number");
  1759. }
  1760. if (!this.limitsSet) {
  1761. this.maxCalls = null;
  1762. this.limitsSet = true;
  1763. }
  1764. this.minCalls = num;
  1765. return this;
  1766. },
  1767. atMost: function atMost(num) {
  1768. if (typeof num != "number") {
  1769. throw new TypeError("'" + num + "' is not number");
  1770. }
  1771. if (!this.limitsSet) {
  1772. this.minCalls = null;
  1773. this.limitsSet = true;
  1774. }
  1775. this.maxCalls = num;
  1776. return this;
  1777. },
  1778. never: function never() {
  1779. return this.exactly(0);
  1780. },
  1781. once: function once() {
  1782. return this.exactly(1);
  1783. },
  1784. twice: function twice() {
  1785. return this.exactly(2);
  1786. },
  1787. thrice: function thrice() {
  1788. return this.exactly(3);
  1789. },
  1790. exactly: function exactly(num) {
  1791. if (typeof num != "number") {
  1792. throw new TypeError("'" + num + "' is not a number");
  1793. }
  1794. this.atLeast(num);
  1795. return this.atMost(num);
  1796. },
  1797. met: function met() {
  1798. return !this.failed && receivedMinCalls(this);
  1799. },
  1800. verifyCallAllowed: function verifyCallAllowed(thisValue, args) {
  1801. if (receivedMaxCalls(this)) {
  1802. this.failed = true;
  1803. sinon.expectation.fail(this.method + " already called " + times(this.maxCalls));
  1804. }
  1805. if ("expectedThis" in this && this.expectedThis !== thisValue) {
  1806. sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " +
  1807. this.expectedThis);
  1808. }
  1809. if (!("expectedArguments" in this)) {
  1810. return;
  1811. }
  1812. if (!args) {
  1813. sinon.expectation.fail(this.method + " received no arguments, expected " +
  1814. this.expectedArguments.join());
  1815. }
  1816. if (args.length < this.expectedArguments.length) {
  1817. sinon.expectation.fail(this.method + " received too few arguments (" + args.join() +
  1818. "), expected " + this.expectedArguments.join());
  1819. }
  1820. if (this.expectsExactArgCount &&
  1821. args.length != this.expectedArguments.length) {
  1822. sinon.expectation.fail(this.method + " received too many arguments (" + args.join() +
  1823. "), expected " + this.expectedArguments.join());
  1824. }
  1825. for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
  1826. if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
  1827. sinon.expectation.fail(this.method + " received wrong arguments (" + args.join() +
  1828. "), expected " + this.expectedArguments.join());
  1829. }
  1830. }
  1831. },
  1832. allowsCall: function allowsCall(thisValue, args) {
  1833. if (this.met() && receivedMaxCalls(this)) {
  1834. return false;
  1835. }
  1836. if ("expectedThis" in this && this.expectedThis !== thisValue) {
  1837. return false;
  1838. }
  1839. if (!("expectedArguments" in this)) {
  1840. return true;
  1841. }
  1842. args = args || [];
  1843. if (args.length < this.expectedArguments.length) {
  1844. return false;
  1845. }
  1846. if (this.expectsExactArgCount &&
  1847. args.length != this.expectedArguments.length) {
  1848. return false;
  1849. }
  1850. for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
  1851. if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
  1852. return false;
  1853. }
  1854. }
  1855. return true;
  1856. },
  1857. withArgs: function withArgs() {
  1858. this.expectedArguments = slice.call(arguments);
  1859. return this;
  1860. },
  1861. withExactArgs: function withExactArgs() {
  1862. this.withArgs.apply(this, arguments);
  1863. this.expectsExactArgCount = true;
  1864. return this;
  1865. },
  1866. on: function on(thisValue) {
  1867. this.expectedThis = thisValue;
  1868. return this;
  1869. },
  1870. toString: function () {
  1871. var args = (this.expectedArguments || []).slice();
  1872. if (!this.expectsExactArgCount) {
  1873. push.call(args, "[...]");
  1874. }
  1875. var callStr = sinon.spyCall.toString.call({
  1876. proxy: this.method, args: args
  1877. });
  1878. var message = callStr.replace(", [...", "[, ...") + " " +
  1879. expectedCallCountInWords(this);
  1880. if (this.met()) {
  1881. return "Expectation met: " + message;
  1882. }
  1883. return "Expected " + message + " (" +
  1884. callCountInWords(this.callCount) + ")";
  1885. },
  1886. verify: function verify() {
  1887. if (!this.met()) {
  1888. sinon.expectation.fail(this.toString());
  1889. } else {
  1890. sinon.expectation.pass(this.toString());
  1891. }
  1892. return true;
  1893. },
  1894. pass: function(message) {
  1895. sinon.assert.pass(message);
  1896. },
  1897. fail: function (message) {
  1898. var exception = new Error(message);
  1899. exception.name = "ExpectationError";
  1900. throw exception;
  1901. }
  1902. };
  1903. }());
  1904. if (commonJSModule) {
  1905. module.exports = mock;
  1906. } else {
  1907. sinon.mock = mock;
  1908. }
  1909. }(typeof sinon == "object" && sinon || null));
  1910. /**
  1911. * @depend ../sinon.js
  1912. * @depend stub.js
  1913. * @depend mock.js
  1914. */
  1915. /*jslint eqeqeq: false, onevar: false, forin: true*/
  1916. /*global module, require, sinon*/
  1917. /**
  1918. * Collections of stubs, spies and mocks.
  1919. *
  1920. * @author Christian Johansen (christian@cjohansen.no)
  1921. * @license BSD
  1922. *
  1923. * Copyright (c) 2010-2011 Christian Johansen
  1924. */
  1925. (function (sinon) {
  1926. var commonJSModule = typeof module == "object" && typeof require == "function";
  1927. var push = [].push;
  1928. var hasOwnProperty = Object.prototype.hasOwnProperty;
  1929. if (!sinon && commonJSModule) {
  1930. sinon = require("../sinon");
  1931. }
  1932. if (!sinon) {
  1933. return;
  1934. }
  1935. function getFakes(fakeCollection) {
  1936. if (!fakeCollection.fakes) {
  1937. fakeCollection.fakes = [];
  1938. }
  1939. return fakeCollection.fakes;
  1940. }
  1941. function each(fakeCollection, method) {
  1942. var fakes = getFakes(fakeCollection);
  1943. for (var i = 0, l = fakes.length; i < l; i += 1) {
  1944. if (typeof fakes[i][method] == "function") {
  1945. fakes[i][method]();
  1946. }
  1947. }
  1948. }
  1949. function compact(fakeCollection) {
  1950. var fakes = getFakes(fakeCollection);
  1951. var i = 0;
  1952. while (i < fakes.length) {
  1953. fakes.splice(i, 1);
  1954. }
  1955. }
  1956. var collection = {
  1957. verify: function resolve() {
  1958. each(this, "verify");
  1959. },
  1960. restore: function restore() {
  1961. each(this, "restore");
  1962. compact(this);
  1963. },
  1964. verifyAndRestore: function verifyAndRestore() {
  1965. var exception;
  1966. try {
  1967. this.verify();
  1968. } catch (e) {
  1969. exception = e;
  1970. }
  1971. this.restore();
  1972. if (exception) {
  1973. throw exception;
  1974. }
  1975. },
  1976. add: function add(fake) {
  1977. push.call(getFakes(this), fake);
  1978. return fake;
  1979. },
  1980. spy: function spy() {
  1981. return this.add(sinon.spy.apply(sinon, arguments));
  1982. },
  1983. stub: function stub(object, property, value) {
  1984. if (property) {
  1985. var original = object[property];
  1986. if (typeof original != "function") {
  1987. if (!hasOwnProperty.call(object, property)) {
  1988. throw new TypeError("Cannot stub non-existent own property " + property);
  1989. }
  1990. object[property] = value;
  1991. return this.add({
  1992. restore: function () {
  1993. object[property] = original;
  1994. }
  1995. });
  1996. }
  1997. }
  1998. if (!property && !!object && typeof object == "object") {
  1999. var stubbedObj = sinon.stub.apply(sinon, arguments);
  2000. for (var prop in stubbedObj) {
  2001. if (typeof stubbedObj[prop] === "function") {
  2002. this.add(stubbedObj[prop]);
  2003. }
  2004. }
  2005. return stubbedObj;
  2006. }
  2007. return this.add(sinon.stub.apply(sinon, arguments));
  2008. },
  2009. mock: function mock() {
  2010. return this.add(sinon.mock.apply(sinon, arguments));
  2011. },
  2012. inject: function inject(obj) {
  2013. var col = this;
  2014. obj.spy = function () {
  2015. return col.spy.apply(col, arguments);
  2016. };
  2017. obj.stub = function () {
  2018. return col.stub.apply(col, arguments);
  2019. };
  2020. obj.mock = function () {
  2021. return col.mock.apply(col, arguments);
  2022. };
  2023. return obj;
  2024. }
  2025. };
  2026. if (commonJSModule) {
  2027. module.exports = collection;
  2028. } else {
  2029. sinon.collection = collection;
  2030. }
  2031. }(typeof sinon == "object" && sinon || null));
  2032. /*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/
  2033. /*global module, require, window*/
  2034. /**
  2035. * Fake timer API
  2036. * setTimeout
  2037. * setInterval
  2038. * clearTimeout
  2039. * clearInterval
  2040. * tick
  2041. * reset
  2042. * Date
  2043. *
  2044. * Inspired by jsUnitMockTimeOut from JsUnit
  2045. *
  2046. * @author Christian Johansen (christian@cjohansen.no)
  2047. * @license BSD
  2048. *
  2049. * Copyright (c) 2010-2011 Christian Johansen
  2050. */
  2051. if (typeof sinon == "undefined") {
  2052. var sinon = {};
  2053. }
  2054. (function (global) {
  2055. var id = 1;
  2056. function addTimer(args, recurring) {
  2057. if (args.length === 0) {
  2058. throw new Error("Function requires at least 1 parameter");
  2059. }
  2060. var toId = id++;
  2061. var delay = args[1] || 0;
  2062. if (!this.timeouts) {
  2063. this.timeouts = {};
  2064. }
  2065. this.timeouts[toId] = {
  2066. id: toId,
  2067. func: args[0],
  2068. callAt: this.now + delay,
  2069. invokeArgs: Array.prototype.slice.call(args, 2)
  2070. };
  2071. if (recurring === true) {
  2072. this.timeouts[toId].interval = delay;
  2073. }
  2074. return toId;
  2075. }
  2076. function parseTime(str) {
  2077. if (!str) {
  2078. return 0;
  2079. }
  2080. var strings = str.split(":");
  2081. var l = strings.length, i = l;
  2082. var ms = 0, parsed;
  2083. if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
  2084. throw new Error("tick only understands numbers and 'h:m:s'");
  2085. }
  2086. while (i--) {
  2087. parsed = parseInt(strings[i], 10);
  2088. if (parsed >= 60) {
  2089. throw new Error("Invalid time " + str);
  2090. }
  2091. ms += parsed * Math.pow(60, (l - i - 1));
  2092. }
  2093. return ms * 1000;
  2094. }
  2095. function createObject(object) {
  2096. var newObject;
  2097. if (Object.create) {
  2098. newObject = Object.create(object);
  2099. } else {
  2100. var F = function () {};
  2101. F.prototype = object;
  2102. newObject = new F();
  2103. }
  2104. newObject.Date.clock = newObject;
  2105. return newObject;
  2106. }
  2107. sinon.clock = {
  2108. now: 0,
  2109. create: function create(now) {
  2110. var clock = createObject(this);
  2111. if (typeof now == "number") {
  2112. clock.now = now;
  2113. }
  2114. if (!!now && typeof now == "object") {
  2115. throw new TypeError("now should be milliseconds since UNIX epoch");
  2116. }
  2117. return clock;
  2118. },
  2119. setTimeout: function setTimeout(callback, timeout) {
  2120. return addTimer.call(this, arguments, false);
  2121. },
  2122. clearTimeout: function clearTimeout(timerId) {
  2123. if (!this.timeouts) {
  2124. this.timeouts = [];
  2125. }
  2126. if (timerId in this.timeouts) {
  2127. delete this.timeouts[timerId];
  2128. }
  2129. },
  2130. setInterval: function setInterval(callback, timeout) {
  2131. return addTimer.call(this, arguments, true);
  2132. },
  2133. clearInterval: function clearInterval(timerId) {
  2134. this.clearTimeout(timerId);
  2135. },
  2136. tick: function tick(ms) {
  2137. ms = typeof ms == "number" ? ms : parseTime(ms);
  2138. var tickFrom = this.now, tickTo = this.now + ms, previous = this.now;
  2139. var timer = this.firstTimerInRange(tickFrom, tickTo);
  2140. var firstException;
  2141. while (timer && tickFrom <= tickTo) {
  2142. if (this.timeouts[timer.id]) {
  2143. tickFrom = this.now = timer.callAt;
  2144. try {
  2145. this.callTimer(timer);
  2146. } catch (e) {
  2147. firstException = firstException || e;
  2148. }
  2149. }
  2150. timer = this.firstTimerInRange(previous, tickTo);
  2151. previous = tickFrom;
  2152. }
  2153. this.now = tickTo;
  2154. if (firstException) {
  2155. throw firstException;
  2156. }
  2157. },
  2158. firstTimerInRange: function (from, to) {
  2159. var timer, smallest, originalTimer;
  2160. for (var id in this.timeouts) {
  2161. if (this.timeouts.hasOwnProperty(id)) {
  2162. if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) {
  2163. continue;
  2164. }
  2165. if (!smallest || this.timeouts[id].callAt < smallest) {
  2166. originalTimer = this.timeouts[id];
  2167. smallest = this.timeouts[id].callAt;
  2168. timer = {
  2169. func: this.timeouts[id].func,
  2170. callAt: this.timeouts[id].callAt,
  2171. interval: this.timeouts[id].interval,
  2172. id: this.timeouts[id].id,
  2173. invokeArgs: this.timeouts[id].invokeArgs
  2174. };
  2175. }
  2176. }
  2177. }
  2178. return timer || null;
  2179. },
  2180. callTimer: function (timer) {
  2181. if (typeof timer.interval == "number") {
  2182. this.timeouts[timer.id].callAt += timer.interval;
  2183. } else {
  2184. delete this.timeouts[timer.id];
  2185. }
  2186. try {
  2187. if (typeof timer.func == "function") {
  2188. timer.func.apply(null, timer.invokeArgs);
  2189. } else {
  2190. eval(timer.func);
  2191. }
  2192. } catch (e) {
  2193. var exception = e;
  2194. }
  2195. if (!this.timeouts[timer.id]) {
  2196. if (exception) {
  2197. throw exception;
  2198. }
  2199. return;
  2200. }
  2201. if (exception) {
  2202. throw exception;
  2203. }
  2204. },
  2205. reset: function reset() {
  2206. this.timeouts = {};
  2207. },
  2208. Date: (function () {
  2209. var NativeDate = Date;
  2210. function ClockDate(year, month, date, hour, minute, second, ms) {
  2211. // Defensive and verbose to avoid potential harm in passing
  2212. // explicit undefined when user does not pass argument
  2213. switch (arguments.length) {
  2214. case 0:
  2215. return new NativeDate(ClockDate.clock.now);
  2216. case 1:
  2217. return new NativeDate(year);
  2218. case 2:
  2219. return new NativeDate(year, month);
  2220. case 3:
  2221. return new NativeDate(year, month, date);
  2222. case 4:
  2223. return new NativeDate(year, month, date, hour);
  2224. case 5:
  2225. return new NativeDate(year, month, date, hour, minute);
  2226. case 6:
  2227. return new NativeDate(year, month, date, hour, minute, second);
  2228. default:
  2229. return new NativeDate(year, month, date, hour, minute, second, ms);
  2230. }
  2231. }
  2232. return mirrorDateProperties(ClockDate, NativeDate);
  2233. }())
  2234. };
  2235. function mirrorDateProperties(target, source) {
  2236. if (source.now) {
  2237. target.now = function now() {
  2238. return target.clock.now;
  2239. };
  2240. } else {
  2241. delete target.now;
  2242. }
  2243. if (source.toSource) {
  2244. target.toSource = function toSource() {
  2245. return source.toSource();
  2246. };
  2247. } else {
  2248. delete target.toSource;
  2249. }
  2250. target.toString = function toString() {
  2251. return source.toString();
  2252. };
  2253. target.prototype = source.prototype;
  2254. target.parse = source.parse;
  2255. target.UTC = source.UTC;
  2256. target.prototype.toUTCString = source.prototype.toUTCString;
  2257. return target;
  2258. }
  2259. var methods = ["Date", "setTimeout", "setInterval",
  2260. "clearTimeout", "clearInterval"];
  2261. function restore() {
  2262. var method;
  2263. for (var i = 0, l = this.methods.length; i < l; i++) {
  2264. method = this.methods[i];
  2265. if (global[method].hadOwnProperty) {
  2266. global[method] = this["_" + method];
  2267. } else {
  2268. delete global[method];
  2269. }
  2270. }
  2271. // Prevent multiple executions which will completely remove these props
  2272. this.methods = [];
  2273. }
  2274. function stubGlobal(method, clock) {
  2275. clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method);
  2276. clock["_" + method] = global[method];
  2277. if (method == "Date") {
  2278. var date = mirrorDateProperties(clock[method], global[method]);
  2279. global[method] = date;
  2280. } else {
  2281. global[method] = function () {
  2282. return clock[method].apply(clock, arguments);
  2283. };
  2284. for (var prop in clock[method]) {
  2285. if (clock[method].hasOwnProperty(prop)) {
  2286. global[method][prop] = clock[method][prop];
  2287. }
  2288. }
  2289. }
  2290. global[method].clock = clock;
  2291. }
  2292. sinon.useFakeTimers = function useFakeTimers(now) {
  2293. var clock = sinon.clock.create(now);
  2294. clock.restore = restore;
  2295. clock.methods = Array.prototype.slice.call(arguments,
  2296. typeof now == "number" ? 1 : 0);
  2297. if (clock.methods.length === 0) {
  2298. clock.methods = methods;
  2299. }
  2300. for (var i = 0, l = clock.methods.length; i < l; i++) {
  2301. stubGlobal(clock.methods[i], clock);
  2302. }
  2303. return clock;
  2304. };
  2305. }(typeof global != "undefined" && typeof global !== "function" ? global : this));
  2306. sinon.timers = {
  2307. setTimeout: setTimeout,
  2308. clearTimeout: clearTimeout,
  2309. setInterval: setInterval,
  2310. clearInterval: clearInterval,
  2311. Date: Date
  2312. };
  2313. if (typeof module == "object" && typeof require == "function") {
  2314. module.exports = sinon;
  2315. }
  2316. /*jslint eqeqeq: false, onevar: false*/
  2317. /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
  2318. /**
  2319. * Minimal Event interface implementation
  2320. *
  2321. * Original implementation by Sven Fuchs: https://gist.github.com/995028
  2322. * Modifications and tests by Christian Johansen.
  2323. *
  2324. * @author Sven Fuchs (svenfuchs@artweb-design.de)
  2325. * @author Christian Johansen (christian@cjohansen.no)
  2326. * @license BSD
  2327. *
  2328. * Copyright (c) 2011 Sven Fuchs, Christian Johansen
  2329. */
  2330. if (typeof sinon == "undefined") {
  2331. this.sinon = {};
  2332. }
  2333. (function () {
  2334. var push = [].push;
  2335. sinon.Event = function Event(type, bubbles, cancelable) {
  2336. this.initEvent(type, bubbles, cancelable);
  2337. };
  2338. sinon.Event.prototype = {
  2339. initEvent: function(type, bubbles, cancelable) {
  2340. this.type = type;
  2341. this.bubbles = bubbles;
  2342. this.cancelable = cancelable;
  2343. },
  2344. stopPropagation: function () {},
  2345. preventDefault: function () {
  2346. this.defaultPrevented = true;
  2347. }
  2348. };
  2349. sinon.EventTarget = {
  2350. addEventListener: function addEventListener(event, listener, useCapture) {
  2351. this.eventListeners = this.eventListeners || {};
  2352. this.eventListeners[event] = this.eventListeners[event] || [];
  2353. push.call(this.eventListeners[event], listener);
  2354. },
  2355. removeEventListener: function removeEventListener(event, listener, useCapture) {
  2356. var listeners = this.eventListeners && this.eventListeners[event] || [];
  2357. for (var i = 0, l = listeners.length; i < l; ++i) {
  2358. if (listeners[i] == listener) {
  2359. return listeners.splice(i, 1);
  2360. }
  2361. }
  2362. },
  2363. dispatchEvent: function dispatchEvent(event) {
  2364. var type = event.type;
  2365. var listeners = this.eventListeners && this.eventListeners[type] || [];
  2366. for (var i = 0; i < listeners.length; i++) {
  2367. if (typeof listeners[i] == "function") {
  2368. listeners[i].call(this, event);
  2369. } else {
  2370. listeners[i].handleEvent(event);
  2371. }
  2372. }
  2373. return !!event.defaultPrevented;
  2374. }
  2375. };
  2376. }());
  2377. /**
  2378. * @depend ../../sinon.js
  2379. * @depend event.js
  2380. */
  2381. /*jslint eqeqeq: false, onevar: false*/
  2382. /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/
  2383. /**
  2384. * Fake XMLHttpRequest object
  2385. *
  2386. * @author Christian Johansen (christian@cjohansen.no)
  2387. * @license BSD
  2388. *
  2389. * Copyright (c) 2010-2011 Christian Johansen
  2390. */
  2391. if (typeof sinon == "undefined") {
  2392. this.sinon = {};
  2393. }
  2394. sinon.xhr = { XMLHttpRequest: this.XMLHttpRequest };
  2395. // wrapper for global
  2396. (function(global) {
  2397. var xhr = sinon.xhr;
  2398. xhr.GlobalXMLHttpRequest = global.XMLHttpRequest;
  2399. xhr.GlobalActiveXObject = global.ActiveXObject;
  2400. xhr.supportsActiveX = typeof xhr.GlobalActiveXObject != "undefined";
  2401. xhr.supportsXHR = typeof xhr.GlobalXMLHttpRequest != "undefined";
  2402. xhr.workingXHR = xhr.supportsXHR ? xhr.GlobalXMLHttpRequest : xhr.supportsActiveX
  2403. ? function() { return new xhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false;
  2404. /*jsl:ignore*/
  2405. var unsafeHeaders = {
  2406. "Accept-Charset": true,
  2407. "Accept-Encoding": true,
  2408. "Connection": true,
  2409. "Content-Length": true,
  2410. "Cookie": true,
  2411. "Cookie2": true,
  2412. "Content-Transfer-Encoding": true,
  2413. "Date": true,
  2414. "Expect": true,
  2415. "Host": true,
  2416. "Keep-Alive": true,
  2417. "Referer": true,
  2418. "TE": true,
  2419. "Trailer": true,
  2420. "Transfer-Encoding": true,
  2421. "Upgrade": true,
  2422. "User-Agent": true,
  2423. "Via": true
  2424. };
  2425. /*jsl:end*/
  2426. function FakeXMLHttpRequest() {
  2427. this.readyState = FakeXMLHttpRequest.UNSENT;
  2428. this.requestHeaders = {};
  2429. this.requestBody = null;
  2430. this.status = 0;
  2431. this.statusText = "";
  2432. if (typeof FakeXMLHttpRequest.onCreate == "function") {
  2433. FakeXMLHttpRequest.onCreate(this);
  2434. }
  2435. }
  2436. function verifyState(xhr) {
  2437. if (xhr.readyState !== FakeXMLHttpRequest.OPENED) {
  2438. throw new Error("INVALID_STATE_ERR");
  2439. }
  2440. if (xhr.sendFlag) {
  2441. throw new Error("INVALID_STATE_ERR");
  2442. }
  2443. }
  2444. // filtering to enable a white-list version of Sinon FakeXhr,
  2445. // where whitelisted requests are passed through to real XHR
  2446. function each(collection, callback) {
  2447. if (!collection) return;
  2448. for (var i = 0, l = collection.length; i < l; i += 1) {
  2449. callback(collection[i]);
  2450. }
  2451. }
  2452. function some(collection, callback) {
  2453. for (var index = 0; index < collection.length; index++) {
  2454. if(callback(collection[index]) === true) return true;
  2455. };
  2456. return false;
  2457. }
  2458. // largest arity in XHR is 5 - XHR#open
  2459. var apply = function(obj,method,args) {
  2460. switch(args.length) {
  2461. case 0: return obj[method]();
  2462. case 1: return obj[method](args[0]);
  2463. case 2: return obj[method](args[0],args[1]);
  2464. case 3: return obj[method](args[0],args[1],args[2]);
  2465. case 4: return obj[method](args[0],args[1],args[2],args[3]);
  2466. case 5: return obj[method](args[0],args[1],args[2],args[3],args[4]);
  2467. };
  2468. };
  2469. FakeXMLHttpRequest.filters = [];
  2470. FakeXMLHttpRequest.addFilter = function(fn) {
  2471. this.filters.push(fn)
  2472. };
  2473. var IE6Re = /MSIE 6/;
  2474. FakeXMLHttpRequest.defake = function(fakeXhr,xhrArgs) {
  2475. var xhr = new sinon.xhr.workingXHR();
  2476. each(["open","setRequestHeader","send","abort","getResponseHeader",
  2477. "getAllResponseHeaders","addEventListener","overrideMimeType","removeEventListener"],
  2478. function(method) {
  2479. fakeXhr[method] = function() {
  2480. return apply(xhr,method,arguments);
  2481. };
  2482. });
  2483. var copyAttrs = function(args) {
  2484. each(args, function(attr) {
  2485. try {
  2486. fakeXhr[attr] = xhr[attr]
  2487. } catch(e) {
  2488. if(!IE6Re.test(navigator.userAgent)) throw e;
  2489. }
  2490. });
  2491. };
  2492. var stateChange = function() {
  2493. fakeXhr.readyState = xhr.readyState;
  2494. if(xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) {
  2495. copyAttrs(["status","statusText"]);
  2496. }
  2497. if(xhr.readyState >= FakeXMLHttpRequest.LOADING) {
  2498. copyAttrs(["responseText"]);
  2499. }
  2500. if(xhr.readyState === FakeXMLHttpRequest.DONE) {
  2501. copyAttrs(["responseXML"]);
  2502. }
  2503. if(fakeXhr.onreadystatechange) fakeXhr.onreadystatechange.call(fakeXhr);
  2504. };
  2505. if(xhr.addEventListener) {
  2506. for(var event in fakeXhr.eventListeners) {
  2507. if(fakeXhr.eventListeners.hasOwnProperty(event)) {
  2508. each(fakeXhr.eventListeners[event],function(handler) {
  2509. xhr.addEventListener(event, handler);
  2510. });
  2511. }
  2512. }
  2513. xhr.addEventListener("readystatechange",stateChange);
  2514. } else {
  2515. xhr.onreadystatechange = stateChange;
  2516. }
  2517. apply(xhr,"open",xhrArgs);
  2518. };
  2519. FakeXMLHttpRequest.useFilters = false;
  2520. function verifyRequestSent(xhr) {
  2521. if (xhr.readyState == FakeXMLHttpRequest.DONE) {
  2522. throw new Error("Request done");
  2523. }
  2524. }
  2525. function verifyHeadersReceived(xhr) {
  2526. if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) {
  2527. throw new Error("No headers received");
  2528. }
  2529. }
  2530. function verifyResponseBodyType(body) {
  2531. if (typeof body != "string") {
  2532. var error = new Error("Attempted to respond to fake XMLHttpRequest with " +
  2533. body + ", which is not a string.");
  2534. error.name = "InvalidBodyException";
  2535. throw error;
  2536. }
  2537. }
  2538. sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, {
  2539. async: true,
  2540. open: function open(method, url, async, username, password) {
  2541. this.method = method;
  2542. this.url = url;
  2543. this.async = typeof async == "boolean" ? async : true;
  2544. this.username = username;
  2545. this.password = password;
  2546. this.responseText = null;
  2547. this.responseXML = null;
  2548. this.requestHeaders = {};
  2549. this.sendFlag = false;
  2550. if(sinon.FakeXMLHttpRequest.useFilters === true) {
  2551. var xhrArgs = arguments;
  2552. var defake = some(FakeXMLHttpRequest.filters,function(filter) {
  2553. return filter.apply(this,xhrArgs)
  2554. });
  2555. if (defake) {
  2556. return sinon.FakeXMLHttpRequest.defake(this,arguments);
  2557. }
  2558. }
  2559. this.readyStateChange(FakeXMLHttpRequest.OPENED);
  2560. },
  2561. readyStateChange: function readyStateChange(state) {
  2562. this.readyState = state;
  2563. if (typeof this.onreadystatechange == "function") {
  2564. try {
  2565. this.onreadystatechange();
  2566. } catch (e) {
  2567. sinon.logError("Fake XHR onreadystatechange handler", e);
  2568. }
  2569. }
  2570. this.dispatchEvent(new sinon.Event("readystatechange"));
  2571. },
  2572. setRequestHeader: function setRequestHeader(header, value) {
  2573. verifyState(this);
  2574. if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) {
  2575. throw new Error("Refused to set unsafe header \"" + header + "\"");
  2576. }
  2577. if (this.requestHeaders[header]) {
  2578. this.requestHeaders[header] += "," + value;
  2579. } else {
  2580. this.requestHeaders[header] = value;
  2581. }
  2582. },
  2583. // Helps testing
  2584. setResponseHeaders: function setResponseHeaders(headers) {
  2585. this.responseHeaders = {};
  2586. for (var header in headers) {
  2587. if (headers.hasOwnProperty(header)) {
  2588. this.responseHeaders[header] = headers[header];
  2589. }
  2590. }
  2591. if (this.async) {
  2592. this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED);
  2593. }
  2594. },
  2595. // Currently treats ALL data as a DOMString (i.e. no Document)
  2596. send: function send(data) {
  2597. verifyState(this);
  2598. if (!/^(get|head)$/i.test(this.method)) {
  2599. if (this.requestHeaders["Content-Type"]) {
  2600. var value = this.requestHeaders["Content-Type"].split(";");
  2601. this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8";
  2602. } else {
  2603. this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8";
  2604. }
  2605. this.requestBody = data;
  2606. }
  2607. this.errorFlag = false;
  2608. this.sendFlag = this.async;
  2609. this.readyStateChange(FakeXMLHttpRequest.OPENED);
  2610. if (typeof this.onSend == "function") {
  2611. this.onSend(this);
  2612. }
  2613. },
  2614. abort: function abort() {
  2615. this.aborted = true;
  2616. this.responseText = null;
  2617. this.errorFlag = true;
  2618. this.requestHeaders = {};
  2619. if (this.readyState > sinon.FakeXMLHttpRequest.UNSENT && this.sendFlag) {
  2620. this.readyStateChange(sinon.FakeXMLHttpRequest.DONE);
  2621. this.sendFlag = false;
  2622. }
  2623. this.readyState = sinon.FakeXMLHttpRequest.UNSENT;
  2624. },
  2625. getResponseHeader: function getResponseHeader(header) {
  2626. if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
  2627. return null;
  2628. }
  2629. if (/^Set-Cookie2?$/i.test(header)) {
  2630. return null;
  2631. }
  2632. header = header.toLowerCase();
  2633. for (var h in this.responseHeaders) {
  2634. if (h.toLowerCase() == header) {
  2635. return this.responseHeaders[h];
  2636. }
  2637. }
  2638. return null;
  2639. },
  2640. getAllResponseHeaders: function getAllResponseHeaders() {
  2641. if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
  2642. return "";
  2643. }
  2644. var headers = "";
  2645. for (var header in this.responseHeaders) {
  2646. if (this.responseHeaders.hasOwnProperty(header) &&
  2647. !/^Set-Cookie2?$/i.test(header)) {
  2648. headers += header + ": " + this.responseHeaders[header] + "\r\n";
  2649. }
  2650. }
  2651. return headers;
  2652. },
  2653. setResponseBody: function setResponseBody(body) {
  2654. verifyRequestSent(this);
  2655. verifyHeadersReceived(this);
  2656. verifyResponseBodyType(body);
  2657. var chunkSize = this.chunkSize || 10;
  2658. var index = 0;
  2659. this.responseText = "";
  2660. do {
  2661. if (this.async) {
  2662. this.readyStateChange(FakeXMLHttpRequest.LOADING);
  2663. }
  2664. this.responseText += body.substring(index, index + chunkSize);
  2665. index += chunkSize;
  2666. } while (index < body.length);
  2667. var type = this.getResponseHeader("Content-Type");
  2668. if (this.responseText &&
  2669. (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
  2670. try {
  2671. this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText);
  2672. } catch (e) {
  2673. // Unable to parse XML - no biggie
  2674. }
  2675. }
  2676. if (this.async) {
  2677. this.readyStateChange(FakeXMLHttpRequest.DONE);
  2678. } else {
  2679. this.readyState = FakeXMLHttpRequest.DONE;
  2680. }
  2681. },
  2682. respond: function respond(status, headers, body) {
  2683. this.setResponseHeaders(headers || {});
  2684. this.status = typeof status == "number" ? status : 200;
  2685. this.statusText = FakeXMLHttpRequest.statusCodes[this.status];
  2686. this.setResponseBody(body || "");
  2687. }
  2688. });
  2689. sinon.extend(FakeXMLHttpRequest, {
  2690. UNSENT: 0,
  2691. OPENED: 1,
  2692. HEADERS_RECEIVED: 2,
  2693. LOADING: 3,
  2694. DONE: 4
  2695. });
  2696. // Borrowed from JSpec
  2697. FakeXMLHttpRequest.parseXML = function parseXML(text) {
  2698. var xmlDoc;
  2699. if (typeof DOMParser != "undefined") {
  2700. var parser = new DOMParser();
  2701. xmlDoc = parser.parseFromString(text, "text/xml");
  2702. } else {
  2703. xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  2704. xmlDoc.async = "false";
  2705. xmlDoc.loadXML(text);
  2706. }
  2707. return xmlDoc;
  2708. };
  2709. FakeXMLHttpRequest.statusCodes = {
  2710. 100: "Continue",
  2711. 101: "Switching Protocols",
  2712. 200: "OK",
  2713. 201: "Created",
  2714. 202: "Accepted",
  2715. 203: "Non-Authoritative Information",
  2716. 204: "No Content",
  2717. 205: "Reset Content",
  2718. 206: "Partial Content",
  2719. 300: "Multiple Choice",
  2720. 301: "Moved Permanently",
  2721. 302: "Found",
  2722. 303: "See Other",
  2723. 304: "Not Modified",
  2724. 305: "Use Proxy",
  2725. 307: "Temporary Redirect",
  2726. 400: "Bad Request",
  2727. 401: "Unauthorized",
  2728. 402: "Payment Required",
  2729. 403: "Forbidden",
  2730. 404: "Not Found",
  2731. 405: "Method Not Allowed",
  2732. 406: "Not Acceptable",
  2733. 407: "Proxy Authentication Required",
  2734. 408: "Request Timeout",
  2735. 409: "Conflict",
  2736. 410: "Gone",
  2737. 411: "Length Required",
  2738. 412: "Precondition Failed",
  2739. 413: "Request Entity Too Large",
  2740. 414: "Request-URI Too Long",
  2741. 415: "Unsupported Media Type",
  2742. 416: "Requested Range Not Satisfiable",
  2743. 417: "Expectation Failed",
  2744. 422: "Unprocessable Entity",
  2745. 500: "Internal Server Error",
  2746. 501: "Not Implemented",
  2747. 502: "Bad Gateway",
  2748. 503: "Service Unavailable",
  2749. 504: "Gateway Timeout",
  2750. 505: "HTTP Version Not Supported"
  2751. };
  2752. sinon.useFakeXMLHttpRequest = function () {
  2753. sinon.FakeXMLHttpRequest.restore = function restore(keepOnCreate) {
  2754. if (xhr.supportsXHR) {
  2755. global.XMLHttpRequest = xhr.GlobalXMLHttpRequest;
  2756. }
  2757. if (xhr.supportsActiveX) {
  2758. global.ActiveXObject = xhr.GlobalActiveXObject;
  2759. }
  2760. delete sinon.FakeXMLHttpRequest.restore;
  2761. if (keepOnCreate !== true) {
  2762. delete sinon.FakeXMLHttpRequest.onCreate;
  2763. }
  2764. };
  2765. if (xhr.supportsXHR) {
  2766. global.XMLHttpRequest = sinon.FakeXMLHttpRequest;
  2767. }
  2768. if (xhr.supportsActiveX) {
  2769. global.ActiveXObject = function ActiveXObject(objId) {
  2770. if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) {
  2771. return new sinon.FakeXMLHttpRequest();
  2772. }
  2773. return new xhr.GlobalActiveXObject(objId);
  2774. };
  2775. }
  2776. return sinon.FakeXMLHttpRequest;
  2777. };
  2778. sinon.FakeXMLHttpRequest = FakeXMLHttpRequest;
  2779. })(this);
  2780. if (typeof module == "object" && typeof require == "function") {
  2781. module.exports = sinon;
  2782. }
  2783. /**
  2784. * @depend fake_xml_http_request.js
  2785. */
  2786. /*jslint eqeqeq: false, onevar: false, regexp: false, plusplus: false*/
  2787. /*global module, require, window*/
  2788. /**
  2789. * The Sinon "server" mimics a web server that receives requests from
  2790. * sinon.FakeXMLHttpRequest and provides an API to respond to those requests,
  2791. * both synchronously and asynchronously. To respond synchronuously, canned
  2792. * answers have to be provided upfront.
  2793. *
  2794. * @author Christian Johansen (christian@cjohansen.no)
  2795. * @license BSD
  2796. *
  2797. * Copyright (c) 2010-2011 Christian Johansen
  2798. */
  2799. if (typeof sinon == "undefined") {
  2800. var sinon = {};
  2801. }
  2802. sinon.fakeServer = (function () {
  2803. var push = [].push;
  2804. function F() {}
  2805. function create(proto) {
  2806. F.prototype = proto;
  2807. return new F();
  2808. }
  2809. function responseArray(handler) {
  2810. var response = handler;
  2811. if (Object.prototype.toString.call(handler) != "[object Array]") {
  2812. response = [200, {}, handler];
  2813. }
  2814. if (typeof response[2] != "string") {
  2815. throw new TypeError("Fake server response body should be string, but was " +
  2816. typeof response[2]);
  2817. }
  2818. return response;
  2819. }
  2820. var wloc = typeof window !== "undefined" ? window.location : {};
  2821. var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host);
  2822. function matchOne(response, reqMethod, reqUrl) {
  2823. var rmeth = response.method;
  2824. var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase();
  2825. var url = response.url;
  2826. var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl));
  2827. return matchMethod && matchUrl;
  2828. }
  2829. function match(response, request) {
  2830. var requestMethod = this.getHTTPMethod(request);
  2831. var requestUrl = request.url;
  2832. if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) {
  2833. requestUrl = requestUrl.replace(rCurrLoc, "");
  2834. }
  2835. if (matchOne(response, this.getHTTPMethod(request), requestUrl)) {
  2836. if (typeof response.response == "function") {
  2837. var ru = response.url;
  2838. var args = [request].concat(!ru ? [] : requestUrl.match(ru).slice(1));
  2839. return response.response.apply(response, args);
  2840. }
  2841. return true;
  2842. }
  2843. return false;
  2844. }
  2845. return {
  2846. create: function () {
  2847. var server = create(this);
  2848. this.xhr = sinon.useFakeXMLHttpRequest();
  2849. server.requests = [];
  2850. this.xhr.onCreate = function (xhrObj) {
  2851. server.addRequest(xhrObj);
  2852. };
  2853. return server;
  2854. },
  2855. addRequest: function addRequest(xhrObj) {
  2856. var server = this;
  2857. push.call(this.requests, xhrObj);
  2858. xhrObj.onSend = function () {
  2859. server.handleRequest(this);
  2860. };
  2861. if (this.autoRespond && !this.responding) {
  2862. setTimeout(function () {
  2863. server.responding = false;
  2864. server.respond();
  2865. }, this.autoRespondAfter || 10);
  2866. this.responding = true;
  2867. }
  2868. },
  2869. getHTTPMethod: function getHTTPMethod(request) {
  2870. if (this.fakeHTTPMethods && /post/i.test(request.method)) {
  2871. var matches = (request.requestBody || "").match(/_method=([^\b;]+)/);
  2872. return !!matches ? matches[1] : request.method;
  2873. }
  2874. return request.method;
  2875. },
  2876. handleRequest: function handleRequest(xhr) {
  2877. if (xhr.async) {
  2878. if (!this.queue) {
  2879. this.queue = [];
  2880. }
  2881. push.call(this.queue, xhr);
  2882. } else {
  2883. this.processRequest(xhr);
  2884. }
  2885. },
  2886. respondWith: function respondWith(method, url, body) {
  2887. if (arguments.length == 1 && typeof method != "function") {
  2888. this.response = responseArray(method);
  2889. return;
  2890. }
  2891. if (!this.responses) { this.responses = []; }
  2892. if (arguments.length == 1) {
  2893. body = method;
  2894. url = method = null;
  2895. }
  2896. if (arguments.length == 2) {
  2897. body = url;
  2898. url = method;
  2899. method = null;
  2900. }
  2901. push.call(this.responses, {
  2902. method: method,
  2903. url: url,
  2904. response: typeof body == "function" ? body : responseArray(body)
  2905. });
  2906. },
  2907. respond: function respond() {
  2908. if (arguments.length > 0) this.respondWith.apply(this, arguments);
  2909. var queue = this.queue || [];
  2910. var request;
  2911. while(request = queue.shift()) {
  2912. this.processRequest(request);
  2913. }
  2914. },
  2915. processRequest: function processRequest(request) {
  2916. try {
  2917. if (request.aborted) {
  2918. return;
  2919. }
  2920. var response = this.response || [404, {}, ""];
  2921. if (this.responses) {
  2922. for (var i = 0, l = this.responses.length; i < l; i++) {
  2923. if (match.call(this, this.responses[i], request)) {
  2924. response = this.responses[i].response;
  2925. break;
  2926. }
  2927. }
  2928. }
  2929. if (request.readyState != 4) {
  2930. request.respond(response[0], response[1], response[2]);
  2931. }
  2932. } catch (e) {
  2933. sinon.logError("Fake server request processing", e);
  2934. }
  2935. },
  2936. restore: function restore() {
  2937. return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments);
  2938. }
  2939. };
  2940. }());
  2941. if (typeof module == "object" && typeof require == "function") {
  2942. module.exports = sinon;
  2943. }
  2944. /**
  2945. * @depend fake_server.js
  2946. * @depend fake_timers.js
  2947. */
  2948. /*jslint browser: true, eqeqeq: false, onevar: false*/
  2949. /*global sinon*/
  2950. /**
  2951. * Add-on for sinon.fakeServer that automatically handles a fake timer along with
  2952. * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery
  2953. * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead,
  2954. * it polls the object for completion with setInterval. Dispite the direct
  2955. * motivation, there is nothing jQuery-specific in this file, so it can be used
  2956. * in any environment where the ajax implementation depends on setInterval or
  2957. * setTimeout.
  2958. *
  2959. * @author Christian Johansen (christian@cjohansen.no)
  2960. * @license BSD
  2961. *
  2962. * Copyright (c) 2010-2011 Christian Johansen
  2963. */
  2964. (function () {
  2965. function Server() {}
  2966. Server.prototype = sinon.fakeServer;
  2967. sinon.fakeServerWithClock = new Server();
  2968. sinon.fakeServerWithClock.addRequest = function addRequest(xhr) {
  2969. if (xhr.async) {
  2970. if (typeof setTimeout.clock == "object") {
  2971. this.clock = setTimeout.clock;
  2972. } else {
  2973. this.clock = sinon.useFakeTimers();
  2974. this.resetClock = true;
  2975. }
  2976. if (!this.longestTimeout) {
  2977. var clockSetTimeout = this.clock.setTimeout;
  2978. var clockSetInterval = this.clock.setInterval;
  2979. var server = this;
  2980. this.clock.setTimeout = function (fn, timeout) {
  2981. server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
  2982. return clockSetTimeout.apply(this, arguments);
  2983. };
  2984. this.clock.setInterval = function (fn, timeout) {
  2985. server.longestTimeout = Math.max(timeout, server.longestTimeout || 0);
  2986. return clockSetInterval.apply(this, arguments);
  2987. };
  2988. }
  2989. }
  2990. return sinon.fakeServer.addRequest.call(this, xhr);
  2991. };
  2992. sinon.fakeServerWithClock.respond = function respond() {
  2993. var returnVal = sinon.fakeServer.respond.apply(this, arguments);
  2994. if (this.clock) {
  2995. this.clock.tick(this.longestTimeout || 0);
  2996. this.longestTimeout = 0;
  2997. if (this.resetClock) {
  2998. this.clock.restore();
  2999. this.resetClock = false;
  3000. }
  3001. }
  3002. return returnVal;
  3003. };
  3004. sinon.fakeServerWithClock.restore = function restore() {
  3005. if (this.clock) {
  3006. this.clock.restore();
  3007. }
  3008. return sinon.fakeServer.restore.apply(this, arguments);
  3009. };
  3010. }());
  3011. /**
  3012. * @depend ../sinon.js
  3013. * @depend collection.js
  3014. * @depend util/fake_timers.js
  3015. * @depend util/fake_server_with_clock.js
  3016. */
  3017. /*jslint eqeqeq: false, onevar: false, plusplus: false*/
  3018. /*global require, module*/
  3019. /**
  3020. * Manages fake collections as well as fake utilities such as Sinon's
  3021. * timers and fake XHR implementation in one convenient object.
  3022. *
  3023. * @author Christian Johansen (christian@cjohansen.no)
  3024. * @license BSD
  3025. *
  3026. * Copyright (c) 2010-2011 Christian Johansen
  3027. */
  3028. if (typeof module == "object" && typeof require == "function") {
  3029. var sinon = require("../sinon");
  3030. sinon.extend(sinon, require("./util/fake_timers"));
  3031. }
  3032. (function () {
  3033. var push = [].push;
  3034. function exposeValue(sandbox, config, key, value) {
  3035. if (!value) {
  3036. return;
  3037. }
  3038. if (config.injectInto) {
  3039. config.injectInto[key] = value;
  3040. } else {
  3041. push.call(sandbox.args, value);
  3042. }
  3043. }
  3044. function prepareSandboxFromConfig(config) {
  3045. var sandbox = sinon.create(sinon.sandbox);
  3046. if (config.useFakeServer) {
  3047. if (typeof config.useFakeServer == "object") {
  3048. sandbox.serverPrototype = config.useFakeServer;
  3049. }
  3050. sandbox.useFakeServer();
  3051. }
  3052. if (config.useFakeTimers) {
  3053. if (typeof config.useFakeTimers == "object") {
  3054. sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers);
  3055. } else {
  3056. sandbox.useFakeTimers();
  3057. }
  3058. }
  3059. return sandbox;
  3060. }
  3061. sinon.sandbox = sinon.extend(sinon.create(sinon.collection), {
  3062. useFakeTimers: function useFakeTimers() {
  3063. this.clock = sinon.useFakeTimers.apply(sinon, arguments);
  3064. return this.add(this.clock);
  3065. },
  3066. serverPrototype: sinon.fakeServer,
  3067. useFakeServer: function useFakeServer() {
  3068. var proto = this.serverPrototype || sinon.fakeServer;
  3069. if (!proto || !proto.create) {
  3070. return null;
  3071. }
  3072. this.server = proto.create();
  3073. return this.add(this.server);
  3074. },
  3075. inject: function (obj) {
  3076. sinon.collection.inject.call(this, obj);
  3077. if (this.clock) {
  3078. obj.clock = this.clock;
  3079. }
  3080. if (this.server) {
  3081. obj.server = this.server;
  3082. obj.requests = this.server.requests;
  3083. }
  3084. return obj;
  3085. },
  3086. create: function (config) {
  3087. if (!config) {
  3088. return sinon.create(sinon.sandbox);
  3089. }
  3090. var sandbox = prepareSandboxFromConfig(config);
  3091. sandbox.args = sandbox.args || [];
  3092. var prop, value, exposed = sandbox.inject({});
  3093. if (config.properties) {
  3094. for (var i = 0, l = config.properties.length; i < l; i++) {
  3095. prop = config.properties[i];
  3096. value = exposed[prop] || prop == "sandbox" && sandbox;
  3097. exposeValue(sandbox, config, prop, value);
  3098. }
  3099. } else {
  3100. exposeValue(sandbox, config, "sandbox", value);
  3101. }
  3102. return sandbox;
  3103. }
  3104. });
  3105. sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer;
  3106. if (typeof module == "object" && typeof require == "function") {
  3107. module.exports = sinon.sandbox;
  3108. }
  3109. }());
  3110. /**
  3111. * @depend ../sinon.js
  3112. * @depend stub.js
  3113. * @depend mock.js
  3114. * @depend sandbox.js
  3115. */
  3116. /*jslint eqeqeq: false, onevar: false, forin: true, plusplus: false*/
  3117. /*global module, require, sinon*/
  3118. /**
  3119. * Test function, sandboxes fakes
  3120. *
  3121. * @author Christian Johansen (christian@cjohansen.no)
  3122. * @license BSD
  3123. *
  3124. * Copyright (c) 2010-2011 Christian Johansen
  3125. */
  3126. (function (sinon) {
  3127. var commonJSModule = typeof module == "object" && typeof require == "function";
  3128. if (!sinon && commonJSModule) {
  3129. sinon = require("../sinon");
  3130. }
  3131. if (!sinon) {
  3132. return;
  3133. }
  3134. function test(callback) {
  3135. var type = typeof callback;
  3136. if (type != "function") {
  3137. throw new TypeError("sinon.test needs to wrap a test function, got " + type);
  3138. }
  3139. return function () {
  3140. var config = sinon.getConfig(sinon.config);
  3141. config.injectInto = config.injectIntoThis && this || config.injectInto;
  3142. var sandbox = sinon.sandbox.create(config);
  3143. var exception, result;
  3144. var args = Array.prototype.slice.call(arguments).concat(sandbox.args);
  3145. try {
  3146. result = callback.apply(this, args);
  3147. } catch (e) {
  3148. exception = e;
  3149. }
  3150. if (typeof exception !== "undefined") {
  3151. sandbox.restore();
  3152. throw exception;
  3153. }
  3154. else {
  3155. sandbox.verifyAndRestore();
  3156. }
  3157. return result;
  3158. };
  3159. }
  3160. test.config = {
  3161. injectIntoThis: true,
  3162. injectInto: null,
  3163. properties: ["spy", "stub", "mock", "clock", "server", "requests"],
  3164. useFakeTimers: true,
  3165. useFakeServer: true
  3166. };
  3167. if (commonJSModule) {
  3168. module.exports = test;
  3169. } else {
  3170. sinon.test = test;
  3171. }
  3172. }(typeof sinon == "object" && sinon || null));
  3173. /**
  3174. * @depend ../sinon.js
  3175. * @depend test.js
  3176. */
  3177. /*jslint eqeqeq: false, onevar: false, eqeqeq: false*/
  3178. /*global module, require, sinon*/
  3179. /**
  3180. * Test case, sandboxes all test functions
  3181. *
  3182. * @author Christian Johansen (christian@cjohansen.no)
  3183. * @license BSD
  3184. *
  3185. * Copyright (c) 2010-2011 Christian Johansen
  3186. */
  3187. (function (sinon) {
  3188. var commonJSModule = typeof module == "object" && typeof require == "function";
  3189. if (!sinon && commonJSModule) {
  3190. sinon = require("../sinon");
  3191. }
  3192. if (!sinon || !Object.prototype.hasOwnProperty) {
  3193. return;
  3194. }
  3195. function createTest(property, setUp, tearDown) {
  3196. return function () {
  3197. if (setUp) {
  3198. setUp.apply(this, arguments);
  3199. }
  3200. var exception, result;
  3201. try {
  3202. result = property.apply(this, arguments);
  3203. } catch (e) {
  3204. exception = e;
  3205. }
  3206. if (tearDown) {
  3207. tearDown.apply(this, arguments);
  3208. }
  3209. if (exception) {
  3210. throw exception;
  3211. }
  3212. return result;
  3213. };
  3214. }
  3215. function testCase(tests, prefix) {
  3216. /*jsl:ignore*/
  3217. if (!tests || typeof tests != "object") {
  3218. throw new TypeError("sinon.testCase needs an object with test functions");
  3219. }
  3220. /*jsl:end*/
  3221. prefix = prefix || "test";
  3222. var rPrefix = new RegExp("^" + prefix);
  3223. var methods = {}, testName, property, method;
  3224. var setUp = tests.setUp;
  3225. var tearDown = tests.tearDown;
  3226. for (testName in tests) {
  3227. if (tests.hasOwnProperty(testName)) {
  3228. property = tests[testName];
  3229. if (/^(setUp|tearDown)$/.test(testName)) {
  3230. continue;
  3231. }
  3232. if (typeof property == "function" && rPrefix.test(testName)) {
  3233. method = property;
  3234. if (setUp || tearDown) {
  3235. method = createTest(property, setUp, tearDown);
  3236. }
  3237. methods[testName] = sinon.test(method);
  3238. } else {
  3239. methods[testName] = tests[testName];
  3240. }
  3241. }
  3242. }
  3243. return methods;
  3244. }
  3245. if (commonJSModule) {
  3246. module.exports = testCase;
  3247. } else {
  3248. sinon.testCase = testCase;
  3249. }
  3250. }(typeof sinon == "object" && sinon || null));
  3251. /**
  3252. * @depend ../sinon.js
  3253. * @depend stub.js
  3254. */
  3255. /*jslint eqeqeq: false, onevar: false, nomen: false, plusplus: false*/
  3256. /*global module, require, sinon*/
  3257. /**
  3258. * Assertions matching the test spy retrieval interface.
  3259. *
  3260. * @author Christian Johansen (christian@cjohansen.no)
  3261. * @license BSD
  3262. *
  3263. * Copyright (c) 2010-2011 Christian Johansen
  3264. */
  3265. (function (sinon, global) {
  3266. var commonJSModule = typeof module == "object" && typeof require == "function";
  3267. var slice = Array.prototype.slice;
  3268. var assert;
  3269. if (!sinon && commonJSModule) {
  3270. sinon = require("../sinon");
  3271. }
  3272. if (!sinon) {
  3273. return;
  3274. }
  3275. function verifyIsStub() {
  3276. var method;
  3277. for (var i = 0, l = arguments.length; i < l; ++i) {
  3278. method = arguments[i];
  3279. if (!method) {
  3280. assert.fail("fake is not a spy");
  3281. }
  3282. if (typeof method != "function") {
  3283. assert.fail(method + " is not a function");
  3284. }
  3285. if (typeof method.getCall != "function") {
  3286. assert.fail(method + " is not stubbed");
  3287. }
  3288. }
  3289. }
  3290. function failAssertion(object, msg) {
  3291. object = object || global;
  3292. var failMethod = object.fail || assert.fail;
  3293. failMethod.call(object, msg);
  3294. }
  3295. function mirrorPropAsAssertion(name, method, message) {
  3296. if (arguments.length == 2) {
  3297. message = method;
  3298. method = name;
  3299. }
  3300. assert[name] = function (fake) {
  3301. verifyIsStub(fake);
  3302. var args = slice.call(arguments, 1);
  3303. var failed = false;
  3304. if (typeof method == "function") {
  3305. failed = !method(fake);
  3306. } else {
  3307. failed = typeof fake[method] == "function" ?
  3308. !fake[method].apply(fake, args) : !fake[method];
  3309. }
  3310. if (failed) {
  3311. failAssertion(this, fake.printf.apply(fake, [message].concat(args)));
  3312. } else {
  3313. assert.pass(name);
  3314. }
  3315. };
  3316. }
  3317. function exposedName(prefix, prop) {
  3318. return !prefix || /^fail/.test(prop) ? prop :
  3319. prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1);
  3320. };
  3321. assert = {
  3322. failException: "AssertError",
  3323. fail: function fail(message) {
  3324. var error = new Error(message);
  3325. error.name = this.failException || assert.failException;
  3326. throw error;
  3327. },
  3328. pass: function pass(assertion) {},
  3329. callOrder: function assertCallOrder() {
  3330. verifyIsStub.apply(null, arguments);
  3331. var expected = "", actual = "";
  3332. if (!sinon.calledInOrder(arguments)) {
  3333. try {
  3334. expected = [].join.call(arguments, ", ");
  3335. actual = sinon.orderByFirstCall(slice.call(arguments)).join(", ");
  3336. } catch (e) {
  3337. // If this fails, we'll just fall back to the blank string
  3338. }
  3339. failAssertion(this, "expected " + expected + " to be " +
  3340. "called in order but were called as " + actual);
  3341. } else {
  3342. assert.pass("callOrder");
  3343. }
  3344. },
  3345. callCount: function assertCallCount(method, count) {
  3346. verifyIsStub(method);
  3347. if (method.callCount != count) {
  3348. var msg = "expected %n to be called " + sinon.timesInWords(count) +
  3349. " but was called %c%C";
  3350. failAssertion(this, method.printf(msg));
  3351. } else {
  3352. assert.pass("callCount");
  3353. }
  3354. },
  3355. expose: function expose(target, options) {
  3356. if (!target) {
  3357. throw new TypeError("target is null or undefined");
  3358. }
  3359. var o = options || {};
  3360. var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix;
  3361. var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail;
  3362. for (var method in this) {
  3363. if (method != "export" && (includeFail || !/^(fail)/.test(method))) {
  3364. target[exposedName(prefix, method)] = this[method];
  3365. }
  3366. }
  3367. return target;
  3368. }
  3369. };
  3370. mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called");
  3371. mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; },
  3372. "expected %n to not have been called but was called %c%C");
  3373. mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C");
  3374. mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C");
  3375. mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C");
  3376. mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t");
  3377. mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t");
  3378. mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new");
  3379. mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new");
  3380. mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C");
  3381. mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C");
  3382. mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C");
  3383. mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C");
  3384. mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C");
  3385. mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C");
  3386. mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C");
  3387. mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C");
  3388. mirrorPropAsAssertion("threw", "%n did not throw exception%C");
  3389. mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C");
  3390. if (commonJSModule) {
  3391. module.exports = assert;
  3392. } else {
  3393. sinon.assert = assert;
  3394. }
  3395. }(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : global));
  3396. return sinon;}.call(typeof window != 'undefined' && window || {}));